Download tasks/data/forward/4subsea__evapy.4baf6a9/instruction.md from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 69.2 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/4subsea__evapy.4baf6a9/instruction.md
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/forward/4subsea__evapy.4baf6a9/instruction.md
-
curl -L -o instruction.md https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/forward/4subsea__evapy.4baf6a9/instruction.md
4subsea/evapy
Project Overview
evapy_4s (published from the 4Subsea/evapy repository) is an open-source Python package for extreme value analysis (EVA) of time series. Aimed at scientific and engineering users — particularly those working with measured or simulated environmental and structural response data such as ocean and offshore measurements — it provides the statistical machinery needed to characterize the tails of a time series and estimate the probability of extreme events. The library is intentionally small and focused: it depends only on numpy and scipy, supports Python 3.5+, and is distributed under the MIT license. Functionally, evapy_4s is organized around three layers. First, time series analysis utilities extract the events of interest from a raw signal, offering zero-upcrossing analysis and peak detection with declustering, which convert a continuous record into samples of independent peaks and cycles. Second, a set of peak distributions fits parametric models to those peak samples, including the Rayleigh distribution and the Weibull distribution, which supports three-parameter fitting through the location parameter and is exposed as both weibull and weibull_min, plus the generalized exponential tail model. Third, maxima distributions model the extremes of the process, providing the classical Gumbel distribution (gumbel and gumbel_max) and the first-order ACER method (Average Conditional Exceedance Rate, due to Naess et al.), a well-known approach for extreme-value prediction from short records. Architecturally, these models are implemented as frozen generator classes in a _continuous_distns module that deliberately mirrors SciPy's rv_continuous design — each supplying pdf, cdf, ppf, survival and moment methods — and are re-exported through a distributions facade, while a small _optimize helper computes residual errors during fitting. Together these components form a pipeline: extract peaks/cycles from a time series, fit a tail model, and extrapolate to long-return-period maxima. The repository is structured as a single installable package (evapy_4s) with accompanying tests, tox-based test configuration, and documentation built around Jupyter notebook usage examples that demonstrate the workflows end to end. Development status is beta; the README also outlines planned additions such as truncated Rayleigh and truncated Weibull 3p peak distributions for subsequent releases.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
Submission Constraints (read carefully — the evaluation depends on these)
This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:
Do NOT create or modify any files under the test directories (e.g.
tests/,test/,testing/, or files namedtest_*.py/conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.Your package MUST be importable by the name the tests use. The hidden tests
importyour package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a validpyproject.toml/setup.py/setup.cfgand lay out your modules so thatpip install -e .succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.
Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- Project root:
/workspace/repoat runtime; the submitted repository root is.. - Package/distribution name:
evapy_4s - Package roots:
. - Install strategy:
editable-install - Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- Provision commands:
python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel programgen_pip_install python3 -m pip install 'setuptools>=61,<82' wheel ( programgen_install_report="$(mktemp)" trap 'rm -f "$programgen_install_report"' EXIT SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" ) - Runtime setup:
{ SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; } - Project root for installation:
. - Build-version environment:
SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0,PDM_BUILD_SCM_VERSION=0.0.0,POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0,UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 - Test directory:
tests - Test command:
bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_distributions.py tests/test_evstats.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_distributions.py tests/test_evstats.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_distributions.py tests/test_evstats.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?' - Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.
Environment & Project Structure
- Language: python
- Build system: python
- Test command:
bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_distributions.py tests/test_evstats.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_distributions.py tests/test_evstats.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_distributions.py tests/test_evstats.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?
Project Directory Structure
.gitignore
LICENSE
MANIFEST.in
README.md
docs/conf.py
docs/distributions.rst
docs/index.rst
docs/nb_examples.rst
docs/notebooks/Basic statistical analysis of time series.ipynb
docs/ts_anal.rst
evapy_4s/__init__.py
evapy_4s/_continuous_distns.py
evapy_4s/_optimize.py
evapy_4s/distributions.py
evapy_4s/evstats.py
setup.py
tox.ini
API Usage Guide
Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.
Capability: Package interface for extreme value analysis
Package interface for extreme value analysis
Purpose
The public surface of evapy_4s is deliberately tiny: two importable modules that together expose the whole extreme-value toolkit. evapy_4s.distributions re-exports the fitted random-variable objects (the tail and maxima models plus the ACER-lineage Gumbel-like model), and evapy_4s.evstats holds the time-series statistics helpers that turn a raw signal into the peak/cycle samples those models consume. Importing evapy_4s itself executes from . import evstats and from . import distributions, so a bare import evapy_4s is enough to make both submodule names attributes of the package — but the canonical, test-checked access paths are the fully qualified ones shown below.
Import contract and the name map
The facade in evapy_4s.distributions performs exactly one thing: it imports the private _continuous_distns module and re-exports seven module-level singletons:
rayleigh— Rayleigh peak model (2-parameter; the generator class israyleigh_gen, "A Rayleigh continuous random variable").weibullandweibull_min— two names bound to the same Weibull machinery built onfrechet_r_gen("A Frechet right class continuous random variable"); this is the 3-parameter Weibull, fitted through an explicit location parameter.gumbelandgumbel_max— two names for the right-skewed Gumbel maxima model built ongumbel_r_gen("A right-skewed Gumbel continuous random variable").genexptail— the generalized exponential tail model for peak overshoots.acer_o1— "A generalized Gumbel-like continuous random variable" (shape parametersc,qn): a distribution instance whose tail form and fitting descend from the first-order ACER (Average Conditional Exceedance Rate) method (Naess et al.).
Two consequences matter for re-implementation and for tests:
- Instances, not classes, are the public API of the facade.
dist.rayleighis a ready-to-use frozen generator instance in the style of a SciPyrv_continuoussingleton. The underlying generator classes (rayleigh_gen,frechet_r_gen,gumbel_r_gen) live inevapy_4s._continuous_distnsand are not re-exported throughdistributions; reaching them requires the private module path. Tests that exercise the capability importimport evapy_4s.distributions as distand touch the seven names above — the facade must not add, drop, or rename any of them. - Alias pairs must stay aliases.
weibull/weibull_minandgumbel/gumbel_maxexist so both a scientific naming convention and a SciPy-flavored naming convention resolve. In the reference they are separate frozen instances of the same generator class —weibull = frechet_r_gen(a=0.0, name='weibull')vsweibull_min = frechet_r_gen(a=0.0, name='weibull_min'), and likewisegumbel = gumbel_r_gen(name='gumbel')vsgumbel_max = gumbel_r_gen(name='gumbel_max')— so object identity is False and thenameattributes differ even in the repository itself. The requirement is therefore behavioral equivalence only: both names of a pair must behave identically (divergent behavior is a failure), while distinct instances with differingnameattributes are expected and correct.
evapy_4s.evstats is a plain module (no __all__ gate) exposing at minimum:
argupcross(x, x_up=0.0)— "Find the upcrossing of 1D time series data": the public wrapper returning the indices of the samples at or belowx_upimmediately preceding each upward crossing (inclusive comparison: indexiqualifies whenx[i] <= x_up < x[i+1]); the crossing sample itself sits one position after each returned index._argupcross(x, x_up)— "Find the cross ups of 1D time series data": the private worker that does the actual scan and returns a same-length boolean mask; the public wrapper converts that mask via flatnonzero into the index array above. The public function's defaultx_up=0.0is the only default among this evidenced pair; the private function takes the threshold positionally with no default, so callers must always supply it. Both are module-level attributes, so the underscore name is importable (evapy_4s.evstats._argupcross) even though it is not part of the supported surface.
from evapy_4s import evstats and import evapy_4s.distributions as dist are the two exact import forms the evidence records; support both. The first form does not depend on eager initialization: Python's from-import falls back to importing the named submodule whenever the attribute is missing on a package that has __path__, so it succeeds even for a lazy package. The eager imports in __init__ matter for the other access path — they are what make a bare import evapy_4s bind evapy_4s.evstats and evapy_4s.distributions as package attributes — and that is the test-sensitive distinction.
How the pieces fit in a workflow
The intended pipeline is: signal → upcrossing/peak extraction (evstats) → parametric tail fit (distributions) → long-return-period extrapolation.
- Extract events. Feed the measured series to
evstats.argupcross(default threshold 0.0) to segment the record at upward crossings; each returned index marks the last sample at or below the threshold, the crossing sample is the next position, and consecutive upcrossings delimit individual cycles from which peaks (half-cycle maxima) are collected. The result is a sample of independent peaks — declustering is what makes the independence assumption of the tail models tenable. - Fit a peak distribution. Pass the peak sample to
dist.rayleigh,dist.weibull(the same 3-parameter model is also reachable asdist.weibull_min), ordist.genexptail. The Weibull path is the flexible one: the location parameter turns the 2-parameter Weibull into a 3-parameter model that can anchor the fit above the sample minimum, which is what tail fitting to regime-limited offshore response data usually requires.dist.rayleighanddist.weibullfit through the inherited SciPy MLE.dist.genexptaildoes not: its generator (gen_exp_tail_gen) overrides_penalized_nnlfto minimize the_residual_errorsupplied by the small internal_optimizehelper, because no MLE exists for the model — the fit is a least-squares procedure, and locking the location parameter is the recommended practice. The_optimizehelper is internal and not re-exported. - Extrapolate maxima. For extremes of the process itself, use
dist.gumbel/dist.gumbel_maxon block maxima.dist.acer_o1is likewise consumed as a distribution, never as a raw-record processor: fit it to a sample of extremes, then evaluatepdf/cdf/ppfexactly as for the other singletons. Its first-order ACER lineage (Naess et al.) — the method that makes extreme-value prediction from short records feasible by working with conditional exceedance rates rather than requiring many independent maxima — motivates its Gumbel-like tail form and its least-squares fit (same_optimizemachinery asgenexptail); the short-record advantage lives in that functional form, not in any in-package scanning of the raw time series.
Every distribution instance mirrors the SciPy rv_continuous design: it supplies pdf, cdf, ppf, survival (sf), and moment methods, plus fitting. Code that works against the SciPy idiom (evaluate dist.gumbel.pdf(x, *pars), invert ppf for return levels) transfers unchanged, which is precisely why the internals were written as frozen generator classes rather than ad-hoc fit functions.
State, ordering, defaults, edge cases
- No hidden global state. The singletons are stateless value objects; all sample-specific information enters through method arguments. Calling
dist.weibulltwice on different data shares nothing. - Import order is fixed by the package.
evapy_4s/__init__importsevstatsfirst anddistributionssecond, anddistributionsimports_continuous_distnsat module load. There is therefore no valid ordering in whichdist.rayleighexists whileevapy_4s.evstatsdoes not, or vice versa; a successfulimport evapy_4s.distributionsimplies the whole package initialized. - Defaults are minimal by design. Among the evidenced pair
argupcross/_argupcross, the only default is the public wrapper'sx_up=0.0. Zero is the physically sensible upcrossing level for wave/response signals, but for pre-processed or offset series the caller must pass the threshold explicitly — nothing infers it. (Beyond that pair,evstatsalso providesargrelmax/argrelmax_decluster, andargrelmax_declustercarries the samex_up=0.default.) - 1-D only, and the no-crossing sentinel.
argupcrossis documented for 1-D time series; higher-rank input is outside the contract. A series containing no upcrossings does not yield an empty result:argupcrossreturns the sentinelarray([0])— the index of the first value — so downstream peak collection must recognize the sentinel rather than read it as zero events. Truly empty input is outside the working contract too: the shifted comparison inside_argupcrosscannot be evaluated on an empty series and raises rather than returning an empty set. - Alias discipline. Because
weibullandweibull_min(and likewisegumbel/gumbel_max) are distinct frozen instances of one generator class, tests should assert behavioral equivalence, not object identity or equal attributes; the pair'snameattributes differ by design. Keep both names backed by the same generator and behaviorally identical.
Test-sensitive behavior summary
- The seven facade names (
rayleigh,weibull,weibull_min,gumbel,gumbel_max,genexptail,acer_o1) must be importable viaimport evapy_4s.distributions as distand attribute-accessible as written. from evapy_4s import evstatsmust succeed, andevapy_4s.evstats.argupcross/evapy_4s.evstats._argupcrossmust exist with the documented signatures (x_updefaulted to0.0only on the public wrapper).- The generator classes
rayleigh_gen,frechet_r_gen,gumbel_r_genmust exist inevapy_4s._continuous_distnswith the documented docstrings, each providingpdf,cdf,ppf, survival, and moment methods. - Package import must not raise: importing
evapy_4spulls in both submodules eagerly, so any import-time error in_continuous_distnssurfaces immediately and fails collection.
Exact API Reference
evapy_4s._continuous_distns.rayleigh_gen
- Import Path:
from evapy_4s._continuous_distns import rayleigh_gen - Signature:
class rayleigh_gen
- Behavior: A Rayleigh continuous random variable.
evapy_4s._continuous_distns.frechet_r_gen
- Import Path:
from evapy_4s._continuous_distns import frechet_r_gen - Signature:
class frechet_r_gen
- Behavior: A Frechet right class continuous random variable.
evapy_4s._continuous_distns.gumbel_r_gen
- Import Path:
from evapy_4s._continuous_distns import gumbel_r_gen - Signature:
class gumbel_r_gen
- Behavior: A right-skewed Gumbel continuous random variable.
evapy_4s.evstats.argupcross
- Import Path:
from evapy_4s.evstats import argupcross - Required Test Import Paths:
- evapy_4s.evstats.argupcross
- Exact Test Import Statements:
- from evapy_4s import evstats
- Signature:
def argupcross(x, x_up=0.0)
- Behavior: Find the upcrossing of 1D time series data.
evapy_4s.distributions
- Import Path:
from evapy_4s import distributions - Required Test Import Paths:
- evapy_4s.distributions
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: module
- Behavior: Module required during hidden-test collection.
evapy_4s._continuous_distns.acer_o1
- Import Path:
from evapy_4s._continuous_distns import acer_o1 - Required Test Import Paths:
- evapy_4s.distributions.acer_o1
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
acer_o1: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s._continuous_distns.genexptail
- Import Path:
from evapy_4s._continuous_distns import genexptail - Required Test Import Paths:
- evapy_4s.distributions.genexptail
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
genexptail: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s._continuous_distns.gumbel
- Import Path:
from evapy_4s._continuous_distns import gumbel - Required Test Import Paths:
- evapy_4s.distributions.gumbel
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
gumbel: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s._continuous_distns.gumbel_max
- Import Path:
from evapy_4s._continuous_distns import gumbel_max - Required Test Import Paths:
- evapy_4s.distributions.gumbel_max
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
gumbel_max: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s._continuous_distns.rayleigh
- Import Path:
from evapy_4s._continuous_distns import rayleigh - Required Test Import Paths:
- evapy_4s.distributions.rayleigh
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
rayleigh: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s._continuous_distns.weibull
- Import Path:
from evapy_4s._continuous_distns import weibull - Required Test Import Paths:
- evapy_4s.distributions.weibull
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
weibull: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s._continuous_distns.weibull_min
- Import Path:
from evapy_4s._continuous_distns import weibull_min - Required Test Import Paths:
- evapy_4s.distributions.weibull_min
- Exact Test Import Statements:
- import evapy_4s.distributions as dist
- Kind: constant
- Signature:
weibull_min: Any
- Behavior: Module-level value required by the test import contract.
evapy_4s.evstats
- Import Path:
from evapy_4s import evstats - Required Test Import Paths:
- evapy_4s.evstats
- Exact Test Import Statements:
- from evapy_4s import evstats
- Kind: module
- Behavior: Module required during hidden-test collection.
evapy_4s.evstats._argupcross
- Import Path:
from evapy_4s.evstats import _argupcross - Required Test Import Paths:
- evapy_4s.evstats._argupcross
- Exact Test Import Statements:
- from evapy_4s import evstats
- Kind: function
- Signature:
def _argupcross(x, x_up)
- Behavior: Find the cross ups of 1D time series data.
Capability: Peak detection and declustering of time series
Purpose and mental model
This capability converts a continuous 1D record into index samples of its crests, at two granularities. argrelmax reports every relative maximum, the fine-grained view you want when each individual crest is a sample for tail fitting. argrelmax_decluster reports at most one peak per upcrossing cycle: it obtains the level upcrossings of the signal from the package's argupcross utility (the same machinery as the zero/level-upcrossing function documented elsewhere in the package), splits the record at those upcrossings, and keeps only the largest sample of each upcrossing-to-upcrossing cycle. This declustering step is what turns a noisy, clustered crest population into roughly independent peaks — the input assumption of the Rayleigh/Weibull peak-distribution layer that normally consumes these indices. The private kernel _argrelmax is the vectorized boolean mask underneath argrelmax and is the reason that function is faster than the generic windowed logic of scipy.signal.argrelmax. argrelmax_decluster shares none of that machinery: it is built solely from the level-upcrossing utility, np.split, and per-segment np.argmax, with no dependency on the peak mask — so the mask explains neither its construction nor its speed.
All three functions are pure: they never mutate x, keep no state, and return new numpy arrays of indices (or booleans, for the kernel). Results are always in ascending index order by construction.
How the pieces relate
_argrelmax(x) is the primitive. It marks position i as a peak exactly when the sample rises strictly from the left (x[i] > x[i-1]) and does not rise to the right (x[i] >= x[i+1]). The asymmetry matters: the left comparison is strict, the right one is not. Consequences:
- The first and last positions are always
False— a crest must have a sample on each side. - A plateau of equal maxima resolves to its leftmost sample, because the plateau's first element passes both tests while its successors fail the strict rise.
- A monotonically increasing or decreasing series yields an all-
Falsemask. - The return value is a boolean array of the same length as
x, not a list of positions.
argrelmax(x) is np.flatnonzero applied to that mask, so it returns integer indices of all crests. It never returns an empty array: if no relative maximum exists (e.g., a purely monotonic record), it falls back to np.asarray([np.argmax(x)]) — the index of the global maximum, leftmost on ties. For a ramp 0,1,2,3,4,5 the answer is [5], i.e., the last index, not the first. This fallback is a deliberate contract: downstream code can index peak samples without checking for emptiness.
argrelmax_decluster(x, x_up=0.) composes two steps, neither of which involves the peak mask. First it obtains upcrossing indices — the positions of samples at or below x_up that are immediately followed by a sample strictly above x_up, i.e., x[i] <= x_up before and x[i+1] > x_up after. Note that this is the opposite strictness split from the peak mask, which is strict before (>) and non-strict after (>=); in particular, ties here resolve to the last at-or-below-level sample rather than the leftmost. If no upcrossing exists, that step yields [0]. Then it splits x at those indices with np.split and, for every interior segment — those starting at an upcrossing index and ending just before the next one — reports the segment's argmax plus the segment's start offset. The result is one index per complete upcrossing-to-upcrossing cycle: the largest sample in that cycle.
On the success path every declustered index is a genuine _argrelmax peak, so argrelmax_decluster(x) is always a subset of argrelmax(x). Within a cycle the upcrossing sample is at or below the level while the sample after it is strictly above, so the cycle's leftmost maximizer strictly rises from its left neighbor — it can never be the upcrossing sample itself — and it does not rise to its right, whether against the next in-cycle sample or against the next cycle's at-or-below-level upcrossing sample. A cycle maximum may therefore sit at the segment's last position, immediately before the next dip below the level, and still pass both mask tests. The differences from argrelmax come only from secondary crests dropped within cycles and from the unclosed head and trailing segments: the trailing segment's argmax — index 11 in the example below, the final sample of the record — is an endpoint and hence not a _argrelmax peak, and it is never reported because its cycle is not closed.
Two structural consequences of the np.split design are easy to miss and are exercised by the tests:
- The head of the record before the first upcrossing and, more importantly, the tail after the last upcrossing are discarded. A peak that arrives after the final upcrossing — even a clear one above the level — is never returned, because its cycle is not closed by a subsequent upcrossing.
- Each cycle includes its starting at-or-below-level sample, but that sample can never be the cycle's argmax: the sample immediately after an upcrossing is strictly above the level, so the cycle maximum always strictly exceeds the upcrossing sample.
The fallback mirrors but differs from argrelmax: when no complete upcrossing pair exists, the function returns np.asarray([np.max([np.argmax(x), x_up])]). With the default x_up=0.0 this is value-equal to argmax(x) (since argmax is never negative), but if a caller passes a positive x_up larger than the argmax index, the returned value is the threshold itself, not an index. The numeric type differs too: the success path yields an integer array, while the fallback path promotes to float64 by default (np.max of the [int, x_up] pair promotes even under the default level). Tests compare by value (np.testing.assert_array_equal), so [5] and [5.0] both pass — but a re-implementation that returns an int here is still value-compatible.
Defaults, ordering, and edge cases
x_updefaults to0.0but any float level works: the tests shift a whole signal by+2.0and passx_up=2.0, producing identical index results to the unshifted case withx_up=0.0. The level is a parameter, not a zero-finding heuristic.- Upcrossing detection treats a sample exactly at
x_upas below the level. A stretch grazing the level and then rising produces one upcrossing at the last at-or-below-level sample; a transition from below the level up to exactly the level (x[i] < x_up,x[i+1] == x_up), like a flat at-level stretch, is not an upcrossing because the following sample must be strictly greater thanx_up. Consecutive equal values above the level never trigger anything until the signal returns to at-or-below the level. - The last sample of
xcan never be an upcrossing (it has no successor), while the first sample can be, whenx[0] <= x_up < x[1]. On a record that never rises above the level, the upcrossing step's own fallback contributes index0, which makes the decluster split produce no interior segments and triggers the decluster fallback described above. - Monotonic input cascades cleanly:
_argrelmaxallFalse,argrelmaxreturns the global-argmax index, decluster returnsmax(argmax(x), x_up).np.argmaxtherefore raises on empty input; the functions are intended for non-empty 1D arrays. Length-1 input is safe and degenerates to the fallbacks. - Despite the docstring's "array-like",
xmust support vectorized elementwise comparison and slicing; numpy arrays are the working input type, and plain Python lists fail on the>between slices. - Tie-breaking is leftmost for every argmax-style mechanism: plateau crests,
np.argmaxin every fallback, and per-segment argmaxes all resolve to the smallest qualifying index. The upcrossing test is the exception — a level-grazing run places its upcrossing at the last at-or-below-level sample — because that follows from the<=-level test, not from argmax tie-breaking.
Typical workflow placement
In the package's EVA pipeline, these functions are the first stage: raw measured or simulated response series in, crest indices out. Use argrelmax when every local crest should enter the peak sample; use argrelmax_decluster when crests riding the same underlying wave or cluster must collapse to one representative per upcrossing cycle. The resulting peak samples feed directly into the package's peak distributions (Rayleigh, Weibull) and onward to the maxima/extreme-value layer. Because argrelmax (and the boolean kernel) guarantee a non-empty result of integer indices (or booleans), callers can uniformly do x[peaks] / x[mask] without special-casing the no-peak situation. The same does not hold for argrelmax_decluster: its fallback array is float-typed by default — indexing with a float array raises IndexError — and when x_up exceeds the argmax index it contains the threshold value itself, which is not a valid index at all; a decluster result must therefore be cast or validated before being used as an indexer. Callers should also be aware that the fallback values are global-argmax (or threshold) positions, not detected events, and the decluster path silently drops the record's head and unclosed trailing cycle.
Exact API Reference
evapy_4s.evstats.argrelmax
- Import Path:
from evapy_4s.evstats import argrelmax - Required Test Import Paths:
- evapy_4s.evstats.argrelmax
- Exact Test Import Statements:
- from evapy_4s import evstats
- Signature:
def argrelmax(x)
- Behavior: Find the relative maxima of 1D time series data.
evapy_4s.evstats.argrelmax_decluster
- Import Path:
from evapy_4s.evstats import argrelmax_decluster - Required Test Import Paths:
- evapy_4s.evstats.argrelmax_decluster
- Exact Test Import Statements:
- from evapy_4s import evstats
- Signature:
def argrelmax_decluster(x, x_up=0.0)
- Behavior: Find the declustred relative maxima of 1D time series data.
evapy_4s.evstats._argrelmax
- Import Path:
from evapy_4s.evstats import _argrelmax - Required Test Import Paths:
- evapy_4s.evstats._argrelmax
- Exact Test Import Statements:
- from evapy_4s import evstats
- Kind: function
- Signature:
def _argrelmax(x)
- Behavior: Find the relative maxima of 1D time series data.
Capability: Generalized exponential tail distribution
genexptail — the generalized exponential tail distribution
Purpose and tail semantics
gen_exp_tail_gen defines the two-shape law behind genexptail, built for the last step of an extreme-value workflow: modelling peaks-over-threshold (POT) tails whose survival function decays exponentially, which places the law in the domain of attraction of the type I (Gumbel) extreme-value distribution. On the support x > 0 the density is
pdf(x; c, q) = c * x**(c - 1) * exp(-x**c + log(q)) = c * x**(c-1) * q * exp(-x**c)
Two properties drive all behaviour:
- Mass factor. The density integrates to
q, not 1. The missing1 - qis the probability at or below the threshold:cdf(0) = 1 - qexactly, andsf(x) = q * exp(-x**c)everywhere on the support.qis read as the fraction of peaks that are exceedances above the threshold carried byloc; a valid law needsc > 0and0 < q <= 1. - Exponential tail.
sfis a pure exponential inx**c, so the level exceeded with probability1/Tsolvesx**c = log(q*T): long return periods extrapolate in closed form, which is what makes the model useful for engineering tail prediction.
With q = 1 the law reduces to a Weibull with shape c and unit scale — a handy sanity anchor when hand-checking numbers.
Where it sits in a workflow
The generator lives in evapy_4s._continuous_distns beside the Rayleigh/Weibull/Gumbel/ACER generators; the supported surface is the distributions facade, which re-exports the singleton instance genexptail (created with lower support bound a = 0). A typical chain: extract independent peaks from a time series (zero-upcrossing or declustered peak detection — the tail model assumes independent peaks, so declustering matters), fit genexptail to the peak sample, then query exceedance probabilities and return levels. The maxima layer (gumbel, acer_o1) answers the same extreme-value question from the other direction: parametric tail fit versus extremal extrapolation of block maxima.
Parameters, freezing, and state
- Method signatures are
(x, c, q, loc=0, scale=1)— shapes positional, location/scale trailing with defaults 0 and 1;fitreturns the tuple in the same order(c, q, loc, scale). Genericrv_continuousloc/scale wrapping applies: evaluate atz = (x - loc)/scaleand divide the pdf byscale. - Unfrozen:
genexptail.pdf(x, c, q)evaluates at explicit shapes; useful when sweeping parameters. - Frozen:
tail = genexptail(c, q, loc=..., scale=...)binds the four parameters; its methods take only the evaluation point (tail.sf,tail.ppf,tail.rvs(size=n, random_state=...)). Frozen objects are cheap, independent, and share no state with the singleton or each other. - The class and singleton are stateless: a freshly constructed
gen_exp_tail_gen()must produce identical method outputs to the singleton — the test suite constructs both and compares them, so any per-instance state or singleton-only special casing breaks that equality. - Arrays broadcast elementwise against the shapes;
naninputs propagate asnanoutputs, never exceptions.
Fitting: least squares, not maximum likelihood
Maximum likelihood does not exist for this law (the docstring says so directly). Instead _penalized_nnlf is overridden and hands scipy's generic fit optimizer a least-squares residual computed by _residual_error from _optimize:
- Standardize the sample and sort it; empirical probabilities use the plotting positions
F_i = (i + 1 - 0.3)/(N + 0.4). - Transform both empirical and model probabilities with
y(F) = log(1/(1 - F)), the log-return-period (standard-exponential) scale that linearizessf— on the model sidey_model = z**c - log q, i.e.-log sf(z). (It is not the reduced-Gumbel variate-log(-log F); substituting that would not reproduce the least-squares residuals.) - Minimize the summed squared residuals over
(c, q, loc, scale), starting from the generic_fitstartguess.
Non-finite behaviour of the objective is part of the contract: scale <= 0 or a failed shape check returns inf; data outside the support (standardized x <= 0 here, or >= b) is dropped and each dropped point adds 10000; a parameter vector shorter than location+scale raises ValueError with the literal message "Not enough input arguments.". Because points at z <= 0 are penalized, a fitted loc always ends up strictly below the sample minimum. Fits are deterministic for a fixed sample — no hidden state, no warm start. The docstring also recommends locking the location parameter (floc) for more robust estimates on real data.
Edge cases and test-sensitive behaviour
- Never use
1 - cdffor tails. The far-tail cdf rounds to 1.0 and its complement collapses to 0._cdfis written withexpm1and_logcdfwithlog1pfor accuracy near 0;_sfis the exact exponentialq*exp(-x**c). Return-period work must go throughsf/isf/logcdf. - Quantile domain. The generic wrapper clamps
p <= 0/p >= 1to the support endpoints, but for0 < p < 1 - qthere is no probability mass above the threshold: the explicit_ppfhas a negative radicand there and yieldsnan.ppf(1 - q)returns exactly the threshold. The same nan region surfaces in the mirrored inverses:isf(p) = ppf(1 - p)isnanforp > q, and genericrvsdraws uniforms and maps them through_ppf, so withq < 1roughly a1 - qfraction of the draws — the uniforms below1 - q— come back asnaninstead of samples. - Invalid shapes are not rejected. The default
_argcheckaccepts anything, soq > 1,q <= 0, orc <= 0produce inconsistent numbers ornanrather than a raised error — matching that silent behaviour matters if tests probe bad input. - Generic moments carry the mass factor. Since the pdf integrates to
q, unconditionally integrated generic moments scale withq: the generic mean isloc + scale*q*Gamma(1 + 1/c). Do not silently renormalize. - Boundary values. Below the support
pdfis exactly 0; atx = 0the explicit cdf applies and gives1 - q, not 0. - Reference-style checks. Tests evaluate the closed forms directly — with
c=2, q=1, loc=0.5, scale=2atx=2.5the cdf is-expm1(-1), the pdfexp(-1), andppf(0.5)equals2*sqrt(log(2)) + 0.5— so the standardization and closed forms must be reproduced exactly, and the fresh-instance-vs-singleton equality must hold.
Re-implementation checklist
Closed forms for pdf/logpdf/cdf/logcdf/ppf/sf as above; parameter order (c, q, loc, scale) everywhere; support (0, inf) with mass factor q; sf as the exact exponential; the least-squares fit objective with its plotting positions, the 10000-per-outside-point penalty, and the literal ValueError; statelessness so fresh instances equal the singleton. Any drift in these — even with a "correct-looking" density — breaks the original tests.
Exact API Reference
evapy_4s._continuous_distns.gen_exp_tail_gen
- Import Path:
from evapy_4s._continuous_distns import gen_exp_tail_gen - Signature:
class gen_exp_tail_gen
- Behavior: A generalized exponential tail continuous random variable.
Capability: ACER first-order extreme value distribution
What acer_o1_gen provides
acer_o1_gen is a SciPy rv_continuous subclass implementing the first-order ACER (Average Conditional Exceedance Rate, Naess et al.) extreme-value model. It follows the standard scipy.stats module-level singleton pattern, in the style of gumbel_r: the class lives in evapy_4s._continuous_distns beside gumbel_r_gen and gen_exp_tail_gen, and its singleton instance acer_o1 is re-exported through the evapy_4s.distributions facade. The singleton is unfrozen: it binds no parameters into the instance, and the shapes c, qn plus loc/scale are supplied on every call. It is a generalized Gumbel-like distribution: on the standardized variate z = (x - loc)/scale it supplies
- cdf:
F(z) = exp(-exp(-z**c + log(qn))) - pdf:
f(z) = c*qn*z**(c-1)*exp(-exp(-z**c + log(qn)) - z**c) - ppf:
z = (-log(-log(f)/qn))**(1/c) - logcdf:
-exp(-z**c + log(qn))
It assumes an exponentially decreasing tail and lies in the domain of attraction of the type I (Gumbel) extreme-value distribution. At c = 1 and qn = 1 every expression collapses to the ordinary Gumbel (cdf exp(-exp(-z)), pdf exp(-z - exp(-z)), ppf -log(-log f)), which is the canonical sanity check for the class.
Parameters, ordering, defaults
c(first shape, positional): the power applied tozinside the double exponential; controls tail curvature. Fractional values near 1 are the ACER norm for fitting, but see Edge cases for the parity restrictions: only odd-integercgives a proper distribution on the full real line, and fractionalcis nan forz < 0.qn(second shape, positional): a positive exceedance-rate-like factor that enters only aslog(qn);qn = 1removes it entirely.loc,scale: inherited fromrv_continuous, defaults 0 and 1.- Support: the whole real line (proper cdf/pdf there only for odd-integer
c; see Edge cases). Unlikegenexptail(instantiated witha=0.),acer_o1is created without a lower bound, soself.a = -infandself.b = inf.
Shapes must precede loc/scale: cdf(x, c, qn, loc=..., scale=...).
Test-sensitive behavior
- Gumbel reduction is asserted numerically:
cdf(3.0, 1.0, 1.0, loc=1.0, scale=2.0) == exp(-exp(-1.0)),pdf(3.0, 1.0, 1.0, loc=1.0, scale=2.0) == exp(-1 - exp(-1))/2, andppf(0.5, 1.0, 1.0, loc=1.0, scale=2.0) == 1 - 2*log(log(2)), each to 4 decimal places. Notelog(log 2) < 0, so the ppf value exceedsloc. - Instance equivalence:
dist.acer_o1.cdf(...)must equalacer_o1_gen().cdf(...)for identical arguments; the module-level instance carries no state beyond its name. _logpdfis defective: its parameter is namedqbut the body referencesqn, so calling.logpdf(...)raises a NameError. The tests exercise only pdf/cdf/ppf, so a re-implementation must simply not rely onlogpdf;_logcdfis correct and safe.pdfis exactly the derivative of the cdf; any re-derivation must keep theqnprefactor consistent with the innerlog(qn)shift.
Fitting (least squares, not MLE)
The maximum-likelihood estimate does not exist for this family, so _penalized_nnlf is overridden to inject a least-squares objective into SciPy's fit machinery via _residual_error in evapy_4s._optimize. For a candidate theta = (c, qn, loc, scale):
- Standardize the sample with loc/scale and sort it ascending.
- Compute plotting positions
u_i = (i + 1 - 0.3)/(N + 0.4)fori = 0..N-1(Blom-type). - Transform both
u_iand the model cdf onto Gumbel probability paper:y = log(-1/log(u)). - Objective = sum of
abs(y(u_i) - y(F(z_i)))**2, plus10000per sample outside the support. The objective returnsinfwhenscale <= 0or the shape_argcheckfails; the out-of-support penalty is dormant foracer_o1because its support is unbounded.
fit(data) therefore returns (c_hat, qn_hat, loc_hat, scale_hat) in that order. Because the location is weakly identified by the paper fit, the source recommends locking the location parameter (SciPy's floc convention) for more robust estimates. A theta shorter than shapes plus loc plus scale raises a ValueError.
Do not confuse the probability paper with the sibling peak model: gen_exp_tail_gen shares the same _residual_error helper but transforms with y = log(1/(1 - u)) (exponential paper). Swapping the two transforms silently changes what is fitted.
Workflow placement
The package pipeline is: raw series -> zero-upcrossing / peak declustering -> independent peak or maxima sample -> fit a tail model -> extrapolate long return periods. acer_o1 sits on the maxima side: fit it to block maxima (or ACER-extracted conditional exceedances) and read return values from ppf(1 - 1/return_period, ...) or exceedance probabilities from sf. Both routes are floored by the cdf value F(0+) = exp(-qn): ppf(1 - 1/T, ...) yields nan for fractional c unless T > 1/(1 - exp(-qn)) (roughly 1/qn for small qn), and on z > 0 sf never exceeds 1 - exp(-qn), so matching sf = 1/T needs the same bound. Use genexptail/weibull for peaks instead of maxima, and plain gumbel when the first-order shapes are already at their Gumbel limit.
Edge cases
- Validity regime: only odd-integer
c(including the Gumbel limitc = 1) gives a proper cdf/pdf on the claimed full real line; forz < 0an odd power keeps-z**c > 0, soF(-inf) = 0and the pdf stays positive. Even-integercis silently wrong rather than nan:z**cis defined for negativez, but the cdf tends to 1 asz -> -inf(-z**c -> -inf) and the pdf prefactorz**(c-1)is negative onz < 0. - For non-integer
c, negative standardizedzproduces nan (fractional power of a negative number) because the support is not clamped at 0. Keep data positive relative toloc, or fixcto an odd integer when samples can go negative; an even integer is not a safe fix (see the validity regime above). - ppf floor: from
logcdf(0) = -qnthe cdf satisfiesF(0+) = exp(-qn)and mapsz > 0onto(exp(-qn), 1). For non-odd-integerc(fractional or even) the ppf's effective domain is thereforefin(exp(-qn), 1); forf <= exp(-qn)the inner term-log(-log(f)/qn)is negative and the1/cpower yields nan, a floor rather than a divergence. Only odd-integercaccepts the full0 < f < 1range, wheref -> 0diverges to-inf;f -> 1diverges to+inffor everyc. qn <= 0orc = 0makeslog(qn)/powers invalid; results become nan rather than raising, and the fit objective reportsinf.stats/moment methods are not overridden and fall back torv_continuousnumerical integration over the unbounded domain; they are not merely slow or imprecise here. For fractionalcthe pdf is nan onz < 0, so the moments return nan, and for evencthe negative pdf onz < 0makes them garbage. Moment estimates are meaningful only for odd-integerc.
Exact API Reference
evapy_4s._continuous_distns.acer_o1_gen
- Import Path:
from evapy_4s._continuous_distns import acer_o1_gen - Signature:
class acer_o1_gen
- Behavior: A generalized Gumbel-like continuous random variable.
Detailed Implementation Nodes
Node: Package interface for extreme value analysis
Functional constraints
evapy_4s/__init__eagerly imports bothevstatsanddistributions; a bareimport evapy_4stherefore bindsevapy_4s.evstatsandevapy_4s.distributionsas attributes. The eager imports are what produce that attribute binding;from evapy_4s import evstatsworks regardless, because Python's from-import falls back to importing the named submodule when the attribute is missing on a package that has__path__.evapy_4s.distributionsis a pure facade: import_continuous_distns, then re-export exactly the singletonsrayleigh,weibull,weibull_min,gumbel,gumbel_max,genexptail,acer_o1. No other public names, no__all__filtering beyond the import list.weibullandweibull_minare separate frozen instances of the same 3-parameter Weibull machinery (weibull = frechet_r_gen(a=0.0, name='weibull');weibull_min = frechet_r_gen(a=0.0, name='weibull_min'));gumbelandgumbel_maxare likewise separate instances of the right-skewed Gumbel maxima machinery (gumbel = gumbel_r_gen(name='gumbel');gumbel_max = gumbel_r_gen(name='gumbel_max')). Alias pairs must remain behaviorally identical; object identity or attribute equality across a pair is False in the reference and is not required.- Generator classes (
rayleigh_gen,frechet_r_gen,gumbel_r_gen) stay in_continuous_distnsand are not re-exported; each suppliespdf,cdf,ppf, survival (sf), andmomentmethods following the SciPyrv_continuousfrozen-singleton design and fits through the inherited SciPy MLE. Onlygen_exp_tail_genandacer_o1_genoverride_penalized_nnlfto minimize the_residual_errorsupplied by the internal_optimizehelper — a least-squares fit used because no MLE exists for those two models (locking the location parameter is recommended). acer_o1(acer_o1_gen(name='acer_o1')) is a Gumbel-like frozenrv_continuousinstance — "A generalized Gumbel-like continuous random variable" with shape parametersc,qn— whose tail form and fitting derive from the first-order ACER method (Naess et al.) for extreme-value prediction from short records; like every other singleton it is fit to a sample and then evaluated viapdf/cdf/ppf, never fed the raw record.genexptailis the generalized exponential tail peak model.evapy_4s.evstatsexposesargupcross(x, x_up=0.0)(public wrapper; threshold defaults to 0.0) and_argupcross(x, x_up)(private worker; threshold is required and positional). Both operate on 1-D series._argupcrossreturns a same-length boolean mask ("Return the True values for all upcrossings"); the public wrapper converts that mask with flatnonzero into the indices of the samples at or belowx_upimmediately before each upward crossing (inclusive comparison). A series with no upcrossings yields the sentinelnp.array([0])— the index of the first value — not an empty result.- No global or instance state carries between calls: samples are passed per call, and the distribution singletons are stateless value objects.
Usage example
import numpy as np
import evapy_4s.distributions as dist
from evapy_4s import evstats
x = np.random.standard_normal(4096) # raw 1-D record
crossings = evstats.argupcross(x, x_up=0.0) # indices just before each upward crossing (default 0.0)
peaks = np.array([x[i:i+2].max() for i in crossings[:-1]])
pars = dist.weibull.fit(peaks) # 3-parameter Weibull fit
tail = dist.gumbel_max # maxima model, SciPy-style API
level = tail.ppf(0.999, *tail.fit(peaks)) # 99.9% return level via ppf
print(crossings.size, pars, level)
Node: Peak detection and declustering of time series
Functional constraints
_argrelmax(x)→ boolean mask, same length asx. Peak atiiffx[i] > x[i-1]andx[i] >= x[i+1]; endpoints forcedFalse; plateaus resolve to the leftmost sample; monotonic input → allFalse.argrelmax(x)→ ascending int indices of the mask; never empty — falls back to[np.argmax(x)](leftmost global max, so a ramp returns its last index).argrelmax_decluster(x, x_up=0.)→ built only from the level-upcrossing utility (argupcross/_argupcross),np.split, and per-segmentnp.argmax; it never calls_argrelmax. Upcrossing indices (sample<= x_upfollowed by a strictly greater sample; fallback[0]),np.splitthere, then per interior segmentsegment_offset + np.argmax(segment). Head before the first upcrossing and the tail after the last are dropped: a peak after the final upcrossing is never reported. Fallback with no complete cycle pair:[max(np.argmax(x), x_up)]— value-equals the argmax index under the default level, but equals the thresholdx_upitself (not an index) whenx_up > np.argmax(x); the fallback array is float-typed by default, so it must be cast/validated before use as an indexer.- Every success-path decluster result is a genuine
_argrelmaxpeak, so the output is a subset ofargrelmax(x): within a cycle the upcrossing sample is at-or-below the level and the next sample strictly above, so the cycle's leftmost maximizer strictly rises from its left neighbor (the upcrossing sample itself is never the argmax) and does not rise to its right, including when it sits at the segment's right edge immediately before the next at-or-below-level upcrossing sample. Differences fromargrelmaxcome only from dropped secondary crests and the unclosed head/trailing segments; the dropped tail cycle's argmax (index 11 in the example) is a record endpoint and hence not a_argrelmaxpeak. - Upcrossing asymmetry:
x[i] <= x_upbefore /x[i+1] > x_upafter — the mirror of the peak mask's strict->-before / non-strict->=-after. A sample exactly at the level counts as below, so level-grazing rises trigger at the last at-or-below-level sample (not the leftmost); a step from below the level up to exactly the level, like a flat at-level stretch, is not an upcrossing. First sample may be an upcrossing; last never is. - Pure functions: no mutation, no state, ascending output order. Success paths return integer index arrays; the decluster fallback is float-typed by default and may contain the threshold rather than an index. Inputs must be non-empty 1D arrays supporting vectorized comparison and slicing (plain lists fail); length-1 input degenerates to fallbacks.
x_upis any float level, not tied to zero.
Example
import numpy as np
from evapy_4s import evstats
x = np.array([0.0, 1.0, 2.0, 1.0, 2.0, 3.0, 2.0, 1.0, 0.0, 2.0, -1.0, 1.0])
evstats._argrelmax(x) # boolean mask; endpoints False
evstats.argrelmax(x) # array([2, 5, 9]) — every local crest
evstats.argrelmax_decluster(x) # array([5, 9]) — one peak per upcrossing cycle;
# crest 2 is declustered into 5; the unclosed tail
# cycle's argmax 11 (x[-1], an endpoint and not an
# _argrelmax peak) is dropped with it
evstats.argrelmax(np.array([1., 2., 3.])) # no peak -> array([2]) via argmax fallback
Value-exact outputs (mask truth pattern, index arrays including fallbacks, plateau leftmost resolution, <=/> level semantics with upcrossings at the last at-or-below-level sample, the subset relation on the decluster success path, and trailing-cycle exclusion) are the behaviors the original tests pin down; a re-implementation must reproduce them exactly.
Node: Generalized exponential tail distribution
Functional constraints
- Class
gen_exp_tail_gen(rv_continuous)inevapy_4s._continuous_distns(docstring: a generalized exponential tail continuous random variable). Singletongenexptail = gen_exp_tail_gen(name='genexptail', a=0.), re-exported fromevapy_4s.distributions; the module pulls_residual_errorfrom._optimizefor fitting. - Support
x > 0(a=0, unbounded above). Shapesc,qfollowxpositionally; trailingloc=0,scale=1; parameter order everywhere — signatures and thefitreturn tuple — is(c, q, loc, scale). Generic loc/scale wrapping applies (evaluate atz=(x-loc)/scale, pdf divided by scale). - Closed forms that must be reproduced exactly:
_pdf = c*z**(c-1)*exp(-z**c + log(q));_logpdf = log(c) + (c-1)*log(z) - z**c + log(q);_cdf = -expm1(-z**c + log(q))(scipy.special.expm1);_logcdf = log1p(-exp(-z**c + log(q)));_ppf(f) = (log(q) - log1p(-f))**(1/c);_sf = exp(-z**c + log(q)). Everything else (rvs,isf,stats,moment, the genericfitdriver) comes fromrv_continuous. - Mass property: the pdf integrates to
q, socdf(0) = 1 - qandsf(x) = q*exp(-z**c). Generic moments scale withq(mean =loc + scale*q*Gamma(1 + 1/c)); do not renormalize. Valid shapes arec > 0,0 < q <= 1, but the default_argcheckaccepts anything — invalid shapes yieldnan/inconsistent numbers, never exceptions. - Tail property:
sfdecays exponentially inz**c, the domain of attraction of the type I (Gumbel) extreme-value distribution; the1/Treturn level satisfiesz**c = log(q*T). - Fitting: MLE does not exist.
_penalized_nnlfsupplies the least-squares objective of_residual_error: standardize and sort the sample, plotting positionsF_i = (i + 0.7)/(N + 0.4), transform both byy(F) = log(1/(1 - F)), minimize the summed squared residuals. Points withz <= aorz >= bare dropped and each adds10000;scale <= 0(or failed_argcheck) givesinf;thetawith fewer than two entries raisesValueError("Not enough input arguments."). Deterministic per sample;z <= 0penalized, so fittedlocstays below the sample minimum; locking the location (floc) is the recommended robustness measure. - State: generator and singleton are stateless; a fresh
gen_exp_tail_gen()must match the singleton output for output (tested). Frozen instances are independent objects.
Usage example
import numpy as np
from evapy_4s.distributions import genexptail
rng = np.random.default_rng(0)
peaks = rng.weibull(1.5, 500) # independent peaks, all > 0
c, q, loc, scale = genexptail.fit(peaks) # least-squares fit -> (c, q, loc, scale)
tail = genexptail(c, q, loc=loc, scale=scale) # frozen model
tail.sf(3.0) # q * exp(-((3-loc)/scale)**c): exact exceedance probability
tail.ppf(1 - 1e-3) # level exceeded by 0.1% of peaks
tail.cdf(0.0) # 1 - q: mass at/below the threshold
tail.logpdf(2.0) # stable log-density
Node: ACER first-order extreme value distribution
Functional constraints
- Shapes are positional and ordered
(c, qn)before loc/scale; evaluation always standardizesz = (x - loc)/scale. - Core formulas: cdf
exp(-exp(-z**c + log(qn))); pdfc*qn*z**(c-1)*exp(-exp(-z**c + log(qn)) - z**c); ppf(-log(-log(f)/qn))**(1/c); logcdf-exp(-z**c + log(qn)). No_sf/_isf/_statsoverrides; those come from the genericrv_continuouspaths. - Support is the full real line (
a = -inf,b = inf), unlikegenexptailwhich is clamped ata = 0. Consequently the fit's out-of-support penalty never fires for this class. - Validity parity: only odd-integer
c(Gumbel limit included) is a proper distribution on the whole line; fractionalcis nan forz < 0, and even-integercsilently givesF(-inf) = 1with a negative pdf onz < 0. - The cdf floors at
F(0+) = exp(-qn): with fractionalcthe ppf is real only onfin(exp(-qn), 1)and nan below the floor;f -> 0diverges to-infonly for odd-integerc. rvsis not overridden: the genericrv_continuous.rvsmaps uniform draws through the ppf, so with fractionalcit injects nan for every drawu <= exp(-qn)(about 41% of draws atqn = 0.9). Draw uniforms on(exp(-qn), 1)and map through the ppf, or sample with an odd-integercsuch as1.c = 1, qn = 1reduces exactly to the Gumbel distribution; tests verify the reduction atloc=1, scale=2(cdf, pdf, ppf) to 1e-4._logpdfhas a parameter-name defect (qvsqn) and raises NameError; onlypdf,cdf,ppf,logcdfare dependable (the ppf within its effective domain whencis fractional).- Fitting replaces the ML objective: sorted sample, Blom plotting positions
(i + 0.7)/(N + 0.4), squared residuals on Gumbel paperlog(-1/log(u)),infobjective on non-positive scale or failed shape check; returns(c, qn, loc, scale). Locking the location is recommended. gen_exp_tail_genreuses the same residual helper with a different transform (log(1/(1 - u))); keep the papers distinct.- The instance
acer_o1and a freshacer_o1_gen()return identical values.
Example
import numpy as np
from evapy_4s import distributions as dist
g = dist._distns.acer_o1_gen()
# Gumbel reduction (c=1, qn=1)
assert abs(g.cdf(3.0, 1.0, 1.0, loc=1, scale=2) - np.exp(-np.exp(-1))) < 1e-4
assert abs(g.ppf(0.5, 1.0, 1.0, loc=1, scale=2) - (1 - 2*np.log(np.log(2)))) < 1e-4
# General shapes: cdf/ppf round-trip (x > loc keeps z > 0, above the cdf floor)
x = np.linspace(0.5, 6.0, 25)
assert np.allclose(g.ppf(g.cdf(x, 1.4, 0.9), 1.4, 0.9), x)
# Least-squares fit (no MLE exists); lock loc for stability in practice.
# Generic rvs has no override: with fractional c it pushes uniforms through
# the ppf, and every draw u <= exp(-qn) = exp(-0.9) ~ 0.41 becomes nan, so
# sample above the floor and map through the ppf manually (with odd-integer
# c = 1.0, plain rvs would be safe).
rng = np.random.default_rng(0)
u = rng.uniform(np.exp(-0.9), 1.0, 400) # u in (exp(-qn), 1)
data = 2.0 + 1.5 * g.ppf(u, 1.4, 0.9) # loc=2.0, scale=1.5
c_hat, qn_hat, loc_hat, scale_hat = dist.acer_o1.fit(data)