File size: 69,171 Bytes
d086025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# 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:

1. **Do NOT create or modify any files under the test directories** (e.g.
   `tests/`, `test/`, `testing/`, or files named `test_*.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.

2. **Your package MUST be importable by the name the tests use.** The hidden
   tests `import` your package by its documented top-level name (see the
   Project Directory Structure and API Usage Guide below). Provide a valid
   `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
   `pip install -e .` succeeds and the package imports cleanly. If your package
   is not installable/importable, every test errors out and the reward is 0.

3. **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/repo` at 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**:
  ```bash
  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**:
  ```bash
  {
    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 is `rayleigh_gen`, "A Rayleigh continuous random variable").
- `weibull` and `weibull_min` — two names bound to the same Weibull machinery built on `frechet_r_gen` ("A Frechet right class continuous random variable"); this is the 3-parameter Weibull, fitted through an explicit location parameter.
- `gumbel` and `gumbel_max` — two names for the right-skewed Gumbel maxima model built on `gumbel_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 parameters `c`, `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:

1. **Instances, not classes, are the public API of the facade.** `dist.rayleigh` is a ready-to-use frozen generator instance in the style of a SciPy `rv_continuous` singleton. The underlying generator classes (`rayleigh_gen`, `frechet_r_gen`, `gumbel_r_gen`) live in `evapy_4s._continuous_distns` and are *not* re-exported through `distributions`; reaching them requires the private module path. Tests that exercise the capability import `import evapy_4s.distributions as dist` and touch the seven names above — the facade must not add, drop, or rename any of them.
2. **Alias pairs must stay aliases.** `weibull`/`weibull_min` and `gumbel`/`gumbel_max` exist 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')` vs `weibull_min = frechet_r_gen(a=0.0, name='weibull_min')`, and likewise `gumbel = gumbel_r_gen(name='gumbel')` vs `gumbel_max = gumbel_r_gen(name='gumbel_max')` — so object identity is False and the `name` attributes 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 differing `name` attributes 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 below `x_up` immediately preceding each upward crossing (inclusive comparison: index `i` qualifies when `x[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 default `x_up=0.0` is 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.

1. **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.
2. **Fit a peak distribution.** Pass the peak sample to `dist.rayleigh`, `dist.weibull` (the same 3-parameter model is also reachable as `dist.weibull_min`), or `dist.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.rayleigh` and `dist.weibull` fit through the inherited SciPy MLE. `dist.genexptail` does not: its generator (`gen_exp_tail_gen`) overrides `_penalized_nnlf` to minimize the `_residual_error` supplied by the small internal `_optimize` helper, because no MLE exists for the model — the fit is a least-squares procedure, and locking the location parameter is the recommended practice. The `_optimize` helper is internal and not re-exported.
3. **Extrapolate maxima.** For extremes of the process itself, use `dist.gumbel`/`dist.gumbel_max` on block maxima. `dist.acer_o1` is likewise consumed as a distribution, never as a raw-record processor: fit it to a sample of extremes, then evaluate `pdf`/`cdf`/`ppf` exactly 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 `_optimize` machinery as `genexptail`); 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.weibull` twice on different data shares nothing.
- **Import order is fixed by the package.** `evapy_4s/__init__` imports `evstats` first and `distributions` second, and `distributions` imports `_continuous_distns` at module load. There is therefore no valid ordering in which `dist.rayleigh` exists while `evapy_4s.evstats` does not, or vice versa; a successful `import evapy_4s.distributions` implies the whole package initialized.
- **Defaults are minimal by design.** Among the evidenced pair `argupcross`/`_argupcross`, the only default is the public wrapper's `x_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, `evstats` also provides `argrelmax`/`argrelmax_decluster`, and `argrelmax_decluster` carries the same `x_up=0.` default.)
- **1-D only, and the no-crossing sentinel.** `argupcross` is documented for 1-D time series; higher-rank input is outside the contract. A series containing no upcrossings does not yield an empty result: `argupcross` returns the sentinel `array([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 `_argupcross` cannot be evaluated on an empty series and raises rather than returning an empty set.
- **Alias discipline.** Because `weibull` and `weibull_min` (and likewise `gumbel`/`gumbel_max`) are distinct frozen instances of one generator class, tests should assert behavioral equivalence, not object identity or equal attributes; the pair's `name` attributes 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 via `import evapy_4s.distributions as dist` and attribute-accessible as written.
- `from evapy_4s import evstats` must succeed, and `evapy_4s.evstats.argupcross` / `evapy_4s.evstats._argupcross` must exist with the documented signatures (`x_up` defaulted to `0.0` only on the public wrapper).
- The generator classes `rayleigh_gen`, `frechet_r_gen`, `gumbel_r_gen` must exist in `evapy_4s._continuous_distns` with the documented docstrings, each providing `pdf`, `cdf`, `ppf`, survival, and moment methods.
- Package import must not raise: importing `evapy_4s` pulls in both submodules eagerly, so any import-time error in `_continuous_distns` surfaces immediately and fails collection.

#### Exact API Reference

#### `evapy_4s._continuous_distns.rayleigh_gen`

- **Import Path**: `from evapy_4s._continuous_distns import rayleigh_gen`
- **Signature**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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**:

```python
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-`False` mask.
- 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_up` defaults to `0.0` but any float level works: the tests shift a whole signal by `+2.0` and pass `x_up=2.0`, producing identical index results to the unshifted case with `x_up=0.0`. The level is a parameter, not a zero-finding heuristic.
- Upcrossing detection treats a sample *exactly at* `x_up` as 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 than `x_up`. Consecutive equal values above the level never trigger anything until the signal returns to at-or-below the level.
- The last sample of `x` can never be an upcrossing (it has no successor), while the first sample can be, when `x[0] <= x_up < x[1]`. On a record that never rises above the level, the upcrossing step's own fallback contributes index `0`, which makes the decluster split produce no interior segments and triggers the decluster fallback described above.
- Monotonic input cascades cleanly: `_argrelmax` all `False`, `argrelmax` returns the global-argmax index, decluster returns `max(argmax(x), x_up)`. `np.argmax` therefore 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", `x` must 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.argmax` in 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**:

```python
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**:

```python
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**:

```python
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 missing `1 - q` is the probability at or below the threshold: `cdf(0) = 1 - q` exactly, and `sf(x) = q * exp(-x**c)` everywhere on the support. `q` is read as the fraction of peaks that are exceedances above the threshold carried by `loc`; a valid law needs `c > 0` and `0 < q <= 1`.
- **Exponential tail.** `sf` is a pure exponential in `x**c`, so the level exceeded with probability `1/T` solves `x**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; `fit` returns the tuple in the same order `(c, q, loc, scale)`. Generic `rv_continuous` loc/scale wrapping applies: evaluate at `z = (x - loc)/scale` and divide the pdf by `scale`.
- **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; `nan` inputs propagate as `nan` outputs, 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`:

1. Standardize the sample and sort it; empirical probabilities use the plotting positions `F_i = (i + 1 - 0.3)/(N + 0.4)`.
2. Transform both empirical and model probabilities with `y(F) = log(1/(1 - F))`, the log-return-period (standard-exponential) scale that linearizes `sf` — on the model side `y_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.)
3. Minimize the summed squared residuals over `(c, q, loc, scale)`, starting from the generic `_fitstart` guess.

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 - cdf` for tails.** The far-tail cdf rounds to 1.0 and its complement collapses to 0. `_cdf` is written with `expm1` and `_logcdf` with `log1p` for accuracy near 0; `_sf` is the exact exponential `q*exp(-x**c)`. Return-period work must go through `sf`/`isf`/`logcdf`.
- **Quantile domain.** The generic wrapper clamps `p <= 0` / `p >= 1` to the support endpoints, but for `0 < p < 1 - q` there is no probability mass above the threshold: the explicit `_ppf` has a negative radicand there and yields `nan`. `ppf(1 - q)` returns exactly the threshold. The same nan region surfaces in the mirrored inverses: `isf(p) = ppf(1 - p)` is `nan` for `p > q`, and generic `rvs` draws uniforms and maps them through `_ppf`, so with `q < 1` roughly a `1 - q` fraction of the draws — the uniforms below `1 - q` — come back as `nan` instead of samples.
- **Invalid shapes are not rejected.** The default `_argcheck` accepts anything, so `q > 1`, `q <= 0`, or `c <= 0` produce inconsistent numbers or `nan` rather 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 with `q`: the generic mean is `loc + scale*q*Gamma(1 + 1/c)`. Do not silently renormalize.
- **Boundary values.** Below the support `pdf` is exactly 0; at `x = 0` the explicit cdf applies and gives `1 - q`, not 0.
- **Reference-style checks.** Tests evaluate the closed forms directly — with `c=2, q=1, loc=0.5, scale=2` at `x=2.5` the cdf is `-expm1(-1)`, the pdf `exp(-1)`, and `ppf(0.5)` equals `2*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**:

```python
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 to `z` inside 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-integer `c` gives a proper distribution on the full real line, and fractional `c` is nan for `z < 0`.
- `qn` (second shape, positional): a positive exceedance-rate-like factor that enters only as `log(qn)`; `qn = 1` removes it entirely.
- `loc`, `scale`: inherited from `rv_continuous`, defaults 0 and 1.
- Support: the whole real line (proper cdf/pdf there only for odd-integer `c`; see Edge cases). Unlike `genexptail` (instantiated with `a=0.`), `acer_o1` is created without a lower bound, so `self.a = -inf` and `self.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`, and `ppf(0.5, 1.0, 1.0, loc=1.0, scale=2.0) == 1 - 2*log(log(2))`, each to 4 decimal places. Note `log(log 2) < 0`, so the ppf value exceeds `loc`.
- Instance equivalence: `dist.acer_o1.cdf(...)` must equal `acer_o1_gen().cdf(...)` for identical arguments; the module-level instance carries no state beyond its name.
- `_logpdf` is defective: its parameter is named `q` but the body references `qn`, so calling `.logpdf(...)` raises a NameError. The tests exercise only pdf/cdf/ppf, so a re-implementation must simply not rely on `logpdf`; `_logcdf` is correct and safe.
- `pdf` is exactly the derivative of the cdf; any re-derivation must keep the `qn` prefactor consistent with the inner `log(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)`:

1. Standardize the sample with loc/scale and sort it ascending.
2. Compute plotting positions `u_i = (i + 1 - 0.3)/(N + 0.4)` for `i = 0..N-1` (Blom-type).
3. Transform both `u_i` and the model cdf onto Gumbel probability paper: `y = log(-1/log(u))`.
4. Objective = sum of `abs(y(u_i) - y(F(z_i)))**2`, plus `10000` per sample outside the support. The objective returns `inf` when `scale <= 0` or the shape `_argcheck` fails; the out-of-support penalty is dormant for `acer_o1` because 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 limit `c = 1`) gives a proper cdf/pdf on the claimed full real line; for `z < 0` an odd power keeps `-z**c > 0`, so `F(-inf) = 0` and the pdf stays positive. Even-integer `c` is silently wrong rather than nan: `z**c` is defined for negative `z`, but the cdf tends to 1 as `z -> -inf` (`-z**c -> -inf`) and the pdf prefactor `z**(c-1)` is negative on `z < 0`.
- For non-integer `c`, negative standardized `z` produces nan (fractional power of a negative number) because the support is not clamped at 0. Keep data positive relative to `loc`, or fix `c` to 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) = -qn` the cdf satisfies `F(0+) = exp(-qn)` and maps `z > 0` onto `(exp(-qn), 1)`. For non-odd-integer `c` (fractional or even) the ppf's effective domain is therefore `f` in `(exp(-qn), 1)`; for `f <= exp(-qn)` the inner term `-log(-log(f)/qn)` is negative and the `1/c` power yields nan, a floor rather than a divergence. Only odd-integer `c` accepts the full `0 < f < 1` range, where `f -> 0` diverges to `-inf`; `f -> 1` diverges to `+inf` for every `c`.
- `qn <= 0` or `c = 0` makes `log(qn)`/powers invalid; results become nan rather than raising, and the fit objective reports `inf`.
- `stats`/moment methods are not overridden and fall back to `rv_continuous` numerical integration over the unbounded domain; they are not merely slow or imprecise here. For fractional `c` the pdf is nan on `z < 0`, so the moments return nan, and for even `c` the negative pdf on `z < 0` makes them garbage. Moment estimates are meaningful only for odd-integer `c`.

#### Exact API Reference

#### `evapy_4s._continuous_distns.acer_o1_gen`

- **Import Path**: `from evapy_4s._continuous_distns import acer_o1_gen`
- **Signature**:

```python
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 both `evstats` and `distributions`; a bare `import evapy_4s` therefore binds `evapy_4s.evstats` and `evapy_4s.distributions` as attributes. The eager imports are what produce that attribute binding; `from evapy_4s import evstats` works 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.distributions` is a pure facade: import `_continuous_distns`, then re-export exactly the singletons `rayleigh`, `weibull`, `weibull_min`, `gumbel`, `gumbel_max`, `genexptail`, `acer_o1`. No other public names, no `__all__` filtering beyond the import list.
- `weibull` and `weibull_min` are 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')`); `gumbel` and `gumbel_max` are 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_distns` and are not re-exported; each supplies `pdf`, `cdf`, `ppf`, survival (`sf`), and `moment` methods following the SciPy `rv_continuous` frozen-singleton design and fits through the inherited SciPy MLE. Only `gen_exp_tail_gen` and `acer_o1_gen` override `_penalized_nnlf` to minimize the `_residual_error` supplied by the internal `_optimize` helper — 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 frozen `rv_continuous` instance — "A generalized Gumbel-like continuous random variable" with shape parameters `c`, `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 via `pdf`/`cdf`/`ppf`, never fed the raw record. `genexptail` is the generalized exponential tail peak model.
- `evapy_4s.evstats` exposes `argupcross(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. `_argupcross` returns 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 below `x_up` immediately before each upward crossing (inclusive comparison). A series with no upcrossings yields the sentinel `np.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

```python
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 as `x`. Peak at `i` iff `x[i] > x[i-1]` and `x[i] >= x[i+1]`; endpoints forced `False`; plateaus resolve to the leftmost sample; monotonic input → all `False`.
- `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-segment `np.argmax`; it never calls `_argrelmax`. Upcrossing indices (sample `<= x_up` followed by a strictly greater sample; fallback `[0]`), `np.split` there, then per *interior* segment `segment_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 threshold `x_up` itself (not an index) when `x_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 `_argrelmax` peak, so the output is a subset of `argrelmax(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 from `argrelmax` come 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 `_argrelmax` peak.
- Upcrossing asymmetry: `x[i] <= x_up` before / `x[i+1] > x_up` after — 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_up` is any float level, not tied to zero.

## Example

```python
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)` in `evapy_4s._continuous_distns` (docstring: a generalized exponential tail continuous random variable). Singleton `genexptail = gen_exp_tail_gen(name='genexptail', a=0.)`, re-exported from `evapy_4s.distributions`; the module pulls `_residual_error` from `._optimize` for fitting.
- Support `x > 0` (`a=0`, unbounded above). Shapes `c`, `q` follow `x` positionally; trailing `loc=0`, `scale=1`; parameter order everywhere — signatures and the `fit` return tuple — is `(c, q, loc, scale)`. Generic loc/scale wrapping applies (evaluate at `z=(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 generic `fit` driver) comes from `rv_continuous`.
- Mass property: the pdf integrates to `q`, so `cdf(0) = 1 - q` and `sf(x) = q*exp(-z**c)`. Generic moments scale with `q` (mean = `loc + scale*q*Gamma(1 + 1/c)`); do not renormalize. Valid shapes are `c > 0`, `0 < q <= 1`, but the default `_argcheck` accepts anything — invalid shapes yield `nan`/inconsistent numbers, never exceptions.
- Tail property: `sf` decays exponentially in `z**c`, the domain of attraction of the type I (Gumbel) extreme-value distribution; the `1/T` return level satisfies `z**c = log(q*T)`.
- Fitting: MLE does not exist. `_penalized_nnlf` supplies the least-squares objective of `_residual_error`: standardize and sort the sample, plotting positions `F_i = (i + 0.7)/(N + 0.4)`, transform both by `y(F) = log(1/(1 - F))`, minimize the summed squared residuals. Points with `z <= a` or `z >= b` are dropped and each adds `10000`; `scale <= 0` (or failed `_argcheck`) gives `inf`; `theta` with fewer than two entries raises `ValueError("Not enough input arguments.")`. Deterministic per sample; `z <= 0` penalized, so fitted `loc` stays 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

```python
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 standardizes `z = (x - loc)/scale`.
- Core formulas: cdf `exp(-exp(-z**c + log(qn)))`; pdf `c*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`/`_stats` overrides; those come from the generic `rv_continuous` paths.
- Support is the full real line (`a = -inf`, `b = inf`), unlike `genexptail` which is clamped at `a = 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; fractional `c` is nan for `z < 0`, and even-integer `c` silently gives `F(-inf) = 1` with a negative pdf on `z < 0`.
- The cdf floors at `F(0+) = exp(-qn)`: with fractional `c` the ppf is real only on `f` in `(exp(-qn), 1)` and nan below the floor; `f -> 0` diverges to `-inf` only for odd-integer `c`.
- `rvs` is not overridden: the generic `rv_continuous.rvs` maps uniform draws through the ppf, so with fractional `c` it injects nan for every draw `u <= exp(-qn)` (about 41% of draws at `qn = 0.9`). Draw uniforms on `(exp(-qn), 1)` and map through the ppf, or sample with an odd-integer `c` such as `1`.
- `c = 1, qn = 1` reduces exactly to the Gumbel distribution; tests verify the reduction at `loc=1, scale=2` (cdf, pdf, ppf) to 1e-4.
- `_logpdf` has a parameter-name defect (`q` vs `qn`) and raises NameError; only `pdf`, `cdf`, `ppf`, `logcdf` are dependable (the ppf within its effective domain when `c` is fractional).
- Fitting replaces the ML objective: sorted sample, Blom plotting positions `(i + 0.7)/(N + 0.4)`, squared residuals on Gumbel paper `log(-1/log(u))`, `inf` objective on non-positive scale or failed shape check; returns `(c, qn, loc, scale)`. Locking the location is recommended.
- `gen_exp_tail_gen` reuses the same residual helper with a different transform (`log(1/(1 - u))`); keep the papers distinct.
- The instance `acer_o1` and a fresh `acer_o1_gen()` return identical values.

## Example

```python
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)
```