diff --git a/.codespell-ignore-words b/.codespell-ignore-words index be48e98e..ab4394b2 100644 --- a/.codespell-ignore-words +++ b/.codespell-ignore-words @@ -1 +1,2 @@ MOR +theses diff --git a/.coveragerc b/.coveragerc index a7cba45f..f97c8305 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,3 +1,11 @@ [run] +branch = true +source = pysatl_criterion omit = tests/* + +[report] +show_missing = true +precision = 2 +# The measured combined statement/branch baseline is 82.08%. +fail_under = 80 diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b362992f..5e7ea1f6 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -29,10 +29,13 @@ jobs: python-version: ${{ matrix.python-version }} - name: Install Poetry - run: pip install poetry==2.1.1 + run: pip install poetry==2.4.1 - - name: Install dynamic versioning plugin - run: poetry self add poetry-dynamic-versioning[plugin] + - name: Validate locked dependencies + run: poetry check --lock + + - name: Install dependencies with Poetry + run: poetry sync --only main,lint,test - name: Build distribution run: poetry build @@ -43,9 +46,6 @@ jobs: - name: Display Python version run: python -c "import sys; print(sys.version)" - - name: Install dependencies with Poetry - run: poetry install --with dev - - name: Run Ruff lint run: poetry run ruff check --output-format=github @@ -57,12 +57,22 @@ jobs: poetry run mypy src/pysatl_criterion tests - name: Run tests - run: poetry run pytest --random-order + if: matrix.python-version != '3.12' + run: poetry run pytest --random-order --junitxml=${{ runner.temp }}/pytest-results.xml - name: Tests with Coveralls if: (runner.os == 'Linux' && matrix.python-version == '3.12') run: | - poetry run pytest --random-order --cov=pysatl_criterion --cov-config=.coveragerc + poetry run pytest --random-order --cov=pysatl_criterion --cov-config=.coveragerc --cov-report=term-missing --cov-report=xml --junitxml=${{ runner.temp }}/pytest-results.xml + + - name: Upload test reports + if: always() + uses: actions/upload-artifact@v7 + with: + name: test-reports-python-${{ matrix.python-version }} + path: | + ${{ runner.temp }}/pytest-results.xml + coverage.xml - name: Coveralls if: (runner.os == 'Linux' && matrix.python-version == '3.12') @@ -72,9 +82,6 @@ jobs: # Allow failure for coveralls poetry run coveralls || true - - name: Remove poetry.lock before checking for changes - run: rm -f poetry.lock - - name: Check for repository changes run: | if [ -n "$(git status --porcelain)" ]; then @@ -98,7 +105,14 @@ jobs: - uses: actions/setup-python@v7 with: python-version: "3.12" - - uses: pre-commit/action@v3.0.1 + - name: Install Poetry + run: pip install poetry==2.4.1 + - name: Validate locked dependencies + run: poetry check --lock + - name: Install dependencies + run: poetry sync --only main,lint,test + - name: Run pre-commit + run: poetry run pre-commit run --all-files --show-diff-on-failure build: @@ -118,11 +132,11 @@ jobs: with: python-version: "3.12" - - name: Build distribution - run: pip install poetry==2.1.1 + - name: Install Poetry + run: pip install poetry==2.4.1 - - name: Install dynamic versioning plugin - run: poetry self add poetry-dynamic-versioning[plugin] + - name: Validate locked dependencies + run: poetry check --lock - name: Build distribution run: poetry build diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 602713b3..ba05c378 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -20,16 +20,21 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v7 with: python-version: '3.12' - - name: Install dependencies + - name: Install Poetry + run: pip install poetry==2.4.1 + + - name: Install documentation dependencies run: | - python -m pip install --upgrade pip - pip install -r docs/requirements-docs.txt + poetry check --lock + poetry sync --only docs --no-root - name: Fetch gh-pages branch run: | @@ -43,13 +48,13 @@ jobs: - name: Build and push Mike if: ${{ github.event_name == 'push' }} run: | - mike deploy ${{ github.ref_name }} latest --push --update-aliases + poetry run mike deploy ${{ github.ref_name }} latest --push --update-aliases - name: Build and push Mike - Release if: ${{ github.event_name == 'release' }} run: | - mike deploy ${{ github.ref_name }} stable --push --update-aliases + poetry run mike deploy ${{ github.ref_name }} stable --push --update-aliases - name: Show mike versions run: | - mike list \ No newline at end of file + poetry run mike list diff --git a/.github/workflows/extended-validation.yaml b/.github/workflows/extended-validation.yaml new file mode 100644 index 00000000..f859eab6 --- /dev/null +++ b/.github/workflows/extended-validation.yaml @@ -0,0 +1,85 @@ +name: Statistical and database validation + +on: + workflow_dispatch: + schedule: + - cron: "0 3 * * 1" + +permissions: + contents: read + +jobs: + statistical: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - run: pip install poetry==2.4.1 + - run: poetry sync --only main,test + - name: Validate level and power with independent simulation samples + env: + PYSATL_STATISTICAL: "1" + PYSATL_MULTIPLE_TESTING_MONTE_CARLO: "1" + run: >- + poetry run pytest -m statistical --random-order + --junitxml=${{ runner.temp }}/statistical.xml + - uses: actions/upload-artifact@v7 + if: always() + with: + name: statistical-results + path: ${{ runner.temp }}/statistical.xml + + databases: + runs-on: ubuntu-latest + timeout-minutes: 15 + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: criterion + POSTGRES_PASSWORD: criterion + POSTGRES_DB: criterion + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U criterion" + --health-interval 10s --health-timeout 5s --health-retries 10 + mysql: + image: mysql:8.4 + env: + MYSQL_ROOT_PASSWORD: criterion + MYSQL_ROOT_HOST: "%" + MYSQL_DATABASE: criterion + ports: + - 3306:3306 + options: >- + --health-cmd "mysqladmin ping -h localhost -pcriterion" + --health-interval 10s --health-timeout 5s --health-retries 20 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - run: pip install poetry==2.4.1 + - run: poetry sync --only main,test + - name: Install optional MySQL integration driver + run: poetry run python -m pip install 'PyMySQL[rsa]==1.1.2' + - name: Check real database transactions and concurrent writers + env: + CRITERION_TEST_POSTGRES_URL: postgresql+psycopg2://criterion:criterion@127.0.0.1:5432/criterion + CRITERION_TEST_MYSQL_URL: mysql+pymysql://root:criterion@127.0.0.1:3306/criterion + run: >- + poetry run pytest tests/persistence tests/loader --random-order + --junitxml=${{ runner.temp }}/databases.xml + - uses: actions/upload-artifact@v7 + if: always() + with: + name: database-results + path: ${{ runner.temp }}/databases.xml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 94e3d4c5..57516f6c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,40 +1,25 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - - repo: https://github.com/pycqa/flake8 - rev: "7.1.1" - hooks: - - id: flake8 - additional_dependencies: [Flake8-pyproject] - # stages: [push] - - - repo: https://github.com/pre-commit/mirrors-mypy - rev: "v1.13.0" + # Use the locked project environment so hooks and CI run identical tools. + - repo: local hooks: - id: mypy - exclude: build_helpers - additional_dependencies: - - types-cachetools==5.5.0.20240820 - - types-filelock==3.2.7 - - types-requests==2.32.0.20241016 - - types-tabulate==0.9.0.20240106 - - types-python-dateutil==2.9.0.20241003 - - SQLAlchemy==2.0.36 - # stages: [push] - - - repo: https://github.com/pycqa/isort - rev: "5.13.2" - hooks: - - id: isort - name: isort (python) - # stages: [push] - - - repo: https://github.com/charliermarsh/ruff-pre-commit - # Ruff version. - rev: 'v0.15.5' - hooks: + name: mypy + entry: poetry run mypy src/pysatl_criterion tests + language: system + types_or: [python, pyi] + pass_filenames: false - id: ruff + name: Ruff lint + entry: poetry run ruff check + language: system + types_or: [python, pyi] - id: ruff-format + name: Ruff format + entry: poetry run ruff format + language: system + types_or: [python, pyi] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v5.0.0 diff --git a/.readthedocs.yaml b/.readthedocs.yaml index ea25f4c8..fe853d11 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -5,10 +5,13 @@ build: os: "ubuntu-22.04" tools: python: "3.12" - -python: - install: - - requirements: docs/requirements-docs.txt + jobs: + post_create_environment: + - pip install poetry==2.4.1 + post_install: + - poetry check --lock + # Keep Read the Docs' own build tools in its shared environment. + - VIRTUAL_ENV=$READTHEDOCS_VIRTUALENV_PATH poetry install --only docs --no-root mkdocs: configuration: mkdocs.yml diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 54bf3955..1ed8561a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing -## Contribute to pysatl-experiment +## Contribute to pysatl-criterion Feel like our lib is missing a feature? We welcome your pull requests! @@ -12,6 +12,17 @@ Few pointers for contributions: ## Before sending the PR +Use Python 3.10–3.12 and Poetry 2.4.1. Install the locked development environment: + +```bash +poetry check --lock +poetry sync --with dev +``` + +Ruff handles linting, import sorting, and formatting. Hooks run the same locked tools as CI. +Keep `poetry.lock` in version control and update it when dependencies change. Use +`poetry add --group lint`, `--group test`, or `--group docs` to add development tools. + ### 1. Run unit tests All unit tests must pass. If a unit test is broken, change your code to @@ -20,19 +31,19 @@ make it pass. It means you have introduced a regression. #### Test the whole project ```bash -pytest +poetry run pytest --random-order ``` #### Test only one file ```bash -pytest tests/test_.py +poetry run pytest tests/test_.py ``` #### Test only one method from one file ```bash -pytest tests/test_.py::test_ +poetry run pytest tests/test_.py::test_ ``` ### 2. Test if your code is PEP8 compliant @@ -40,14 +51,15 @@ pytest tests/test_.py::test_ #### Run Ruff ```bash -ruff check . +poetry run ruff check . ``` We receive a lot of code that fails the `ruff` checks. To help with that, we encourage you to install the git pre-commit hook that will warn you when you try to commit code that fails these checks. -you can manually run pre-commit with `pre-commit run -a`. +Install hooks with `poetry run pre-commit install`, and run them manually with +`poetry run pre-commit run --all-files`. ##### Additional styles applied @@ -61,7 +73,7 @@ you can manually run pre-commit with `pre-commit run -a`. #### Run mypy ``` bash -mypy pysatl_criterion +poetry run mypy src/pysatl_criterion tests ``` ### 4. Ensure formatting is correct @@ -69,9 +81,21 @@ mypy pysatl_criterion #### Run ruff ``` bash -ruff format . +poetry run ruff format . ``` +To check formatting without changing files, use `poetry run ruff format --check .`. + +### 5. Check branch coverage + +```bash +poetry run pytest --random-order --cov=pysatl_criterion --cov-report=term-missing +``` + +The coverage threshold lives in `.coveragerc`. CI measures coverage during its Python 3.12 +test run; each Python version runs the suite once. Type-checking strictness is increased +module by module, starting with the goodness-of-fit test runner. + ## (Core)-Committer Guide ### Process: Pull Requests diff --git a/README.md b/README.md index 100263bc..4c9e62f4 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This repository contains a collection of Python scripts and modules for performing various statistical tests. These tests are designed to help you analyze data, make inferences, and draw conclusions based on statistical methods. The repository is organized to be easy to use, modular, and extensible. ## Installation -To use this repository, you need to have Python 3.9 or later installed on your system. You can install the required dependencies by following these steps: +To use this repository, you need Python 3.10, 3.11, or 3.12 and Poetry 2.4.1. You can install the required dependencies by following these steps: Clone the repository: @@ -18,7 +18,8 @@ git clone https://github.com/PySATL/pysatl-criterion.git Install dependencies: ```bash -poetry install +cd pysatl-criterion +poetry sync --only main ``` You're all set! You can now import and use the statistical tests in your Python scripts. @@ -26,12 +27,16 @@ You're all set! You can now import and use the statistical tests in your Python Statistic calculation example: ```python +from pysatl_criterion.distribution import NormalDistributionDescriptor + # import needed criterion from pysatl_criterion from pysatl_criterion.statistics import KolmogorovSmirnovNormalityGofStatistic # make a criterion object -statistic = KolmogorovSmirnovNormalityGofStatistic(mean=0, var=1) +statistic = KolmogorovSmirnovNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"mean": 0, "var": 1}) +) # initialize test data x = [0.1, 0.7, 0.5, 0.3] @@ -90,18 +95,39 @@ Issues labeled [good first issue](https://github.com/PySATL/pysatl-criterion/lab ## Software requirements -- [Python >= 3.9](http://docs.python-guide.org/en/latest/starting/installation/) -- [poetry](https://python-poetry.org/docs/) +- Python >= 3.10, < 3.13 +- [Poetry 2.4.1](https://python-poetry.org/docs/) - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) -- [virtualenv](https://virtualenv.pypa.io/en/stable/installation.html) (Recommended) ## Development -Install requirements +Install the locked development environment, including lint, test, and documentation tools: + +```bash +poetry check --lock +poetry sync --with dev +``` + +Run checks through Poetry so local development and CI use the same tool versions: + +```bash +poetry run ruff check . +poetry run ruff format --check . +poetry run mypy src/pysatl_criterion tests +poetry run pytest --random-order +poetry run pytest --random-order --cov=pysatl_criterion --cov-report=term-missing +``` + +Dependencies are defined in `pyproject.toml`; commit `poetry.lock` with dependency changes. +Use `poetry add --group lint`, `--group test`, or `--group docs` for development dependencies. +The `dev` group includes all three groups. CI checks lockfile consistency before installation. + +For documentation only: ```bash -poetry install --with dev +poetry sync --only docs --no-root +poetry run mkdocs build ``` ## Pre-commit diff --git a/benchmarks/benchmark_anderson_darling_hyperbolic.py b/benchmarks/benchmark_anderson_darling_hyperbolic.py deleted file mode 100644 index 5677206e..00000000 --- a/benchmarks/benchmark_anderson_darling_hyperbolic.py +++ /dev/null @@ -1,57 +0,0 @@ -import numpy as np -from benchmark_runner import BenchmarkRunner -from hyperbolic_benchmark_utils import ( - ALPHA, - BETA, - CALLS, - DELTA, - MU, - SAMPLE_SIZE, - create_sorted_sample, - log_probabilities, -) - -from pysatl_criterion.statistics.goodness_of_fit.hyperbolic import ( - AndersonDarlingHyperbolicGofStatistic, -) - - -def reference(log_cdf: np.ndarray, log_sf: np.ndarray) -> float: - """Calculate the statistic using vectorized NumPy operations.""" - n = len(log_cdf) - weights = (2.0 * np.arange(n) + 1.0) / n - return float(-n - np.sum(weights * (log_cdf + log_sf[::-1]))) - - -def main() -> None: - """Compare the NumPy and Numba statistic kernels.""" - sorted_sample = create_sorted_sample() - log_cdf, log_sf = log_probabilities(sorted_sample) - statistic = AndersonDarlingHyperbolicGofStatistic( - alpha=ALPHA, - beta=BETA, - delta=DELTA, - mu=MU, - ) - optimized_result = statistic.do_execute_statistic( - sorted_sample, - log_cdf=log_cdf, - log_sf=log_sf, - ) - np.testing.assert_allclose(optimized_result, reference(log_cdf, log_sf)) - - BenchmarkRunner(CALLS).run_comparison( - sample_size=SAMPLE_SIZE, - reference_name="NumPy reference statistic kernel", - reference_function=lambda: reference(log_cdf, log_sf), - optimized_name="Numba statistic kernel", - optimized_function=lambda: statistic.do_execute_statistic( - sorted_sample, - log_cdf=log_cdf, - log_sf=log_sf, - ), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_anderson_darling_laplace.py b/benchmarks/benchmark_anderson_darling_laplace.py deleted file mode 100644 index 0ef9632f..00000000 --- a/benchmarks/benchmark_anderson_darling_laplace.py +++ /dev/null @@ -1,66 +0,0 @@ -import numpy as np -import scipy.stats as scipy_stats -from benchmark_runner import BenchmarkRunner - -from pysatl_criterion.statistics.goodness_of_fit.laplace import AndersonDarlingLaplaceGofStatistic - - -def anderson_darling_laplace_reference( - sorted_sample: np.ndarray, location: float, scale: float -) -> float: - """Calculate the Anderson--Darling statistic using the original approach.""" - n = len(sorted_sample) - log_cdf = scipy_stats.laplace.logcdf( - sorted_sample, - loc=location, - scale=scale, - ) - log_sf = scipy_stats.laplace.logsf( - sorted_sample, - loc=location, - scale=scale, - ) - i = np.arange(1, n + 1) - return float(-n - np.sum((2 * i - 1.0) / n * (log_cdf + log_sf[::-1]))) - - -def main() -> None: - location = 0.0 - scale = 1.0 - calls = 1_000 - sample = np.random.default_rng(42).laplace( - loc=location, - scale=scale, - size=10_000, - ) - sorted_sample = np.sort(sample) - statistic = AndersonDarlingLaplaceGofStatistic( - t=location, - s=scale, - ) - - # Compile the Numba kernel before measuring execution time. - optimized_result = statistic.do_execute_statistic(sorted_sample) - reference_result = anderson_darling_laplace_reference( - sorted_sample, - location, - scale, - ) - np.testing.assert_allclose(optimized_result, reference_result) - runner = BenchmarkRunner(calls) - - runner.run_comparison( - sample_size=sample.size, - reference_name="SciPy reference implementation", - reference_function=lambda: anderson_darling_laplace_reference( - sorted_sample, - location, - scale, - ), - optimized_name="Numba implementation", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_cramer_von_mises_hyperbolic.py b/benchmarks/benchmark_cramer_von_mises_hyperbolic.py deleted file mode 100644 index b678ab00..00000000 --- a/benchmarks/benchmark_cramer_von_mises_hyperbolic.py +++ /dev/null @@ -1,49 +0,0 @@ -import numpy as np -from benchmark_runner import BenchmarkRunner -from hyperbolic_benchmark_utils import ( - ALPHA, - BETA, - CALLS, - DELTA, - MU, - SAMPLE_SIZE, - cdf_values, - create_sorted_sample, -) - -from pysatl_criterion.statistics.goodness_of_fit.hyperbolic import ( - CramerVonMisesHyperbolicGofStatistic, -) - - -def reference(cdf: np.ndarray) -> float: - """Calculate the statistic using vectorized NumPy operations.""" - n = len(cdf) - expected = (2.0 * np.arange(n) + 1.0) / (2.0 * n) - return float(1.0 / (12.0 * n) + np.sum((expected - cdf) ** 2)) - - -def main() -> None: - """Compare the NumPy and Numba statistic kernels.""" - sorted_sample = create_sorted_sample() - cdf = cdf_values(sorted_sample) - statistic = CramerVonMisesHyperbolicGofStatistic( - alpha=ALPHA, - beta=BETA, - delta=DELTA, - mu=MU, - ) - optimized_result = statistic.do_execute_statistic(sorted_sample, cdf) - np.testing.assert_allclose(optimized_result, reference(cdf)) - - BenchmarkRunner(CALLS).run_comparison( - sample_size=SAMPLE_SIZE, - reference_name="NumPy reference statistic kernel", - reference_function=lambda: reference(cdf), - optimized_name="Numba statistic kernel", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample, cdf), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_cramer_von_mises_laplace.py b/benchmarks/benchmark_cramer_von_mises_laplace.py deleted file mode 100644 index 5e5f38ab..00000000 --- a/benchmarks/benchmark_cramer_von_mises_laplace.py +++ /dev/null @@ -1,60 +0,0 @@ -import numpy as np -import scipy.stats as scipy_stats -from benchmark_runner import BenchmarkRunner - -from pysatl_criterion.statistics.goodness_of_fit.laplace import CramerVonMisesLaplaceGofStatistic - - -def cramer_von_mises_laplace_reference( - sorted_sample: np.ndarray, location: float, scale: float -) -> float: - """Calculate the Cramer--von Mises statistic using the original approach.""" - n = len(sorted_sample) - cdf_values = scipy_stats.laplace.cdf( - sorted_sample, - loc=location, - scale=scale, - ) - expected_cdf = (2 * np.arange(1, n + 1) - 1) / (2 * n) - return float(1 / (12 * n) + np.sum((expected_cdf - cdf_values) ** 2)) - - -def main() -> None: - location = 0.0 - scale = 1.0 - calls = 1_000 - sample = np.random.default_rng(42).laplace( - loc=location, - scale=scale, - size=10_000, - ) - sorted_sample = np.sort(sample) - statistic = CramerVonMisesLaplaceGofStatistic( - t=location, - s=scale, - ) - - optimized_result = statistic.do_execute_statistic(sorted_sample) - reference_result = cramer_von_mises_laplace_reference( - sorted_sample, - location, - scale, - ) - np.testing.assert_allclose(optimized_result, reference_result) - runner = BenchmarkRunner(calls) - - runner.run_comparison( - sample_size=sample.size, - reference_name="SciPy reference implementation", - reference_function=lambda: cramer_von_mises_laplace_reference( - sorted_sample, - location, - scale, - ), - optimized_name="Numba implementation", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_greenwood_laplace.py b/benchmarks/benchmark_greenwood_laplace.py deleted file mode 100644 index 13a749ac..00000000 --- a/benchmarks/benchmark_greenwood_laplace.py +++ /dev/null @@ -1,63 +0,0 @@ -import numpy as np -import scipy.stats as scipy_stats -from benchmark_runner import BenchmarkRunner - -from pysatl_criterion.statistics.goodness_of_fit.laplace import GreenwoodLaplaceGofStatistic - - -def greenwood_laplace_reference(sorted_sample: np.ndarray, location: float, scale: float) -> float: - """Calculate the Greenwood statistic using the original SciPy approach.""" - - cdf_values = scipy_stats.laplace.cdf( - sorted_sample, - loc=location, - scale=scale, - ) - spacings = np.diff( - np.concatenate( - ( - [0.0], - cdf_values, - [1.0], - ) - ) - ) - - return float(np.sum(spacings**2)) - - -def main() -> None: - location = 0.0 - scale = 1.0 - calls = 1_000 - - sample = np.random.default_rng(42).laplace( - loc=location, - scale=scale, - size=10_000, - ) - sorted_sample = np.sort(sample) - - statistic = GreenwoodLaplaceGofStatistic( - t=location, - s=scale, - ) - - statistic.do_execute_statistic(sorted_sample) - runner = BenchmarkRunner(calls) - - runner.run_comparison( - sample_size=sample.size, - reference_name="SciPy reference implementation", - reference_function=lambda: greenwood_laplace_reference( - sorted_sample, - location, - scale, - ), - optimized_name="Numba implementation", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_kolmogorov_smirnov_hyperbolic.py b/benchmarks/benchmark_kolmogorov_smirnov_hyperbolic.py deleted file mode 100644 index f980a5e1..00000000 --- a/benchmarks/benchmark_kolmogorov_smirnov_hyperbolic.py +++ /dev/null @@ -1,51 +0,0 @@ -import numpy as np -from benchmark_runner import BenchmarkRunner -from hyperbolic_benchmark_utils import ( - ALPHA, - BETA, - CALLS, - DELTA, - MU, - SAMPLE_SIZE, - cdf_values, - create_sorted_sample, -) - -from pysatl_criterion.statistics.goodness_of_fit.hyperbolic import ( - KolmogorovSmirnovHyperbolicGofStatistic, -) - - -def reference(cdf: np.ndarray) -> float: - """Calculate the two-sided statistic using vectorized NumPy operations.""" - n = len(cdf) - positions = np.arange(n, dtype=np.float64) - d_plus = np.max((positions + 1.0) / n - cdf) - d_minus = np.max(cdf - positions / n) - return float(max(d_plus, d_minus)) - - -def main() -> None: - """Compare the NumPy and Numba statistic kernels.""" - sorted_sample = create_sorted_sample() - cdf = cdf_values(sorted_sample) - statistic = KolmogorovSmirnovHyperbolicGofStatistic( - alpha=ALPHA, - beta=BETA, - delta=DELTA, - mu=MU, - ) - optimized_result = statistic.do_execute_statistic(sorted_sample, cdf) - np.testing.assert_allclose(optimized_result, reference(cdf)) - - BenchmarkRunner(CALLS).run_comparison( - sample_size=SAMPLE_SIZE, - reference_name="NumPy reference statistic kernel", - reference_function=lambda: reference(cdf), - optimized_name="Numba statistic kernel", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample, cdf), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_kuiper_hyperbolic.py b/benchmarks/benchmark_kuiper_hyperbolic.py deleted file mode 100644 index d771d18f..00000000 --- a/benchmarks/benchmark_kuiper_hyperbolic.py +++ /dev/null @@ -1,48 +0,0 @@ -import numpy as np -from benchmark_runner import BenchmarkRunner -from hyperbolic_benchmark_utils import ( - ALPHA, - BETA, - CALLS, - DELTA, - MU, - SAMPLE_SIZE, - cdf_values, - create_sorted_sample, -) - -from pysatl_criterion.statistics.goodness_of_fit.hyperbolic import KuiperHyperbolicGofStatistic - - -def reference(cdf: np.ndarray) -> float: - """Calculate the statistic using vectorized NumPy operations.""" - n = len(cdf) - positions = np.arange(n, dtype=np.float64) - d_plus = np.max((positions + 1.0) / n - cdf) - d_minus = np.max(cdf - positions / n) - return float(d_plus + d_minus) - - -def main() -> None: - """Compare the NumPy and Numba statistic kernels.""" - cdf = cdf_values(create_sorted_sample()) - statistic = KuiperHyperbolicGofStatistic( - alpha=ALPHA, - beta=BETA, - delta=DELTA, - mu=MU, - ) - optimized_result = statistic.do_execute_statistic(cdf) - np.testing.assert_allclose(optimized_result, reference(cdf)) - - BenchmarkRunner(CALLS).run_comparison( - sample_size=SAMPLE_SIZE, - reference_name="NumPy reference statistic kernel", - reference_function=lambda: reference(cdf), - optimized_name="Numba statistic kernel", - optimized_function=lambda: statistic.do_execute_statistic(cdf), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_kuiper_laplace.py b/benchmarks/benchmark_kuiper_laplace.py deleted file mode 100644 index d0828ba8..00000000 --- a/benchmarks/benchmark_kuiper_laplace.py +++ /dev/null @@ -1,63 +0,0 @@ -import numpy as np -import scipy.stats as scipy_stats -from benchmark_runner import BenchmarkRunner - -from pysatl_criterion.statistics.goodness_of_fit.laplace import KuiperLaplaceGofStatistic - - -def kuiper_laplace_reference(sorted_sample: np.ndarray, location: float, scale: float) -> float: - """Calculate the Kuiper statistic using the original SciPy approach.""" - n = len(sorted_sample) - cdf_values = scipy_stats.laplace.cdf( - sorted_sample, - loc=location, - scale=scale, - ) - indices = np.arange(1, n + 1) - d_plus = np.max(indices / n - cdf_values) - d_minus = np.max(cdf_values - (indices - 1) / n) - - return float(d_plus + d_minus) - - -def main() -> None: - location = 0.0 - scale = 1.0 - calls = 1_000 - - sample = np.random.default_rng(42).laplace( - loc=location, - scale=scale, - size=10_000, - ) - sorted_sample = np.sort(sample) - - statistic = KuiperLaplaceGofStatistic( - t=location, - s=scale, - ) - - optimized_result = statistic.do_execute_statistic(sorted_sample) - reference_result = kuiper_laplace_reference( - sorted_sample, - location, - scale, - ) - np.testing.assert_allclose(optimized_result, reference_result) - runner = BenchmarkRunner(calls) - - runner.run_comparison( - sample_size=sample.size, - reference_name="SciPy reference implementation", - reference_function=lambda: kuiper_laplace_reference( - sorted_sample, - location, - scale, - ), - optimized_name="Numba implementation", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_runner.py b/benchmarks/benchmark_runner.py deleted file mode 100644 index a8c51287..00000000 --- a/benchmarks/benchmark_runner.py +++ /dev/null @@ -1,70 +0,0 @@ -import time -from collections.abc import Callable -from dataclasses import dataclass - - -@dataclass(frozen=True) -class BenchmarkResult: - """Store the timing result for one benchmarked implementation.""" - - name: str - total_time: float - calls: int - - @property - def average_time(self) -> float: - """Return the average execution time per call.""" - return self.total_time / self.calls - - -class BenchmarkRunner: - """Measure and report execution times for two implementations.""" - - def __init__(self, calls: int) -> None: - if calls <= 0: - raise ValueError("Number of calls must be positive.") - - self.calls = calls - - def measure(self, name: str, function: Callable[[], object]) -> BenchmarkResult: - """Measure a function for the configured number of calls.""" - start = time.perf_counter() - - for _ in range(self.calls): - function() - - return BenchmarkResult( - name=name, - total_time=time.perf_counter() - start, - calls=self.calls, - ) - - def run_comparison( - self, - *, - sample_size: int, - reference_name: str, - reference_function: Callable[[], object], - optimized_name: str, - optimized_function: Callable[[], object], - ) -> tuple[BenchmarkResult, BenchmarkResult]: - """Measure two implementations and print their comparison.""" - reference_result = self.measure(reference_name, reference_function) - optimized_result = self.measure(optimized_name, optimized_function) - - print(f"Sample size: {sample_size}") - print(f"Calls: {self.calls}") - print() - self._print_result(reference_result) - print() - self._print_result(optimized_result) - print() - print(f"Speedup: {reference_result.total_time / optimized_result.total_time:.2f}x") - - return reference_result, optimized_result - - @staticmethod - def _print_result(result: BenchmarkResult) -> None: - print(f"{result.name}:") - print(f"Total time: {result.total_time:.6f} seconds") - print(f"Average time per call: {result.average_time:.9f} seconds") diff --git a/benchmarks/benchmark_stein_uniform.py b/benchmarks/benchmark_stein_uniform.py deleted file mode 100644 index f1c0f135..00000000 --- a/benchmarks/benchmark_stein_uniform.py +++ /dev/null @@ -1,46 +0,0 @@ -import numpy as np -from benchmark_runner import BenchmarkRunner - -from pysatl_criterion.statistics.goodness_of_fit.uniform import SteinUniformGofStatistic - - -def stein_uniform_reference(sample: np.ndarray) -> float: - """Calculate the Stein statistic using the original Python approach.""" - n = len(sample) - - if n <= 1: - return 0.0 - - total = 0.0 - - for i in range(n): - x = sample[i] - - for j in range(i + 1, n): - y = sample[j] - total += 0.5 * (2 * max(x, y) - 2 * x - 2 * y + x**2 + y**2) - - return float(2 * total / (n * (n - 1))) - - -def main() -> None: - sample_size = 100 - calls = 1_000 - sample = np.random.default_rng(42).uniform(0.0, 1.0, sample_size) - statistic = SteinUniformGofStatistic() - - # Compile the Numba kernel before measuring execution time. - statistic.do_execute_statistic(sample) - runner = BenchmarkRunner(calls) - - runner.run_comparison( - sample_size=sample.size, - reference_name="Python reference implementation", - reference_function=lambda: stein_uniform_reference(sample), - optimized_name="Numba implementation", - optimized_function=lambda: statistic.do_execute_statistic(sample), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_watson_hyperbolic.py b/benchmarks/benchmark_watson_hyperbolic.py deleted file mode 100644 index 9b188a05..00000000 --- a/benchmarks/benchmark_watson_hyperbolic.py +++ /dev/null @@ -1,47 +0,0 @@ -import numpy as np -from benchmark_runner import BenchmarkRunner -from hyperbolic_benchmark_utils import ( - ALPHA, - BETA, - CALLS, - DELTA, - MU, - SAMPLE_SIZE, - cdf_values, - create_sorted_sample, -) - -from pysatl_criterion.statistics.goodness_of_fit.hyperbolic import WatsonHyperbolicGofStatistic - - -def reference(cdf: np.ndarray) -> float: - """Calculate the statistic using vectorized NumPy operations.""" - n = len(cdf) - expected = (2.0 * np.arange(n) + 1.0) / (2.0 * n) - cvm = 1.0 / (12.0 * n) + np.sum((expected - cdf) ** 2) - return float(cvm - n * (np.mean(cdf) - 0.5) ** 2) - - -def main() -> None: - """Compare the NumPy and Numba statistic kernels.""" - cdf = cdf_values(create_sorted_sample()) - statistic = WatsonHyperbolicGofStatistic( - alpha=ALPHA, - beta=BETA, - delta=DELTA, - mu=MU, - ) - optimized_result = statistic.do_execute_statistic(cdf) - np.testing.assert_allclose(optimized_result, reference(cdf)) - - BenchmarkRunner(CALLS).run_comparison( - sample_size=SAMPLE_SIZE, - reference_name="NumPy reference statistic kernel", - reference_function=lambda: reference(cdf), - optimized_name="Numba statistic kernel", - optimized_function=lambda: statistic.do_execute_statistic(cdf), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/benchmark_watson_laplace.py b/benchmarks/benchmark_watson_laplace.py deleted file mode 100644 index 04504401..00000000 --- a/benchmarks/benchmark_watson_laplace.py +++ /dev/null @@ -1,68 +0,0 @@ -import numpy as np -import scipy.stats as scipy_stats -from benchmark_runner import BenchmarkRunner - -from pysatl_criterion.statistics.goodness_of_fit.laplace import WatsonLaplaceGofStatistic - - -def watson_laplace_reference( - sorted_sample: np.ndarray, - location: float, - scale: float, -) -> float: - """Calculate the Watson statistic using the original SciPy approach.""" - n = len(sorted_sample) - cdf_values = scipy_stats.laplace.cdf( - sorted_sample, - loc=location, - scale=scale, - ) - expected_cdf = (2 * np.arange(1, n + 1) - 1) / (2 * n) - differences = cdf_values - expected_cdf - - w_squared = 1.0 / (12 * n) + np.sum(differences**2) - mean_adjustment = np.sum(cdf_values) - n / 2 - - return float(w_squared - mean_adjustment**2 / n) - - -def main() -> None: - location = 0.0 - scale = 1.0 - calls = 1_000 - sample = np.random.default_rng(42).laplace( - loc=location, - scale=scale, - size=10_000, - ) - sorted_sample = np.sort(sample) - statistic = WatsonLaplaceGofStatistic( - t=location, - s=scale, - ) - - # Compile the Numba kernel before measuring execution time. - optimized_result = statistic.do_execute_statistic(sorted_sample) - reference_result = watson_laplace_reference( - sorted_sample, - location, - scale, - ) - np.testing.assert_allclose(optimized_result, reference_result) - runner = BenchmarkRunner(calls) - - runner.run_comparison( - sample_size=sample.size, - reference_name="SciPy reference implementation", - reference_function=lambda: watson_laplace_reference( - sorted_sample, - location, - scale, - ), - optimized_name="Numba implementation", - optimized_function=lambda: statistic.do_execute_statistic(sorted_sample), - ) - - -if __name__ == "__main__": - main() diff --git a/benchmarks/hyperbolic_benchmark_utils.py b/benchmarks/hyperbolic_benchmark_utils.py deleted file mode 100644 index 2df7f560..00000000 --- a/benchmarks/hyperbolic_benchmark_utils.py +++ /dev/null @@ -1,54 +0,0 @@ -import numpy as np -import scipy.stats as scipy_stats - - -ALPHA = 1.5 -BETA = 0.25 -DELTA = 1.0 -MU = 0.0 -CALLS = 1_000 -SAMPLE_SIZE = 10_000 - - -def create_sorted_sample() -> np.ndarray: - """Generate one reproducible sorted hyperbolic sample.""" - sample = scipy_stats.genhyperbolic.rvs( - p=1.0, - a=ALPHA * DELTA, - b=BETA * DELTA, - loc=MU, - scale=DELTA, - size=SAMPLE_SIZE, - random_state=np.random.default_rng(42), - ) - return np.sort(np.asarray(sample, dtype=np.float64)) - - -def cdf_values(sorted_sample: np.ndarray) -> np.ndarray: - """Calculate reference CDF values outside the timed statistic kernels.""" - values = scipy_stats.genhyperbolic.cdf( - sorted_sample, - p=1.0, - a=ALPHA * DELTA, - b=BETA * DELTA, - loc=MU, - scale=DELTA, - ) - return np.asarray(values, dtype=np.float64) - - -def log_probabilities(sorted_sample: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Calculate stable tail probabilities outside the timed AD kernels.""" - parameters = { - "p": 1.0, - "a": ALPHA * DELTA, - "b": BETA * DELTA, - "loc": MU, - "scale": DELTA, - } - log_cdf = scipy_stats.genhyperbolic.logcdf(sorted_sample, **parameters) - log_sf = scipy_stats.genhyperbolic.logsf(sorted_sample, **parameters) - return ( - np.asarray(log_cdf, dtype=np.float64), - np.asarray(log_sf, dtype=np.float64), - ) diff --git a/docs/criteria/goodness-of-fit/beta/anderson_darling_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/anderson_darling_beta_criterion.md index 7b19895d..80c82e2d 100644 --- a/docs/criteria/goodness-of-fit/beta/anderson_darling_beta_criterion.md +++ b/docs/criteria/goodness-of-fit/beta/anderson_darling_beta_criterion.md @@ -1,55 +1,56 @@ -# Anderson-Darling test for beta distribution +# Anderson–Darling for a specified Beta distribution -## Description -Performs Anderson-Darling goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The test gives additional weight to discrepancies in the distribution tails. +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. +Class: `AndersonDarlingBetaGofStatistic`. Code: `AD_BETA_GOODNESS_OF_FIT`. -Test Statistic -The statistic is computed from the log cumulative distribution function and log survival function of the reference beta distribution. +## Hypothesis and formula -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - AndersonDarlingBetaGofStatistic, -) - - -test_statistic = AndersonDarlingBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1)[\log u_i+\log(1-u_{n+1-i})] +$$ -`rvs` - array-like sample data passed to `execute_statistic`. -## Details -For ordered observations $X_{(i)}$, the implementation evaluates beta `logcdf` and `logsf` values and computes +## Input, result and calibration -$$ A_n^2 = -n - \sum_{i=1}^{n}\frac{2i - 1}{n}\left(\log F_0(X_{(i)}) + \log(1 - F_0(X_{(n+1-i)}))\right). $$ +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. -Large values indicate stronger deviation from the beta model. +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov +## Example -## References -Anderson, T.W. and Darling, D.A. (1952): Asymptotic theory of certain goodness of fit criteria based on stochastic processes. - Annals of Mathematical Statistics, vol. 23, pp. 193-212. - -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( AndersonDarlingBetaGofStatistic, ) - -test_statistic = AndersonDarlingBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) +statistic = AndersonDarlingBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) ``` + +## Scientific source + +[Anderson and Darling (1952), Asymptotic Theory of Certain Goodness of Fit Criteria Based on Stochastic Processes](https://doi.org/10.1214/aoms/1177729437); [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.2. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/chi2_pearson_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/chi2_pearson_beta_criterion.md index d595c63c..cecdfa22 100644 --- a/docs/criteria/goodness-of-fit/beta/chi2_pearson_beta_criterion.md +++ b/docs/criteria/goodness-of-fit/beta/chi2_pearson_beta_criterion.md @@ -1,51 +1,61 @@ -# Pearson chi-squared test for beta distribution +# Pearson chi-squared for a specified Beta distribution -## Description -Performs Pearson's chi-squared goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The implementation compares observed histogram bin counts with expected counts under the reference beta distribution. +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. +Class: `Chi2PearsonBetaGofStatistic`. Code: `CHI2_PEARSON_BETA_GOODNESS_OF_FIT`. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Chi2PearsonBetaGofStatistic, -) +## Hypothesis and formula +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. -test_statistic = Chi2PearsonBetaGofStatistic(alpha=2, beta=5, lambda_=1) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +For bins $j=1,\ldots,J$, write $O_j$ for the observed count and $E_j=np_j>0$ +for the expected count under the specified Beta law. -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. +$$ +X^2=\sum_j\frac{(O_j-E_j)^2}{E_j} +$$ -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. +With an empty observed cell and positive expected count, Pearson contributes $E_j$, Freeman–Tukey $4E_j$, modified log-likelihood and Neyman infinity, and Cressie–Read zero. -`lambda_` - power-divergence parameter passed to the common chi-squared statistic implementation. Default value is `1`. +## Input, result and calibration -`rvs` - array-like sample data passed to `execute_statistic`. +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. -## Details -The implementation uses approximately $\sqrt n$ bins on $[0, 1]$. -Expected frequencies are computed from beta CDF differences at the bin edges. +The constructor accepts `binning: BinningStrategy`; the default is +`EqualProbabilityBins()` with `PowerCount(coefficient=2, exponent=0.4)`, +a maximum of 1000 bins and no minimum expected-count pooling. +CDF-space boundaries belong to the cell on their right; 1 belongs to the last cell. +See [binning strategies](../binning/index.md). Each of the five divergences has +its own class; `lambda_` is not a supported constructor argument. -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov +For fixed deterministic bins with positive probabilities the usual asymptotic +null is chi-square with $J-1$ degrees of freedom, with no fitted-shape deduction. +That statement does not justify a fixed-degree limit for a growing number of bins +or data-dependent boundaries. Calibrate using the same binning rule and sample size. +Storage identity includes the serialized binning configuration. -## References -Pearson, K. (1900): On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling. - Philosophical Magazine, vol. 50, pp. 157-175. +## Example -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Chi2PearsonBetaGofStatistic, +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import Chi2PearsonBetaGofStatistic +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins, FixedCount + +statistic = Chi2PearsonBetaGofStatistic( + Beta.DEFAULT.parse({"a": 2, "b": 5}), binning=EqualProbabilityBins(count=FixedCount(3)) ) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` +## Scientific source -test_statistic = Chi2PearsonBetaGofStatistic(alpha=2, beta=5, lambda_=1) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +[Pearson (1900), On the criterion that a given system of deviations from the probable …](https://doi.org/10.1080/14786440009463897); [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/cressie_read_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/cressie_read_beta_criterion.md new file mode 100644 index 00000000..0432c48d --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/cressie_read_beta_criterion.md @@ -0,0 +1,61 @@ +# Cressie–Read for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `CressieReadBetaGofStatistic`. Code: `CRESSIE_READ_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For bins $j=1,\ldots,J$, write $O_j$ for the observed count and $E_j=np_j>0$ +for the expected count under the specified Beta law. + +$$ +CR=\frac95\sum_j O_j\left[(O_j/E_j)^{2/3}-1\right] +$$ + +With an empty observed cell and positive expected count, Pearson contributes $E_j$, Freeman–Tukey $4E_j$, modified log-likelihood and Neyman infinity, and Cressie–Read zero. + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +The constructor accepts `binning: BinningStrategy`; the default is +`EqualProbabilityBins()` with `PowerCount(coefficient=2, exponent=0.4)`, +a maximum of 1000 bins and no minimum expected-count pooling. +CDF-space boundaries belong to the cell on their right; 1 belongs to the last cell. +See [binning strategies](../binning/index.md). Each of the five divergences has +its own class; `lambda_` is not a supported constructor argument. + +For fixed deterministic bins with positive probabilities the usual asymptotic +null is chi-square with $J-1$ degrees of freedom, with no fitted-shape deduction. +That statement does not justify a fixed-degree limit for a growing number of bins +or data-dependent boundaries. Calibrate using the same binning rule and sample size. +Storage identity includes the serialized binning configuration. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import CressieReadBetaGofStatistic +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins, FixedCount + +statistic = CressieReadBetaGofStatistic( + Beta.DEFAULT.parse({"a": 2, "b": 5}), binning=EqualProbabilityBins(count=FixedCount(3)) +) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=2/3$. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/cvm_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/cvm_beta_criterion.md index cc6cb564..018eaea9 100644 --- a/docs/criteria/goodness-of-fit/beta/cvm_beta_criterion.md +++ b/docs/criteria/goodness-of-fit/beta/cvm_beta_criterion.md @@ -1,57 +1,56 @@ -# Cramer-von Mises test for beta distribution +# Cramér–von Mises for a specified Beta distribution -## Description -Performs Cramer-von Mises goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic accumulates squared differences between the empirical distribution function and the theoretical beta cumulative distribution function. +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. +Class: `CrammerVonMisesBetaGofStatistic`. Code: `CVM_BETA_GOODNESS_OF_FIT`. -Test Statistic -The observations are sorted, transformed by the reference beta cumulative distribution function, and compared with expected uniform plotting positions. +## Hypothesis and formula -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CrammerVonMisesBetaGofStatistic, -) - - -test_statistic = CrammerVonMisesBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. +$$ +W^2=\frac{1}{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2 +$$ -`rvs` - array-like sample data passed to `execute_statistic`. -## Details -The Cramer-von Mises statistic is +## Input, result and calibration -$$ W_n^2 = \frac{1}{12n} + \sum_{i=1}^{n} \left(F_0(X_{(i)}) - \frac{2i - 1}{2n}\right)^2 $$ +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. -where $F_0$ is the reference beta cumulative distribution function. +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov +## Example -## References -Cramer, H. (1928): On the composition of elementary errors. - Skandinavisk Aktuarietidskrift, vol. 11, pp. 141-180. - -von Mises, R. (1931): Wahrscheinlichkeitsrechnung und ihre Anwendung in der Statistik und theoretischen Physik. - Leipzig: Deuticke. - -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( CrammerVonMisesBetaGofStatistic, ) - -test_statistic = CrammerVonMisesBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) +statistic = CrammerVonMisesBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) ``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.3. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/ebner_liebenberg_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/ebner_liebenberg_beta_criterion.md new file mode 100644 index 00000000..7032e490 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/ebner_liebenberg_beta_criterion.md @@ -0,0 +1,162 @@ +# Ebner–Liebenberg test for the Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Description + +The criterion tests the composite null hypothesis + +$$ +H_0: X_1,\ldots,X_n \overset{\mathrm{iid}}{\sim} +\operatorname{Beta}(a,b), \qquad a,b>0, +$$ + +against general alternatives on the fixed support $[0,1]$. Both shape +parameters are unknown and fitted by maximum likelihood on each sample; +location and scale remain fixed at 0 and 1. + +The test is based on the conditional-moment characterization of the Beta +family in Ebner and Liebenberg. Large values of the statistic provide evidence +against the null hypothesis. This is the new statistic proposed in the paper, +not the fitted Kolmogorov–Smirnov statistic used there as a competitor. + +## Usage + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous import EbnerLiebenbergBetaGofStatistic + +statistic = EbnerLiebenbergBetaGofStatistic(Beta.DEFAULT.parse({})) +sample = [0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57] +value = statistic.execute_statistic(sample) +print(value) +``` + +## Arguments and return value + +| Argument | Meaning | +| --- | --- | +| `parameters` | `Beta.DEFAULT.parse({})`: neither shape is fixed. Supplying either shape is unsupported. | +| `rvs` | One-dimensional sample of at least two finite real observations strictly inside `(0, 1)`. The sample must be nonconstant. | +| `**kwargs` | Reserved for interface compatibility; ignored. | + +`execute_statistic` returns a nonnegative Python `float`. The class computes +only the statistic, without a p-value or a hypothesis decision. Fitted shapes +are local to each call and do not change `hypothesis().parameters()`, which +remains `{}`. The input sample is not modified. + +Invalid samples, including endpoints, masked observations and constant +samples, raise `ValueError`. Failures of the maximum-likelihood solver +propagate to the caller. Nonfinite numerical results or materially negative +residuals also raise `ValueError`; negative residuals within the implementation's +roundoff tolerance are set to zero. + +The short identifier is `EL`. `alternative()` returns `RightAlternative`. + +## Test statistic + +Let $\hat a,\hat b$ be the maximum-likelihood estimates and define +$c_j=(\hat a+\hat b)x_j-\hat a$. The integral definition is + +$$ +T_n=n\int_0^1\left[ +\frac1n\sum_{j=1}^n c_j\mathbf1\{x_j\ge t\} +-\frac{t^{\hat a}(1-t)^{\hat b}}{B(\hat a,\hat b)} +\right]^2dt. +$$ + +Here $B$ is the beta function. Equation (3) of the source gives + +$$ +\begin{aligned} +T_n={}&\frac1n\sum_{j,k=1}^n c_jc_k\min(x_j,x_k)\\ +&-2\frac{B(\hat a+1,\hat b+1)}{B(\hat a,\hat b)} +\sum_{j=1}^n c_j F_{\hat a+1,\hat b+1}(x_j)\\ +&+n\frac{B(2\hat a+1,2\hat b+1)}{B(\hat a,\hat b)^2}, +\end{aligned} +$$ + +where $F_{a,b}$ is the Beta CDF. + +For sorted observations, set $x_{(0)}=0$ and +$S_i=\sum_{j=i}^n c_{(j)}$. The implementation evaluates the first term as + +$$ +\frac1n\sum_{i=1}^n (x_{(i)}-x_{(i-1)})S_i^2. +$$ + +This avoids an $n\times n$ matrix. After parameter fitting, evaluating the +statistic requires $O(n\log n)$ time and $O(n)$ memory. The last beta-function +ratio uses logarithms, and the cross-term ratio uses the identity +$B(a+1,b+1)/B(a,b)=ab/[(a+b)(a+b+1)]$. + +## Calibration + +The null distribution depends on the unknown shapes. Section 2 of the paper +uses a parametric bootstrap: + +1. Fit both shapes to the observed sample and calculate its statistic. +2. Generate bootstrap samples of the same size from the fitted Beta law. +3. Calculate the statistic on every bootstrap sample, **refitting both shapes + each time**. +4. Reject when the observed statistic exceeds the empirical upper critical + quantile at the chosen significance level. + +The hypothesis-testing layer implements this procedure with reproducible RNG: + +```python +from pysatl_criterion.hypothesis_testing.beta_bootstrap import parametric_bootstrap_beta +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + EbnerLiebenbergBetaGofStatistic, +) + +statistic = EbnerLiebenbergBetaGofStatistic(Beta.DEFAULT.parse({})) +sample = [0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57] +result = parametric_bootstrap_beta( + statistic, sample, significance_level=0.05, n_resamples=1999, random_state=2026 +) +print(result.statistic, result.critical_value, result.p_value, result.rejected) +``` + +The function uses the inverse empirical CDF for the upper critical quantile. +`rejected` means strictly greater than that quantile, following the paper. +The reported p-value is $(1+\#\{T_b^*\ge T_n\})/(B+1)$, where $B$ is +`n_resamples`; its decision can differ from the critical-value decision at +finite $B$. Every replicate is refitted. Fit failures propagate; simulated +endpoints caused by floating-point rounding are neither clipped nor dropped. + +The p-value is a bootstrap approximation; the correction does not make a +composite-null bootstrap exact in finite samples. More replicates reduce +simulation error. Universal critical values or arbitrary Beta(1, 1) +calibration are inappropriate. An empty composite hypothesis alone does not +specify the generating shapes; calibration needs the observed sample. + +## Null limit, consistency and implementation + +The null limit is $\sum_{j\ge1}\lambda_j(a,b)Z_j^2$, with independent +standard normal $Z_j$ and eigenvalues of the fitted-process covariance +operator (Corollary 2.2). The weights depend on both shapes. Section 3 proves +consistency against alternatives for which the shape estimators converge to +finite positive limits, as assumed in equation (6). This is an omnibus +characterization under those conditions, not an unconditional assertion for +all possible samples or endpoint-contaminated distributions. + +[Statistic implementation](https://github.com/PySATL/pysatl-criterion/blob/main/src/pysatl_criterion/statistics/goodness_of_fit/continuous/beta/beta_statistics.py) +and [bootstrap implementation](https://github.com/PySATL/pysatl-criterion/blob/main/src/pysatl_criterion/hypothesis_testing/beta_bootstrap.py). +The full identifier is `EL_BETA_GOODNESS_OF_FIT`. + +## References + +B. Ebner and S. C. Liebenberg, +[On a new test of fit to the beta distribution](https://arxiv.org/pdf/2009.13995) +(2020 preprint), Corollary 1.2, equation (3), and Section 2. + +Ebner, B., Liebenberg, S. C. (2021). *On a new test of fit to the beta distribution.* +Stat, 10, e341. DOI: [10.1002/sta4.341](https://doi.org/10.1002/sta4.341). + +## Stored calibration + +`StorageLimitDistributionResolver` rejects this composite hypothesis because +the storage key lacks fitted shapes. Use `parametric_bootstrap_beta` with the +observed sample; a stored law indexed only by code and sample size is invalid. diff --git a/docs/criteria/goodness-of-fit/beta/entropy_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/entropy_beta_criterion.md deleted file mode 100644 index 6ce4f34b..00000000 --- a/docs/criteria/goodness-of-fit/beta/entropy_beta_criterion.md +++ /dev/null @@ -1,51 +0,0 @@ -# Entropy test for beta distribution - -## Description -Performs entropy-based goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic compares a spacing-based sample entropy estimate with the theoretical entropy of the beta distribution. - -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - EntropyBetaGofStatistic, -) - - -test_statistic = EntropyBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. - -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. - -`m` - optional window size for the spacing-based entropy estimator, passed to `execute_statistic`. Default value is `n // 4`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation uses a Vasicek-style spacing entropy estimator on the sorted sample. -It compares this estimate with the theoretical beta entropy computed from `betaln` and digamma terms. - -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -Vasicek, O. (1976): A test for normality based on sample entropy. - Journal of the Royal Statistical Society, Series B, vol. 38, pp. 54-59. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - EntropyBetaGofStatistic, -) - - -test_statistic = EntropyBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/beta/freeman_tukey_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/freeman_tukey_beta_criterion.md new file mode 100644 index 00000000..c4c55fc3 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/freeman_tukey_beta_criterion.md @@ -0,0 +1,61 @@ +# Freeman–Tukey for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `FreemanTukeyBetaGofStatistic`. Code: `FREEMAN_TUKEY_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For bins $j=1,\ldots,J$, write $O_j$ for the observed count and $E_j=np_j>0$ +for the expected count under the specified Beta law. + +$$ +FT=4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2 +$$ + +With an empty observed cell and positive expected count, Pearson contributes $E_j$, Freeman–Tukey $4E_j$, modified log-likelihood and Neyman infinity, and Cressie–Read zero. + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +The constructor accepts `binning: BinningStrategy`; the default is +`EqualProbabilityBins()` with `PowerCount(coefficient=2, exponent=0.4)`, +a maximum of 1000 bins and no minimum expected-count pooling. +CDF-space boundaries belong to the cell on their right; 1 belongs to the last cell. +See [binning strategies](../binning/index.md). Each of the five divergences has +its own class; `lambda_` is not a supported constructor argument. + +For fixed deterministic bins with positive probabilities the usual asymptotic +null is chi-square with $J-1$ degrees of freedom, with no fitted-shape deduction. +That statement does not justify a fixed-degree limit for a growing number of bins +or data-dependent boundaries. Calibrate using the same binning rule and sample size. +Storage identity includes the serialized binning configuration. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import FreemanTukeyBetaGofStatistic +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins, FixedCount + +statistic = FreemanTukeyBetaGofStatistic( + Beta.DEFAULT.parse({"a": 2, "b": 5}), binning=EqualProbabilityBins(count=FixedCount(3)) +) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence parameter $\lambda=-1/2$. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/index.md b/docs/criteria/goodness-of-fit/beta/index.md new file mode 100644 index 00000000..44b74be6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/index.md @@ -0,0 +1,96 @@ +# Beta goodness-of-fit criteria + +The package `pysatl_criterion.statistics.goodness_of_fit.continuous.beta` exports +**23 concrete criteria**: 13 EDF, 5 frequency, Neyman smooth and 4 fitted-Beta tests. Every criterion has a page below. +See the [mathematical verification report](mathematical-validation.md) for +formula checks, numerical regressions and the limits of the scientific attribution. + +## Package layout + +The layout follows `continuous/uniform`: + +```text +continuous/beta/ +├── __init__.py # public exports and stable class module paths +├── __init__.pyi # generated public type declarations +└── beta_statistics.py # implementations and dynamic EDF/frequency catalogs +``` + +Existing imports from `continuous.beta` remain valid. The public module paths +are preserved for discovery and previously serialized class references. +Regenerate the stub with `python scripts/generate_beta_stub.py`; use `--check` +to detect drift. The generator reads the implementation without importing the +package and uses the project's Ruff formatter. + +## Hypotheses and calibration + +The support is fixed at $[0,1]$, with positive finite shapes $a,b$. +For the 19 specified-null criteria use `Beta.DEFAULT.parse({"a": 2, "b": 5})`. +Both shapes must be chosen independently of the tested sample; there are no +default shape values. +For Ebner–Liebenberg, Raschke, Riad–Abd El Mabood and Kullback–Leibler use `Beta.DEFAULT.parse({})`; both shapes are +estimated by maximum likelihood for every sample. Partially specified shapes +are not supported by these 23 classes. + +All criteria return scalar statistics and reject large values. Executing a +statistic does not compute a p-value. Fixed-null EDF and smooth statistics use +the probability integral transform; fitted-Beta tests require a parametric +bootstrap with refitting. + +## Complete catalog + +Full identifiers append `_BETA_GOODNESS_OF_FIT` to the short codes below. +`CrammerVonMisesBetaGofStatistic` is the exported spelling; no alternative alias +is supplied. KS D+ and D− are separate classes. Frequency settings use `binning`, +not `lambda_`; Watson's short code is `WATSON`. + +| Criterion | Class | Short code | Status and hypothesis | +|-----------------------------------------------------------------------|-------------------------------------------|---------------------------|----------------------------------------------| +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_beta_criterion.md) | `KolmogorovSmirnovDPlusBetaGofStatistic` | `KS_PLUS` | EDF; fixed shapes | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_beta_criterion.md) | `KolmogorovSmirnovDMinusBetaGofStatistic` | `KS_MINUS` | EDF; fixed shapes | +| [Kolmogorov–Smirnov](kolmogorov_smirnov_beta_criterion.md) | `KolmogorovSmirnovBetaGofStatistic` | `KS` | EDF; fixed shapes | +| [Anderson–Darling](anderson_darling_beta_criterion.md) | `AndersonDarlingBetaGofStatistic` | `AD` | EDF; fixed shapes | +| [Cramér–von Mises](cvm_beta_criterion.md) | `CrammerVonMisesBetaGofStatistic` | `CVM` | EDF; fixed shapes | +| [Liao–Shimokawa](liao_shimokawa_beta_criterion.md) | `LiaoShimokawaBetaGofStatistic` | `LS` | EDF; fixed shapes | +| [Watson](watson_beta_criterion.md) | `WatsonBetaGofStatistic` | `WATSON` | EDF; fixed shapes | +| [Kuiper](kuiper_beta_criterion.md) | `KuiperBetaGofStatistic` | `KUIPER` | EDF; fixed shapes | +| [Scaled Kuiper](kuiper_scaled_beta_criterion.md) | `KuiperScaledBetaGofStatistic` | `KUIPER_SCALED` | EDF; fixed shapes | +| [Corrected Kuiper](kuiper_corrected_beta_criterion.md) | `KuiperCorrectedBetaGofStatistic` | `KUIPER_CORRECTED` | EDF; fixed shapes | +| [Zhang Z_K](zhang_k_beta_criterion.md) | `ZhangKBetaGofStatistic` | `ZHANG_ZK` | EDF; fixed shapes | +| [Zhang Z_A](zhang_a_beta_criterion.md) | `ZhangABetaGofStatistic` | `ZHANG_ZA` | EDF; fixed shapes | +| [Zhang Z_C](zhang_c_beta_criterion.md) | `ZhangCBetaGofStatistic` | `ZHANG_ZC` | EDF; fixed shapes | +| [Pearson chi-squared](chi2_pearson_beta_criterion.md) | `Chi2PearsonBetaGofStatistic` | `CHI2_PEARSON` | Frequency; fixed shapes | +| [Freeman–Tukey](freeman_tukey_beta_criterion.md) | `FreemanTukeyBetaGofStatistic` | `FREEMAN_TUKEY` | Frequency; fixed shapes | +| [Modified log-likelihood](modified_log_likelihood_beta_criterion.md) | `ModifiedLogLikelihoodBetaGofStatistic` | `MODIFIED_LOG_LIKELIHOOD` | Frequency; fixed shapes | +| [Neyman chi-squared](neyman_chi2_beta_criterion.md) | `NeymanChi2BetaGofStatistic` | `CHI2_NEYMAN` | Frequency; fixed shapes | +| [Cressie–Read](cressie_read_beta_criterion.md) | `CressieReadBetaGofStatistic` | `CRESSIE_READ` | Frequency; fixed shapes | +| [Neyman smooth](neyman_smooth_beta_criterion.md) | `NeymanSmoothBetaGofStatistic` | `NEYMAN` | Published functional; fixed shapes | +| [Ebner–Liebenberg](ebner_liebenberg_beta_criterion.md) | `EbnerLiebenbergBetaGofStatistic` | `EL` | Published Beta test; both shapes fitted | +| [Raschke](raschke_beta_criterion.md) | `RaschkeBetaGofStatistic` | `RASCHKE` | Published transformation; both shapes fitted | +| [Riad–Abd El Mabood](riad_abd_el_mabood_beta_criterion.md) | `RiadAbdElMaboodBetaGofStatistic` | `RF` | Published functional; both shapes fitted | +| [Kullback–Leibler (Vasicek)](kullback_leibler_beta_criterion.md) | `KullbackLeiblerBetaGofStatistic` | `KL` | Published functional; both shapes fitted | + +The two new pages specify exact formulas and document the limits of full-text +source verification; numerical equivalence to historical tables is not claimed. + +## Examples + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + AndersonDarlingBetaGofStatistic, + EbnerLiebenbergBetaGofStatistic, +) + +sample = [0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57] +fixed = AndersonDarlingBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +fitted = EbnerLiebenbergBetaGofStatistic(Beta.DEFAULT.parse({})) +print(fixed.execute_statistic(sample)) +print(fitted.execute_statistic(sample)) +``` + +For a fitted test, call `parametric_bootstrap_beta` as illustrated on its +individual page. Never reuse a fixed-null EDF table after fitting shapes. +For frequency tests, preserve the [binning strategy](../binning/index.md) +and its count rule in calibration. Existing calibrations from the old +Pearson equal-width default or altered formulas are not interchangeable. diff --git a/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_beta_criterion.md index be0ac404..f29d08b2 100644 --- a/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_beta_criterion.md +++ b/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_beta_criterion.md @@ -1,61 +1,56 @@ -# Kolmogorov-Smirnov test for beta distribution +# Kolmogorov–Smirnov for a specified Beta distribution -## Description -Performs Kolmogorov-Smirnov goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The Kolmogorov-Smirnov test compares the empirical distribution function with the theoretical cumulative distribution function of the beta distribution. +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. +Class: `KolmogorovSmirnovBetaGofStatistic`. Code: `KS_BETA_GOODNESS_OF_FIT`. -Test Statistic -The statistic is based on the maximum distance between the empirical distribution function and the beta cumulative distribution function. +## Hypothesis and formula -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KolmogorovSmirnovBetaGofStatistic, -) - - -test_statistic = KolmogorovSmirnovBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. -`alternative_type` - alternative hypothesis type used by the Kolmogorov-Smirnov statistic. +$$ +D=\max(D^+,D^-),\quad D^+=\max_i(i/n-u_i),\quad D^-=\max_i(u_i-(i-1)/n) +$$ -`mode` - calculation mode passed to the Kolmogorov-Smirnov statistic. Default value is `auto`. -`rvs` - array-like sample data passed to `execute_statistic`. +## Input, result and calibration -## Details -The observations are sorted and transformed with the reference beta cumulative distribution function +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. -$$ F_0(x) = I_x(\alpha, \beta), \quad 0 \le x \le 1. $$ +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. -The transformed values are passed to the common Kolmogorov-Smirnov statistic implementation. +## Example -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -Kolmogorov, A.N. (1933): Sulla determinazione empirica di una legge di distribuzione. - Giornale dell'Istituto Italiano degli Attuari, vol. 4, pp. 83-91. - -Smirnov, N.V. (1948): Table for estimating the goodness of fit of empirical distributions. - Annals of Mathematical Statistics, vol. 19, pp. 279-281. - -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( KolmogorovSmirnovBetaGofStatistic, ) - -test_statistic = KolmogorovSmirnovBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) +statistic = KolmogorovSmirnovBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) ``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.1. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_d_minus_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_d_minus_beta_criterion.md new file mode 100644 index 00000000..524d4302 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_d_minus_beta_criterion.md @@ -0,0 +1,56 @@ +# Kolmogorov–Smirnov D− for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `KolmogorovSmirnovDMinusBetaGofStatistic`. Code: `KS_MINUS_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +D^-=\max_{1\le i\le n}(u_i-(i-1)/n) +$$ + + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + KolmogorovSmirnovDMinusBetaGofStatistic, +) + +statistic = KolmogorovSmirnovDMinusBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.1. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_d_plus_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_d_plus_beta_criterion.md new file mode 100644 index 00000000..999c5fde --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/kolmogorov_smirnov_d_plus_beta_criterion.md @@ -0,0 +1,56 @@ +# Kolmogorov–Smirnov D+ for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `KolmogorovSmirnovDPlusBetaGofStatistic`. Code: `KS_PLUS_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +D^+=\max_{1\le i\le n}(i/n-u_i) +$$ + + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + KolmogorovSmirnovDPlusBetaGofStatistic, +) + +statistic = KolmogorovSmirnovDPlusBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.1. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/kuiper_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kuiper_beta_criterion.md index 51bd9d76..3b032ab5 100644 --- a/docs/criteria/goodness-of-fit/beta/kuiper_beta_criterion.md +++ b/docs/criteria/goodness-of-fit/beta/kuiper_beta_criterion.md @@ -1,52 +1,54 @@ -# Kuiper test for beta distribution +# Kuiper for a specified Beta distribution -## Description -Performs Kuiper goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic combines the largest positive and negative empirical distribution deviations. +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. +Class: `KuiperBetaGofStatistic`. Code: `KUIPER_BETA_GOODNESS_OF_FIT`. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KuiperBetaGofStatistic, -) +## Hypothesis and formula +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. -test_statistic = KuiperBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. +$$ +V=D^++D^-,\quad D^+=\max_i(i/n-u_i),\quad D^-=\max_i(u_i-(i-1)/n) +$$ -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. -`rvs` - array-like sample data passed to `execute_statistic`. +## Input, result and calibration -## Details -The implementation computes +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. -$$ V = D^+ + D^- $$ +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. -where $D^+$ and $D^-$ are the one-sided deviations between empirical plotting positions and beta CDF values. +## Example -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import KuiperBetaGofStatistic -## References -Kuiper, N.H. (1960): Tests concerning random points on a circle. - Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen, Series A, vol. 63, pp. 38-47. +statistic = KuiperBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KuiperBetaGofStatistic, -) +## Scientific source +[Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X), equations (1)–(3). -test_statistic = KuiperBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/kuiper_corrected_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kuiper_corrected_beta_criterion.md new file mode 100644 index 00000000..496cc9f1 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/kuiper_corrected_beta_criterion.md @@ -0,0 +1,57 @@ +# Corrected Kuiper for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `KuiperCorrectedBetaGofStatistic`. Code: `KUIPER_CORRECTED_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +V_c=\left(\sqrt n+0.155+\frac{0.24}{\sqrt n}\right)(D^++D^-) +$$ + +The finite-sample multiplier is part of the statistic; it is not an exact p-value formula. + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + KuiperCorrectedBetaGofStatistic, +) + +statistic = KuiperCorrectedBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X), equations (1)–(3). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/kuiper_scaled_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kuiper_scaled_beta_criterion.md new file mode 100644 index 00000000..c902fdc0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/kuiper_scaled_beta_criterion.md @@ -0,0 +1,54 @@ +# Scaled Kuiper for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `KuiperScaledBetaGofStatistic`. Code: `KUIPER_SCALED_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +V_s=\sqrt n(D^++D^-) +$$ + + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import KuiperScaledBetaGofStatistic + +statistic = KuiperScaledBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X), equations (1)–(3). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/kullback_leibler_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/kullback_leibler_beta_criterion.md new file mode 100644 index 00000000..2907985b --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/kullback_leibler_beta_criterion.md @@ -0,0 +1,78 @@ +# Vasicek–Kullback–Leibler Beta criterion + +`KullbackLeiblerBetaGofStatistic`, code `KL_BETA_GOODNESS_OF_FIT`, estimates +KL divergence from a Beta density with both shapes fitted by maximum likelihood. +The support is fixed at $[0,1]$. + +## Definition + +For the ordered sample $X_{(1)},\ldots,X_{(n)}$, use repeated endpoints: +$X_{(j)}=X_{(1)}$ for $j<1$ and $X_{(j)}=X_{(n)}$ for $j>n$. +For an integer window $1\le m 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +L=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,\ u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}} +$$ + +This is the published EDF functional applied to a specified Beta CDF. The original fitted Weibull/extreme-value critical values do not apply. + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + LiaoShimokawaBetaGofStatistic, +) + +statistic = LiaoShimokawaBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Liao and Shimokawa (1999), A new goodness-of-fit test for Type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/lilliefors_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/lilliefors_beta_criterion.md deleted file mode 100644 index 9ac178ce..00000000 --- a/docs/criteria/goodness-of-fit/beta/lilliefors_beta_criterion.md +++ /dev/null @@ -1,49 +0,0 @@ -# Lilliefors test for beta distribution - -## Description -Performs Lilliefors-type goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The implementation reuses the common Lilliefors statistic calculation with beta cumulative distribution function values. - -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsTestBetaGofStatistic, -) - - -test_statistic = LillieforsTestBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. - -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The sample is sorted and transformed with the reference beta cumulative distribution function. -The transformed values are passed to the common Lilliefors statistic implementation. - -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -Lilliefors, H.W. (1967): On the Kolmogorov-Smirnov test for normality with mean and variance unknown. - Journal of the American Statistical Association, vol. 62, pp. 399-402. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsTestBetaGofStatistic, -) - - -test_statistic = LillieforsTestBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/beta/mathematical-validation.md b/docs/criteria/goodness-of-fit/beta/mathematical-validation.md new file mode 100644 index 00000000..316cb09d --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/mathematical-validation.md @@ -0,0 +1,317 @@ +# Mathematical verification of Beta statistics + +Audit date: **2026-10-14**. Scope: all **23 concrete classes** exported by +`continuous/beta/beta_statistics.py`, including their shared EDF/frequency kernels and +`hypothesis_testing/beta_bootstrap.py`. See the [complete catalog](index.md) +for every class, short code and individual page. + +## Conclusion and scope of the claims + +The implemented definitions were checked algebraically and against independent +numerical references. The current catalog contains 18 generated criteria, +Neyman smooth and four fitted-Beta procedures: Ebner–Liebenberg, Raschke, +Riad–Abd El Mabood and Vasicek–Kullback–Leibler. +References identify published functionals or Beta-specific procedures; their +critical values cannot automatically be reused after fitting parameters. + +Passing formula checks does not establish exact finite-sample significance, +uniform power, or numerical accuracy for every representable positive shape. + +## Null hypotheses and estimation + +$$ +f_{a,b}(x)=\frac{x^{a-1}(1-x)^{b-1}}{B(a,b)},\qquad 00. +$$ + +| Criteria | Hypothesis | Estimation | +|------------------------------------|-----------------------------------------------|-----------------------------------------------------------------------------| +| 13 EDF, 5 frequency, Neyman smooth | Both shapes fixed independently of the sample | None | +| Ebner–Liebenberg | Both shapes unknown; support fixed | Beta MLE on each call | +| Raschke | Both shapes unknown; support fixed | Beta MLE, normal quantile transform, normal location/scale MLE on each call | +| Riad–Abd El Mabood; Vasicek–KL | Both shapes unknown; support fixed | Beta MLE; same weight/window in each bootstrap replicate | + +Specified criteria use `Beta.DEFAULT.parse({"a": 2, "b": 5})`; fitted criteria +use `Beta.DEFAULT.parse({})`. No default or partially fixed shapes are accepted. +All critical regions are right-tailed. Samples must be finite, real and +one-dimensional; masked values are rejected rather than dropped. + +## Generated formula checks + +For sorted observations define $u_i=F_{a,b}(X_{(i)})$, $r_i=i-1/2$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-r_i/n)^2$. Counts are $O_j$ and $E_j=np_j>0$. + +| Criterion | Definition | Source | +|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_beta_criterion.md) | $D^+=\max_{1\le i\le n}(i/n-u_i)$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.1. | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_beta_criterion.md) | $D^-=\max_{1\le i\le n}(u_i-(i-1)/n)$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.1. | +| [Kolmogorov–Smirnov](kolmogorov_smirnov_beta_criterion.md) | $D=\max(D^+,D^-),\quad D^+=\max_i(i/n-u_i),\quad D^-=\max_i(u_i-(i-1)/n)$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.1. | +| [Anderson–Darling](anderson_darling_beta_criterion.md) | $A^2=-n-\frac1n\sum_{i=1}^n(2i-1)[\log u_i+\log(1-u_{n+1-i})]$ | [Anderson and Darling (1952), Asymptotic Theory of Certain Goodness of Fit Criteria Based on Stochastic Processes](https://doi.org/10.1214/aoms/1177729437); [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.2. | +| [Cramér–von Mises](cvm_beta_criterion.md) | $W^2=\frac{1}{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §2.3. | +| [Liao–Shimokawa](liao_shimokawa_beta_criterion.md) | $L=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,\ u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}}$ | [Liao and Shimokawa (1999), A new goodness-of-fit test for Type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). | +| [Watson](watson_beta_criterion.md) | $U^2=W^2-n(\bar u-1/2)^2,\quad W^2=\frac1{12n}+\sum_i[u_i-(i-1/2)/n]^2$ | [Watson (1961), Goodness-of-fit tests on a circle](https://doi.org/10.1093/biomet/48.1-2.109). | +| [Kuiper](kuiper_beta_criterion.md) | $V=D^++D^-,\quad D^+=\max_i(i/n-u_i),\quad D^-=\max_i(u_i-(i-1)/n)$ | [Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X), equations (1)–(3). | +| [Scaled Kuiper](kuiper_scaled_beta_criterion.md) | $V_s=\sqrt n(D^++D^-)$ | [Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X), equations (1)–(3). | +| [Corrected Kuiper](kuiper_corrected_beta_criterion.md) | $V_c=\left(\sqrt n+0.155+\frac{0.24}{\sqrt n}\right)(D^++D^-)$ | [Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X), equations (1)–(3). | +| [Zhang Z_K](zhang_k_beta_criterion.md) | $Z_K=\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right],\quad r_i=i-\tfrac12$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), equation (3.1). | +| [Zhang Z_A](zhang_a_beta_criterion.md) | $Z_A=-\sum_{i=1}^n\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right]$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), equation (3.2). | +| [Zhang Z_C](zhang_c_beta_criterion.md) | $Z_C=\sum_{i=1}^n\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2$ | [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), equation (3.3). | +| [Pearson chi-squared](chi2_pearson_beta_criterion.md) | $X^2=\sum_j\frac{(O_j-E_j)^2}{E_j}$ | [Pearson (1900), On the criterion that a given system of deviations from the probable …](https://doi.org/10.1080/14786440009463897); [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). | +| [Freeman–Tukey](freeman_tukey_beta_criterion.md) | $FT=4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2$ | [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence parameter $\lambda=-1/2$. | +| [Modified log-likelihood](modified_log_likelihood_beta_criterion.md) | $MLL=2\sum_j E_j\log(E_j/O_j)$ | [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=-1$. | +| [Neyman chi-squared](neyman_chi2_beta_criterion.md) | $N=\sum_j\frac{(O_j-E_j)^2}{O_j}$ | [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=-2$. | +| [Cressie–Read](cressie_read_beta_criterion.md) | $CR=\frac95\sum_j O_j\left[(O_j/E_j)^{2/3}-1\right]$ | [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=2/3$. | + +The Beta EDF regression integrates the Beta density to obtain CDF values, +then checks all thirteen statistics at five shape pairs. KS additionally uses +SciPy's one-sided and two-sided tests; CvM, Watson and AD use piecewise numerical +EDF integrals. Zhang and Liao–Shimokawa use explicit rank formulas, independently +of production kernels. The shared-kernel suite adds high-precision Zhang +references and true endpoint limits. The five frequency implementations are +checked against SciPy power divergences with independently constructed bins. + +With fixed shapes the continuous probability integral transform makes EDF null +laws shape-free. Ties can be evaluated, but rounding or discrete observations +change the continuous-null calibration. For fixed deterministic bins and positive +probabilities the usual frequency limit is $\chi^2_{J-1}$. The default +`EqualProbabilityBins()` uses a sample-size-dependent count; a fixed-degree +chi-square claim is not made for that rule. Empty observed cells give infinity +for modified log-likelihood and Neyman, which is mathematically intentional. +Calibration must preserve binning settings; storage keys serialize them. + +## Specialized formula checks + +### Neyman smooth + +For fixed positive integer $k$ and $u_i=F_{a,b}(X_i)$, + +$$T_k=\frac1n\sum_{j=1}^k\left(\sum_i\sqrt{2j+1}P_j(2u_i-1)\right)^2.$$ + +Shifted normalized Legendre polynomials have zero means and identity covariance +under a uniform null, yielding a $\chi^2_k$ limit for fixed $k$. The recurrence +is checked against explicit polynomials of orders 1–4 and endpoint identities +at higher order. The result is shape-free under a fully specified Beta null, +but fixed $k$ does not give omnibus consistency. This applies +[Neyman (1937)](https://doi.org/10.1080/03461238.1937.10404821) through the PIT. +`k != 4` is rejected by the storage-calibration guard; use matching Monte Carlo +simulation. The class does not fit unknown shapes. + +### Ebner–Liebenberg + +With both shapes estimated by MLE and $c_j=(\hat a+\hat b)X_j-\hat a$, +the statistic is $n\int_0^1[n^{-1}\sum_j c_j1\{X_j\ge t\} +-t^{\hat a}(1-t)^{\hat b}/B(\hat a,\hat b)]^2dt$. +The sorted cumulative implementation matches equation (3) of the +[full preprint](https://arxiv.org/pdf/2009.13995), independently checked by +quadrature and a quadratic pairwise sum. Beta-function ratios preserve the +cross and constant terms. Require at least two distinct observations strictly +inside the support. Refitting occurs on each bootstrap replicate; no fitted +state is retained. The paper's bootstrap and consistency statements have +regularity conditions, not an exact finite-sample distribution-free law. + +### Raschke + +The author manuscript's sections 4–5 prescribe Beta MLE, normal quantile +transformation, normal MLE and corrected AD. The implementation uses normal +variance divisor $n$ and correction $1+0.75/n+2.25/n^2$. A separate weighted +EDF integral checks the resulting value. At least three nonconstant interior +observations are required; with two, normal standardization makes the scores +$(-1,1)$ and the statistic constant. Separate Beta tails avoid `1-CDF` +cancellation; unrepresentable normal transforms raise an error. +The paper's normal critical values are approximate. The supplied Beta bootstrap +repeats both fits and is a different calibration; its validity is not implied +by the Ebner–Liebenberg theorem. See [Raschke's page](raschke_beta_criterion.md) +and [author manuscript](https://www.researchgate.net/publication/220504959_The_Biased_Transformation_and_Its_Application_in_Goodness-of-Fit_Tests_for_the_Beta_and_Gamma_Distribution). + +## Numerical boundaries + +EDF underflow is handled with the +[DLMF 8.17.8 identity](https://dlmf.nist.gov/8.17.E8); a failed hypergeometric +evaluation raises an error. True endpoints can legitimately yield infinity. +The fitted criteria require interior, nonconstant samples and propagate fitting +failures. Calibration must preserve the hypothesis and any binning/order settings. + +## Package layout and import compatibility + +Beta follows the uniform package layout: `beta/beta_statistics.py` contains +implementations, `beta/__init__.py` explicitly re-exports the public classes, +and `beta/__init__.pyi` declares their types. The former `beta.py` and +`beta.pyi` are replaced by these package files. +All 25 public classes (23 concrete and two abstract) retain the module path +`pysatl_criterion.statistics.goodness_of_fit.continuous.beta`. Regression checks +cover identity between the package and implementation, old pickle references, +round trips and unique criterion discovery. Private catalogs live in the +implementation module and are not re-exported from the package. + +## Type declarations + +`src/pysatl_criterion/statistics/goodness_of_fit/continuous/beta/__init__.pyi` declares +all 23 concrete criteria and both abstract bases, including generated EDF and +frequency classes. Constructor options `weight`, `window`, `k` and `binning`, +scalar results, NumPy array arguments and class-level numerical helpers are typed. +`tests/distributions/test_beta_stub.py` checks exports, inheritance, method +parameter names and keyword-only defaults against runtime definitions. +The generated stub is maintained with `python scripts/generate_beta_stub.py`; +`python scripts/generate_beta_stub.py --check` verifies that it is current +without importing the package. Generation helpers are methods of +`BetaStubGenerator`, and type annotations are preserved through formatting. +A focused mypy check of the stub and usage examples passed with +`--follow-imports=skip` to isolate unrelated package typing issues. + +## Numba execution and optimization + +All 23 criteria execute numerical reductions through class methods decorated +with `@jit(nopython=True, cache=True)`, without `fastmath`. This does not mean +that SciPy distribution transforms or maximum-likelihood fitting are JIT compiled. + +| Criteria | Compiled computation | Work retained in Python/SciPy | +|---|---|---| +| 13 EDF | Shared EDF and log-tail reduction kernels | Validation, sorting and Beta log tails | +| 5 frequency | Shared frequency divergence kernels | Binning and expected probabilities | +| Ebner–Liebenberg | Tail sums and statistic reduction | MLE, sorting and incomplete Beta functions | +| Neyman smooth | Legendre recurrence and squared-component sums | Validation and Beta CDF | +| Riad–Abd El Mabood | Residual coefficients, compensated pair sum and fallback integrand | MLE and adaptive quadrature controller | +| Vasicek–KL | Fused entropy/log-density reduction | MLE, sorting and scalar `betaln` | +| Raschke | Two-pass normal standardization and AD reduction | Beta MLE and Beta/normal distribution functions | + +KL now computes window gaps, log spacings and log densities in a single loop, +without materializing those arrays. The Laplace fallback computes the minimum +and shifted sample once, and calls a compiled integrand through `quad(args=...)`. +Raschke standardizes in a compiled two-pass calculation using the MLE variance +with denominator n. All new helpers are class methods; the EDF log-probability +callback was also moved into `AbstractSpecifiedBetaGofStatistic`. + +`tests/distributions/test_beta_numba.py` checks that every concrete criterion +executes a nopython kernel, compares the new reductions with independent SciPy +references, and covers degenerate transformations and input preservation. +The existing integral, tail-underflow, negative-KL and quadrature-fallback +regressions remain in the complete run below. + +Local timing on 2026-10-14: median of seven batches of ten complete +`execute_statistic` calls, after JIT warm-up, on Beta(2,5) samples generated +with `np.random.default_rng(234)` separately for each n. Times include fitting. + +| Criterion | n | Before, microseconds | After, microseconds | +|---|---:|---:|---:| +| Vasicek–KL | 100 | 137.2 | 58.4 | +| Vasicek–KL | 1000 | 214.3 | 94.0 | +| Raschke | 100 | 288.1 | 264.1 | +| Raschke | 1000 | 913.7 | 832.3 | +| Riad–Abd El Mabood | 100 | 71.3 | 68.1 | +| Riad–Abd El Mabood | 1000 | 2013.8 | 1933.6 | + +These are local measurements, not portable performance guarantees. Small +Laplace differences may reflect timing variability; its dominant pairwise +kernel was already compiled. First-call compilation cost is excluded. +Observed KL differences were below 6e-15; the other recorded values agreed +at float64 precision for these benchmark samples. + +## Added published criteria: independent checks + +### Riad–Abd El Mabood (2018) + +See the [Laplace criterion](riad_abd_el_mabood_beta_criterion.md) for the complete +formula and [original DOI](https://doi.org/10.17654/AS053020165). +The implementation uses MLE shapes in the Kummer residual with weight $e^{-\rho t}$. +Integrating each pair uses $\int_0^\infty t^k e^{-st}dt=k!/s^{k+1}$. +Tests compare the resulting sum with independent numerical integration of +$L_n,L_n',L_n''$, for multiple weights, shapes and sample sizes. + +**Source discrepancy:** the expanded RF expression in Section 4 of +[Ebner–Liebenberg (published text)](https://publikationen.bibliothek.kit.edu/1000134155/118245046) +prints $\hat\alpha^2$ in the cross-term denominator. From +$A_i=x_i(x_i-1)/\hat\alpha$ and $B_i=1-x_i/\hat\mu$, the cross term +$A_iB_j+A_jB_i$ contains one factor $1/\hat\alpha$, not two. +We implement the squared differential-equation residual, independently +verified by quadrature; the printed expansion is not used verbatim. +Here $\hat\mu=\hat\alpha/(\hat\alpha+\hat\beta)$, as defined in that +published comparison. It is generally different from the sample mean. +The original 2018 full text was unavailable; exact replication of its tables +is not claimed. Default weight 2 is documented and included in configuration. + +### Alizadeh Noughabi–Arghami (2013) + +See the [KL criterion](kullback_leibler_beta_criterion.md) and +[original DOI](https://doi.org/10.1080/00949655.2012.667100). +The original full text was unavailable. The general Vasicek/MLE formula was +verified in [Section 2 of the same author's later paper](https://pmc.ncbi.nlm.nih.gov/articles/PMC9041611/). +Substituting the Beta log density yields the documented statistic. This is +not the previously removed difference between theoretical and sample entropy. +Tests use SciPy's explicit Vasicek estimator and independent Beta log-density +calculation, including boundary window indices, reflection and negative values. +The library window default is explicit and is not attributed to the 2013 +paper. Zero window spacings raise an error; finite negative estimates remain +unchanged. Bootstrap preserves settings and refits both shapes in every draw. + +Both new criteria reject large values. Their tests cover configuration, +invalid settings/samples, no input mutation, permutation invariance and +reproduction of bootstrap p-values. This validates definitions and computation, +not published power tables or exact finite-sample significance. + +## Verification and reproducibility + +The audit runs all Beta suites plus the shared EDF/frequency suites: +`tests/distributions/test_beta*.py`, `tests/statistics/test_beta_dynamic.py`, +`test_beta_mathematical_validation.py`, `test_beta_published.py`, +`test_edf.py`, and `test_frequency.py`. +These cover formula references, sample constraints, hypotheses, endpoints, +small and large shapes, unchanged inputs, fitting and bootstrap reproduction. + +The documentation audit compares runtime concrete classes with all 23 pages, +checks scientific URLs, Python examples, overview/navigation coverage and local +links, then executes every page example. MkDocs checks HTML generation and +math markup; it does not prove browser-side MathJax rendering. + +Historical source access is not uniform: the Ebner–Liebenberg full preprint +and Raschke author manuscript were accessible. DOI access to Zhang, +Liao–Shimokawa, Cressie–Read, Lemeshko and Neyman failed through the +web tool. Their links and shared definitions are documented, but this report +does not claim fresh full-text verification of those articles. + +Normal package initialization currently fails on stale imports of +`AbstractChi2Statistic` and `AbstractCrammerVonMisesStatistic` from `edf.py` +in the common initializer and unrelated distribution modules. The tests and +examples therefore use an isolated `continuous` namespace, without introducing +compatibility aliases into production. This limitation applies to the public +import path and is not concealed by the numerical results. + +Reproduce the isolated test run from the repository root: + +```bash +.venv/bin/python - <<'PYCODE' +import sys +import types +from pathlib import Path +import pytest +name = "pysatl_criterion.statistics.goodness_of_fit.continuous" +package = types.ModuleType(name) +package.__path__ = [str(Path("src/pysatl_criterion/statistics/goodness_of_fit/continuous").resolve())] +sys.modules[name] = package +from pysatl_criterion.statistics.goodness_of_fit.continuous import beta +for export in beta.__all__: + setattr(package, export, getattr(beta, export)) +raise SystemExit(pytest.main([ + *map(str, sorted(Path("tests/distributions").glob("test_beta*.py"))), + "tests/statistics/test_beta_dynamic.py", + "tests/statistics/test_beta_mathematical_validation.py", + "tests/statistics/test_beta_documentation.py", + "tests/statistics/test_beta_published.py", + "tests/statistics/test_edf.py", + "tests/statistics/test_frequency.py", "-q", "--tb=short", +])) +PYCODE +``` + +Measured results for the extended catalog: + +- **680 tests passed** in the isolated run described above, including the independent + formula suites and the Numba execution regressions. +- **23/23 criteria** have a dedicated page, scientific reference, Python example, + overview entry and navigation entry. +- **25 Python example blocks executed successfully**, each in a fresh namespace. +- All Beta Markdown local links resolve. +- MkDocs built successfully. Existing warnings concern other documentation sections. +- Ruff passed for the implementation and both new numerical test suites. + +Ordinary package imports remain blocked by the unrelated obsolete imports +listed above. No compatibility aliases were added. diff --git a/docs/criteria/goodness-of-fit/beta/mode_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/mode_beta_criterion.md deleted file mode 100644 index 4d8fe5f5..00000000 --- a/docs/criteria/goodness-of-fit/beta/mode_beta_criterion.md +++ /dev/null @@ -1,52 +0,0 @@ -# Mode test for beta distribution - -## Description -Performs mode-based goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic compares an estimated sample mode with the theoretical beta distribution mode. - -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with shape parameters `alpha > 1` and `beta > 1` on the interval $[0, 1]$. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ModeBetaGofStatistic, -) - - -test_statistic = ModeBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first shape parameter of the beta distribution. Must be greater than `1`. Default value is `2`. - -`beta` - second shape parameter of the beta distribution. Must be greater than `1`. Default value is `2`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -For `alpha > 1` and `beta > 1`, the beta distribution mode is - -$$ \frac{\alpha - 1}{\alpha + \beta - 2}. $$ - -The implementation estimates the sample mode with a Gaussian kernel density estimate on a grid and returns a scaled absolute difference from the theoretical mode. - -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.beta`. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ModeBetaGofStatistic, -) - - -test_statistic = ModeBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/beta/modified_log_likelihood_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/modified_log_likelihood_beta_criterion.md new file mode 100644 index 00000000..a3499243 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/modified_log_likelihood_beta_criterion.md @@ -0,0 +1,63 @@ +# Modified log-likelihood for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `ModifiedLogLikelihoodBetaGofStatistic`. Code: `MODIFIED_LOG_LIKELIHOOD_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For bins $j=1,\ldots,J$, write $O_j$ for the observed count and $E_j=np_j>0$ +for the expected count under the specified Beta law. + +$$ +MLL=2\sum_j E_j\log(E_j/O_j) +$$ + +With an empty observed cell and positive expected count, Pearson contributes $E_j$, Freeman–Tukey $4E_j$, modified log-likelihood and Neyman infinity, and Cressie–Read zero. + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +The constructor accepts `binning: BinningStrategy`; the default is +`EqualProbabilityBins()` with `PowerCount(coefficient=2, exponent=0.4)`, +a maximum of 1000 bins and no minimum expected-count pooling. +CDF-space boundaries belong to the cell on their right; 1 belongs to the last cell. +See [binning strategies](../binning/index.md). Each of the five divergences has +its own class; `lambda_` is not a supported constructor argument. + +For fixed deterministic bins with positive probabilities the usual asymptotic +null is chi-square with $J-1$ degrees of freedom, with no fitted-shape deduction. +That statement does not justify a fixed-degree limit for a growing number of bins +or data-dependent boundaries. Calibrate using the same binning rule and sample size. +Storage identity includes the serialized binning configuration. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + ModifiedLogLikelihoodBetaGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins, FixedCount + +statistic = ModifiedLogLikelihoodBetaGofStatistic( + Beta.DEFAULT.parse({"a": 2, "b": 5}), binning=EqualProbabilityBins(count=FixedCount(3)) +) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=-1$. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/moment_based_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/moment_based_beta_criterion.md deleted file mode 100644 index fed97968..00000000 --- a/docs/criteria/goodness-of-fit/beta/moment_based_beta_criterion.md +++ /dev/null @@ -1,56 +0,0 @@ -# Moment-based test for beta distribution - -## Description -Performs moment-based goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic compares sample mean and sample variance with the theoretical beta distribution moments. - -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MomentBasedBetaGofStatistic, -) - - -test_statistic = MomentBasedBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. - -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -For a beta distribution, - -$$ E[X] = \frac{\alpha}{\alpha + \beta} $$ - -and - -$$ Var(X) = \frac{\alpha\beta}{(\alpha + \beta)^2(\alpha + \beta + 1)}. $$ - -The implementation combines squared standardized differences for the sample mean and sample variance. - -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.beta`. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MomentBasedBetaGofStatistic, -) - - -test_statistic = MomentBasedBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/beta/neyman_chi2_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/neyman_chi2_beta_criterion.md new file mode 100644 index 00000000..e9e211ee --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/neyman_chi2_beta_criterion.md @@ -0,0 +1,61 @@ +# Neyman chi-squared for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `NeymanChi2BetaGofStatistic`. Code: `CHI2_NEYMAN_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For bins $j=1,\ldots,J$, write $O_j$ for the observed count and $E_j=np_j>0$ +for the expected count under the specified Beta law. + +$$ +N=\sum_j\frac{(O_j-E_j)^2}{O_j} +$$ + +With an empty observed cell and positive expected count, Pearson contributes $E_j$, Freeman–Tukey $4E_j$, modified log-likelihood and Neyman infinity, and Cressie–Read zero. + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +The constructor accepts `binning: BinningStrategy`; the default is +`EqualProbabilityBins()` with `PowerCount(coefficient=2, exponent=0.4)`, +a maximum of 1000 bins and no minimum expected-count pooling. +CDF-space boundaries belong to the cell on their right; 1 belongs to the last cell. +See [binning strategies](../binning/index.md). Each of the five divergences has +its own class; `lambda_` is not a supported constructor argument. + +For fixed deterministic bins with positive probabilities the usual asymptotic +null is chi-square with $J-1$ degrees of freedom, with no fitted-shape deduction. +That statement does not justify a fixed-degree limit for a growing number of bins +or data-dependent boundaries. Calibrate using the same binning rule and sample size. +Storage identity includes the serialized binning configuration. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import NeymanChi2BetaGofStatistic +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins, FixedCount + +statistic = NeymanChi2BetaGofStatistic( + Beta.DEFAULT.parse({"a": 2, "b": 5}), binning=EqualProbabilityBins(count=FixedCount(3)) +) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=-2$. + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/neyman_smooth_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/neyman_smooth_beta_criterion.md new file mode 100644 index 00000000..dff7c21b --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/neyman_smooth_beta_criterion.md @@ -0,0 +1,72 @@ +# Neyman smooth test for the Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Description + +Tests the simple hypothesis of iid observations from $\mathrm{Beta}(a,b)$ +on $[0,1]$, with specified $a,b>0$. Both shapes must be fixed independently +of the observations. This is Neyman's uniform smooth test after the probability +integral transform, not a new Beta-specific polynomial construction. + +## Usage + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous import NeymanSmoothBetaGofStatistic + +statistic = NeymanSmoothBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5}), k=4) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +``` + +## Arguments and statistic + +`parameters` specifies both positive finite shapes; partial hypotheses are +rejected. `k` is a positive integer (default 4), chosen before examining the +sample. `rvs` is a nonempty one-dimensional finite real sample in $[0,1]$; +masked observations are rejected. A single observation and endpoints are valid. +Invalid inputs raise `ValueError` (invalid parameter types may raise `TypeError`). +The result is a scalar; larger values are significant. Identifiers are `NEYMAN` +and `NEYMAN_BETA_GOODNESS_OF_FIT`. + +Let $n$ be sample size, $u_i=F_{a,b}(x_i)$, and $P_j$ the degree-$j$ +Legendre polynomial, normalized by $P_j(1)=1$. Then + +$$ +N_k=\sum_{j=1}^{k}\left[\frac1{\sqrt n}\sum_{i=1}^{n} +\sqrt{2j+1}\,P_j(2u_i-1)\right]^2. +$$ + +## Calibration and limitations + +For fixed $k$, the null limit is $\chi^2_k$. The finite-sample distribution +depends on $n,k$ but not on $a,b$, because the $u_i$ are iid uniform under +the simple null. Monte Carlo from independent uniforms gives finite-sample +critical values; the chi-square limit can be inaccurate for small $n$. +For fixed $k$ the test is consistent against alternatives with a nonzero +selected component, but **not omnibus**: other distributions can match all +$k$ component means. No adaptive order selection is implemented. + +Plugging sample estimates into this class does not produce a calibrated +composite test. Such a procedure requires refitting in every bootstrap sample +and must not use the stated simple-null chi-square or uniform calibration. + +## Implementation + +[NeymanSmoothBetaGofStatistic](https://github.com/PySATL/pysatl-criterion/blob/main/src/pysatl_criterion/statistics/goodness_of_fit/continuous/beta/beta_statistics.py) +uses `NeymanSmoothTestUniformGofStatistic` to validate the order and evaluates +the shifted Legendre recurrence in its own cached Numba kernel. Unit references integrate the Beta density and use explicit +polynomials independently of the implementation. + +## References + +Neyman, J. (1937). *Smooth test for goodness of fit.* Skandinavisk +Aktuarietidskrift, 20, 149–199. +DOI: [10.1080/03461238.1937.10404821](https://doi.org/10.1080/03461238.1937.10404821). + +## Stored calibration + +The Beta storage guard currently permits only the default order. Stored calibration is allowed only for +`k=4`. Other settings raise `ValueError` before storage lookup; use +`MonteCarloLimitDistributionResolver` instead. Existing stored results generated +with other options under the same key must be regenerated. diff --git a/docs/criteria/goodness-of-fit/beta/raschke_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/raschke_beta_criterion.md new file mode 100644 index 00000000..82b1e4ba --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/raschke_beta_criterion.md @@ -0,0 +1,100 @@ +# Raschke biased-transformation test for Beta + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Description + +Tests the composite hypothesis of iid $\mathrm{Beta}(a,b)$ observations, +$a,b>0$, on fixed support $[0,1]$. Both shapes are unknown. Sections 4–5 +of Raschke (2009) prescribe Beta maximum likelihood, transformation to normal +quantiles, normal maximum likelihood and corrected Anderson–Darling. + +## Usage + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous import RaschkeBetaGofStatistic +from pysatl_criterion.hypothesis_testing.beta_bootstrap import parametric_bootstrap_beta + +statistic = RaschkeBetaGofStatistic(Beta.DEFAULT.parse({})) +sample = [0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57] +value = statistic.execute_statistic(sample) +result = parametric_bootstrap_beta(statistic, sample, n_resamples=1999, random_state=2026) +``` + +## Arguments and statistic + +`parameters` must leave both shapes unknown. `rvs` must contain at least three +finite real observations strictly in $(0,1)$ and be nonconstant. Endpoints, +masked data, and out-of-support observations raise `ValueError`. MLE failures +propagate. Shapes are fitted with fixed location 0 and scale 1 on every call. +The two-observation case is excluded because standardizing two distinct normal +scores always produces $(-1,1)$ and hence a constant statistic. + +Let $F_{a,b}$ be the Beta CDF, $\Phi$ the standard normal CDF, and +$(\hat a,\hat b)$ the Beta MLE. Set + +$$ +y_i=\Phi^{-1}(F_{\hat a,\hat b}(x_i)),\quad +\hat\mu=\frac1n\sum_i y_i,\quad +\hat\sigma^2=\frac1n\sum_i(y_i-\hat\mu)^2,\quad +z_i=(y_i-\hat\mu)/\hat\sigma. +$$ + +The normal scale uses the MLE divisor $n$. For ordered $z_{(i)}$, compute + +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1) +\{\log\Phi(z_{(i)})+\log[1-\Phi(z_{(n+1-i)})]\}, +\qquad A^{*2}=A^2(1+0.75/n+2.25/n^2). +$$ + +The result is $A^{*2}$, a scalar with right critical region. Identifiers are +`RASCHKE` and `RASCHKE_BETA_GOODNESS_OF_FIT`. + +## Calibration and limitations + +The original paper transfers fitted-normal critical values approximately, +with simulation evidence for selected shapes and sample sizes. This does not +establish a parameter-free Beta null law or universal omnibus consistency. +The transformed observations share estimated parameters and are not an iid +normal sample. Finite-sample calibration must account for the Beta shapes; +no universal limiting law is used here. + +The supplied bootstrap is an explicitly different calibration from the paper's +normal tables: simulate from the observed Beta MLE, then repeat **both fits**, +the transformation, and the AD correction for every replicate. It returns +an approximate p-value $(1+\#\{T_b^*\ge T\})/(B+1)$ and empirical upper +critical quantile (`inverted_cdf`). `rejected` follows the strict critical-value +comparison; the corrected p-value decision can differ for finite $B$. +`significance_level` is in $(0,1)$, `n_resamples=B` is a positive integer, and +an integer `random_state` ensures reproducibility. Bootstrap validity for +this transformed test is not established by the Ebner–Liebenberg theorem; +no exact finite-sample level or blanket consistency claim is made. + +Both Beta tails are evaluated to avoid subtracting a CDF rounded to 1. +Normal log-CDF/log-SF keep the AD sum stable. Unrepresentable transforms or +failed fits raise errors, including in bootstrap; no clipping or selective +removal of failed replicates occurs. Very small shape parameters can yield +machine-rounded endpoints in simulated samples. + +## Implementation + +[RaschkeBetaGofStatistic](https://github.com/PySATL/pysatl-criterion/blob/main/src/pysatl_criterion/statistics/goodness_of_fit/continuous/beta/beta_statistics.py) +reuses the shared `AbstractAndersonDarlingStatistic` kernel. +[Bootstrap calibration](https://github.com/PySATL/pysatl-criterion/blob/main/src/pysatl_criterion/hypothesis_testing/beta_bootstrap.py) +lives in the hypothesis-testing layer and requires the observed sample. + +## References + +Raschke, M. (2009). *The Biased Transformation and Its Application in +Goodness-of-Fit Tests for the Beta and Gamma Distribution.* Communications +in Statistics – Simulation and Computation, 38, 1870–1890. +DOI: [10.1080/03610910903152631](https://doi.org/10.1080/03610910903152631). +[Author manuscript, Sections 4–5](https://www.researchgate.net/publication/220504959_The_Biased_Transformation_and_Its_Application_in_Goodness-of-Fit_Tests_for_the_Beta_and_Gamma_Distribution). + +## Stored calibration + +`StorageLimitDistributionResolver` rejects this composite hypothesis because +the storage key lacks fitted shapes. Use `parametric_bootstrap_beta` with the +observed sample; a stored law indexed only by code and sample size is invalid. diff --git a/docs/criteria/goodness-of-fit/beta/ratio_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/ratio_beta_criterion.md deleted file mode 100644 index b76a6c82..00000000 --- a/docs/criteria/goodness-of-fit/beta/ratio_beta_criterion.md +++ /dev/null @@ -1,57 +0,0 @@ -# Ratio test for beta distribution - -## Description -Performs ratio goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic compares the sample ratio of geometric mean to arithmetic mean with the theoretical beta distribution ratio. - -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - RatioBetaGofStatistic, -) - - -test_statistic = RatioBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. - -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The sample statistic is the ratio of the geometric mean to the arithmetic mean. -The theoretical ratio uses - -$$ E[X] = \frac{\alpha}{\alpha + \beta} $$ - -and - -$$ E[\log X] = \psi(\alpha) - \psi(\alpha + \beta), $$ - -where $\psi$ is the digamma function. - -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.beta`. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - RatioBetaGofStatistic, -) - - -test_statistic = RatioBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/beta/riad_abd_el_mabood_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/riad_abd_el_mabood_beta_criterion.md new file mode 100644 index 00000000..a7145310 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/riad_abd_el_mabood_beta_criterion.md @@ -0,0 +1,79 @@ +# Riad–Abd El Mabood Beta criterion + +`RiadAbdElMaboodBetaGofStatistic` (`RF_BETA_GOODNESS_OF_FIT`) tests the Beta family on the +fixed support $[0,1]$. Both shapes are unknown and fitted by maximum likelihood. +Reject large statistic values. See the [catalog](index.md) and +[verification report](mathematical-validation.md). + +## Definition + +For fitted shapes $\hat\alpha,\hat\beta$, define + +$$ +L_n(t)=\frac1n\sum_i e^{-tx_i},\qquad +D_n(t)=\frac{t}{\hat\alpha}L_n''(t) + +\left(1+\frac{\hat\beta}{\hat\alpha}+\frac{t}{\hat\alpha}\right)L_n'(t)+L_n(t). +$$ + +The statistic, with `weight` $\rho>0$, is + +$$ +T_{n,\rho}=n\int_0^\infty D_n(t)^2e^{-\rho t}\,dt. +$$ + +Put $A_i=x_i(x_i-1)/\hat\alpha$, $B_i=1-(1+\hat\beta/\hat\alpha)x_i$ +and $s_{ij}=x_i+x_j+\rho$. Exact integration gives + +$$ +T_{n,\rho}=\frac1n\sum_{i,j}\left[ +\frac{2A_iA_j}{s_{ij}^3}+\frac{A_iB_j+A_jB_i}{s_{ij}^2} ++\frac{B_iB_j}{s_{ij}}\right]. +$$ + +`weight=2.0` is the library default, one of the values studied by Ebner and +Liebenberg. Fix it before examining the sample. The fitted mean is +$\hat\alpha/(\hat\alpha+\hat\beta)$, not the arithmetic sample mean. +The printed expanded RF formula in their Section 4 has an apparent extra +factor $\hat\alpha$ in the cross-term denominator. This implementation follows +the defining differential equation above; it does not reproduce that factor. + +Samples require at least two distinct finite observations strictly inside +$(0,1)$. Invalid weights and samples raise `ValueError`. Analytic evaluation +uses compensated summation in $O(n^2)$ time and $O(n)$ memory; severe cancellation +triggers scaled quadrature of the nonnegative integrand. Numerical failures +raise errors rather than yielding a negative squared norm. + +## Scientific sources + +- Riad, M.; Abd El Mabood, O. F. (2018). *A new goodness of fit test for the beta distribution based on the empirical Laplace transform*. Advances and Applications in Statistics 53(2), 165–177. [DOI](https://doi.org/10.17654/AS053020165). +- Ebner, B.; Liebenberg, S. C. (2021). *On a new test of fit to the beta distribution*, Section 4. [DOI](https://doi.org/10.1002/sta4.341), [open published text](https://publikationen.bibliothek.kit.edu/1000134155/118245046). + +The original 2018 full text was not accessible during this audit. The +characterization and MLE convention were checked against the published 2021 +comparison; the integral was expanded independently. + +## Example and calibration + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ( + RiadAbdElMaboodBetaGofStatistic, +) +from pysatl_criterion.hypothesis_testing.beta_bootstrap import parametric_bootstrap_beta + +sample = [0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57] +criterion = RiadAbdElMaboodBetaGofStatistic(Beta.DEFAULT.parse({}), weight=2.0) +value = criterion.execute_statistic(sample) +result = parametric_bootstrap_beta( + criterion, + sample, + n_resamples=99, + random_state=42, +) +print(value, result.p_value) +``` + +The small bootstrap count keeps this example fast. Use more replicates for +inference. Calibration is approximate and shape-dependent: every replicate +refits both shapes and retains the same settings. `execute_statistic` returns +only the statistic; stored universal critical values are unsupported. diff --git a/docs/criteria/goodness-of-fit/beta/skewness_kurtosis_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/skewness_kurtosis_beta_criterion.md deleted file mode 100644 index bcaea45d..00000000 --- a/docs/criteria/goodness-of-fit/beta/skewness_kurtosis_beta_criterion.md +++ /dev/null @@ -1,49 +0,0 @@ -# Skewness-kurtosis test for beta distribution - -## Description -Performs skewness-kurtosis goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The statistic compares sample skewness and kurtosis with the theoretical beta distribution values. - -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SkewnessKurtosisBetaGofStatistic, -) - - -test_statistic = SkewnessKurtosisBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` - -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. - -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation computes sample skewness and kurtosis and compares them with the theoretical values for the beta distribution. -The squared differences are combined in a Jarque-Bera-like statistic. - -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov - -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.beta`. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SkewnessKurtosisBetaGofStatistic, -) - - -test_statistic = SkewnessKurtosisBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/beta/watson_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/watson_beta_criterion.md index 9c25f763..c2dbea87 100644 --- a/docs/criteria/goodness-of-fit/beta/watson_beta_criterion.md +++ b/docs/criteria/goodness-of-fit/beta/watson_beta_criterion.md @@ -1,52 +1,54 @@ -# Watson test for beta distribution +# Watson for a specified Beta distribution -## Description -Performs Watson goodness-of-fit test for the hypothesis that the sample comes from a beta distribution. -The Watson statistic is a centered modification of the Cramer-von Mises statistic. +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Hypothesis of Beta Distribution -The null hypothesis is that the data comes from a beta distribution with positive shape parameters `alpha` and `beta` on the interval $[0, 1]$. +Class: `WatsonBetaGofStatistic`. Code: `WATSON_BETA_GOODNESS_OF_FIT`. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WatsonBetaGofStatistic, -) +## Hypothesis and formula +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. -test_statistic = WatsonBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. -## Arguments -`alpha` - first positive shape parameter of the beta distribution. Default value is `1`. +$$ +U^2=W^2-n(\bar u-1/2)^2,\quad W^2=\frac1{12n}+\sum_i[u_i-(i-1/2)/n]^2 +$$ -`beta` - second positive shape parameter of the beta distribution. Default value is `1`. -`rvs` - array-like sample data passed to `execute_statistic`. +## Input, result and calibration -## Details -The implementation computes a Cramer-von Mises statistic from beta CDF values and subtracts the Watson correction term +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. -$$ n\left(\bar F_0 - \frac{1}{2}\right)^2. $$ +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. -Large values indicate stronger deviation from the beta model. +## Example -## Author(s) -Dmitry Deruzhinsky, Aleksei Tokarev, Vladimir Zakharov, Alexey Mironov +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import WatsonBetaGofStatistic -## References -Watson, G.S. (1961): Goodness-of-fit tests on a circle. - Biometrika, vol. 48, pp. 109-114. +statistic = WatsonBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WatsonBetaGofStatistic, -) +## Scientific source +[Watson (1961), Goodness-of-fit tests on a circle](https://doi.org/10.1093/biomet/48.1-2.109). -test_statistic = WatsonBetaGofStatistic(alpha=2, beta=5) -statistic_result = test_statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) -print(statistic_result) -``` +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/zhang_a_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/zhang_a_beta_criterion.md new file mode 100644 index 00000000..86557af4 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/zhang_a_beta_criterion.md @@ -0,0 +1,54 @@ +# Zhang Z_A for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `ZhangABetaGofStatistic`. Code: `ZHANG_ZA_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +Z_A=-\sum_{i=1}^n\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right] +$$ + + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ZhangABetaGofStatistic + +statistic = ZhangABetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), equation (3.2). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/zhang_c_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/zhang_c_beta_criterion.md new file mode 100644 index 00000000..c39285a9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/zhang_c_beta_criterion.md @@ -0,0 +1,54 @@ +# Zhang Z_C for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `ZhangCBetaGofStatistic`. Code: `ZHANG_ZC_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +Z_C=\sum_{i=1}^n\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2 +$$ + + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ZhangCBetaGofStatistic + +statistic = ZhangCBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), equation (3.3). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/beta/zhang_k_beta_criterion.md b/docs/criteria/goodness-of-fit/beta/zhang_k_beta_criterion.md new file mode 100644 index 00000000..509d7ca1 --- /dev/null +++ b/docs/criteria/goodness-of-fit/beta/zhang_k_beta_criterion.md @@ -0,0 +1,54 @@ +# Zhang Z_K for a specified Beta distribution + +[All Beta criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +Class: `ZhangKBetaGofStatistic`. Code: `ZHANG_ZK_BETA_GOODNESS_OF_FIT`. + +## Hypothesis and formula + +Both shape parameters `a > 0` and `b > 0` are finite and fixed independently of +the sample. Pass `Beta.DEFAULT.parse({"a": 2, "b": 5})`; omitted shapes are +unknown and are rejected by this class. The support is fixed at $[0,1]$. + +For sorted observations, let $u_i=F_{a,b}(X_{(i)})$, $i=1,\ldots,n$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$W^2=1/(12n)+\sum_i(u_i-(i-1/2)/n)^2$. + +$$ +Z_K=\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right],\quad r_i=i-\tfrac12 +$$ + + +## Input, result and calibration + +`execute_statistic(rvs, **kwargs)` accepts a nonempty, finite, one-dimensional +real sample in $[0,1]$. Ties and constants are allowed; masked observations and +complex values are rejected. It returns a scalar and leaves the sample unchanged. +Large values reject (`RightAlternative`). Extra execution keywords are ignored. + +For a continuous fully specified null, the probability integral transform +makes this EDF statistic's null law independent of both shapes. Calibrate at the +same sample size. No parameter is fitted, and no p-value is returned. +AD, Liao–Shimokawa and Zhang use separate log-CDF and log-survival probabilities; +the other kernels use the CDF. Underflowed interior tails have a hypergeometric +logarithmic fallback; unrepresentable tail evaluation raises `ValueError`. +True endpoints give infinity for AD, Liao–Shimokawa and Zhang. Other EDF +statistics remain finite. The data are never clipped. + +## Example + +```python +from pysatl_criterion.distribution import BetaDistributionDescriptor as Beta +from pysatl_criterion.statistics.goodness_of_fit.continuous.beta import ZhangKBetaGofStatistic + +statistic = ZhangKBetaGofStatistic(Beta.DEFAULT.parse({"a": 2, "b": 5})) +value = statistic.execute_statistic([0.08, 0.14, 0.22, 0.31, 0.38, 0.46, 0.57]) +print(value) +``` + +## Scientific source + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), equation (3.1). + +The source identifies the shared statistical functional; applying it through +the specified Beta distribution does not constitute a new Beta-specific test. diff --git a/docs/criteria/goodness-of-fit/binning/alternative-optimized.md b/docs/criteria/goodness-of-fit/binning/alternative-optimized.md new file mode 100644 index 00000000..6b41e309 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/alternative-optimized.md @@ -0,0 +1,73 @@ +# Binning selected for a specified alternative + +`AlternativeOptimizedBins.select(...)` chooses from an explicit list of candidate +strategies using synthetic null and alternative samples. Selection happens before +the tested observations are processed. + +## Algorithm + +1. Supply a bound null distribution, a matching null sampler, an alternative + sampler, the frequency kernel, sample size and candidate strategies. +2. Generate `repetitions` null and alternative samples with a seeded NumPy RNG. + Each sampler receives `(sample_size, rng)`. Candidates share these samples. +3. Evaluate every candidate/kernel combination on the generated samples. +4. For each candidate, sort its null values and select zero-based rank + `ceil((1-alpha) * (repetitions-1))` as a simulated critical value. +5. Score the candidate by the fraction of alternative values strictly above its + critical value. Choose the largest score; ties retain the first candidate. +6. Freeze the winning strategy, sample size and all `estimated_powers`. + +Defaults are `repetitions=1000`, `alpha=0.05`, and `seed=0`; at least 20 +repetitions and `0 < alpha < 1` are required. Candidate errors are propagated. +NaN statistics are rejected; infinite statistics can occur for some kernels. + +## Example + +```python +import numpy as np +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import ( + AlternativeOptimizedBins, + EqualProbabilityBins, +) + + +def pearson(observed, expected): + return float(np.sum((observed - expected) ** 2 / expected)) + + +selected = AlternativeOptimizedBins.select( + [EqualProbabilityBins(2), EqualProbabilityBins(4)], + distribution=stats.uniform(), + null_sampler=lambda n, rng: rng.uniform(size=n), + alternative_sampler=lambda n, rng: rng.beta(1, 4, size=n), + kernel=pearson, + sample_size=40, + repetitions=100, # Small demonstration budget, not a precision recommendation. + seed=19, +) + +# New observations, not the synthetic selection samples. +sample = np.random.default_rng(100).uniform(size=40) +table = selected.build(sample, stats.uniform()) +assert table.observed.sum() == 40 +assert len(selected.estimated_powers) == 2 +``` + +Pass the resulting strategy as `binning=selected` to the criterion using that +same kernel and null model. A different sample size is rejected. The caller must +also repeat selection when changing the null model or kernel; only sample size +is checked automatically. + +The returned power scores are selection estimates, not unbiased performance +estimates. Calibrate the selected test on fresh null simulations. Do not choose +candidates by maximizing the statistic on the actual tested observations. + +## Scientific context and differences + +[Rolke and Gutierrez Gongora (2021), *A chi-square goodness-of-fit test for continuous distributions against a known alternative*](https://doi.org/10.1007/s00180-020-00997-x) studies selection against a known alternative; see the +[open preprint, §5.3](https://arxiv.org/html/2005.02793v1#S5.SS3). +Our implementation is a Monte Carlo candidate search, **not a reproduction of +their exact selection algorithm**, and it provides no universal optimality claim. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/calibration.md b/docs/criteria/goodness-of-fit/binning/calibration.md new file mode 100644 index 00000000..1c1564cb --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/calibration.md @@ -0,0 +1,111 @@ +# Saving and retrieving calibrations + +Binning affects the null distribution. A calibration for four bins cannot be +reused for eight bins. Storage identity now includes the criterion code, +null-hypothesis parameters, **criterion configuration**, and sample size. +Simulation count still determines which calibration is newer for that identity. +The critical-value cache uses the same configuration and checks the source's +simulation count, significance level and alternative. + +## Save and retrieve + +```python +from pysatl_criterion.distribution import UniformDistributionDescriptor as Uniform +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.uniform import ( + Chi2PearsonUniformGofStatistic, +) +from pysatl_criterion.hypothesis_testing.limit_distribution.base import ( + MonteCarloLimitDistributionResolver, + StorageLimitDistributionResolver, +) +from pysatl_criterion.persistence.models.distribution_key import DistributionKey +from pysatl_criterion.persistence.models.limit_distribution import LimitDistributionModel +from pysatl_criterion.persistence.sqlalchemy.database import AlchemyDatabase +from pysatl_criterion.persistence.sqlalchemy.stores.limit_distribution import ( + AlchemyLimitDistributionStorage, +) + +criterion = Chi2PearsonUniformGofStatistic( + Uniform.DEFAULT.parse({"a": 0, "b": 1}), + binning=EqualProbabilityBins(8, min_expected=5), +) +values = MonteCarloLimitDistributionResolver(1000).resolve(criterion, 100) +record = LimitDistributionModel.from_statistic(criterion, 100, values) + +database = AlchemyDatabase("sqlite:///:memory:") +database.init() +with database.session_factory.begin() as session: + store = AlchemyLimitDistributionStorage(session) + store.insert(record) + saved = store.get(DistributionKey.from_statistic(criterion, 100)) + assert saved is not None + resolved = StorageLimitDistributionResolver(store).resolve(criterion, 100) + assert resolved is not None +database.dispose() +``` + +`StorageLimitDistributionResolver` returns `None` if that configuration is absent. +Place it before `MonteCarloLimitDistributionResolver` in a +`CompositeLimitDistributionResolver` to simulate on a miss. The composite does +not automatically save simulations; use `from_statistic` to persist them. + +## Configuration and filters + +`criterion.code()` remains unchanged. `criterion.configuration()` includes +`schema_version`, `statistic_version` and `binning`. Built-in policies expose +`to_config()` with a stable type name, version and explicit defaults: count rule, +merging threshold, maximum bins and other policy parameters. An optimized policy +records the selected strategy and sample size; selection scores are excluded. + +Both tables store canonical JSON in `criterion_configuration` and SHA-256 in +`criterion_configuration_hash`. The hash participates in primary keys and the +critical-value foreign key. Callers do not calculate hashes themselves. +Dictionary order does not affect identity; equivalent numbers such as `4` and +`4.0` match. Infinite explicit edges use `"-inf"` and `"+inf"`; other non-finite +numbers are rejected. + +Custom policies and count rules must implement a stable `to_config()` dictionary +for storage. Monte Carlo does not require this method. Include every option that +affects computation, and increment the policy or statistic version when its +meaning changes. + +```python +from pysatl_criterion.persistence.queries.limit_distribution import ( + CriterionFilter, + LimitDistributionFilter, +) + +all_variants = LimitDistributionFilter( + criteria=[CriterionFilter(criterion.code())], +) +exact_variant = LimitDistributionFilter( + criteria=[ + CriterionFilter( + criterion.code(), + criterion.hypothesis().parameters(), + criterion.configuration(), + ) + ], +) +legacy_only = LimitDistributionFilter( + criteria=[CriterionFilter(criterion.code(), legacy_only=True)], +) +# Within a session: +# rows = store.get_batch(exact_variant, batch_size=100) +# next_rows = store.get_batch(exact_variant, batch_size=100, after=rows[-1].key) +``` + +Configuration `None` in a **filter** means all variants. Configuration `None` in +a **DistributionKey** means unknown legacy settings. `{}` is an explicit empty +configuration and is distinct from `None`. + +## Database schema + +`database.init()` rejects incompatible existing tables: `create_all` cannot +change their primary and foreign keys. Use a new database for configuration-aware +calibrations and recalibrate to populate it. No schema migration or transfer of +old records is provided. + +Unknown settings are represented by JSON `null` and never match a newly configured +criterion, including defaults. Do not infer missing settings from current defaults. diff --git a/docs/criteria/goodness-of-fit/binning/discrete.md b/docs/criteria/goodness-of-fit/binning/discrete.md new file mode 100644 index 00000000..4621caad --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/discrete.md @@ -0,0 +1,46 @@ +# Discrete category bins + +`DiscreteCategoryBins(cut_points, min_expected=None)` groups a discrete null +using ordered cut points. It uses actual category masses, not equal probabilities. + +## Algorithm + +For finite increasing cuts $c_1,\ldots,c_m$, form + +$$ +(-\infty,c_1],\ (c_1,c_2],\ \ldots,\ (c_m,\infty). +$$ + +1. Assign each observation to its right-closed category. An atom exactly at a cut + belongs to the category on its left. +2. Calculate null masses using CDF differences, with stable SF differences in + the upper tail; multiply by $n$ for expected counts. +3. Remove zero-probability empty categories and optionally merge adjacent small + expected categories using the [shared policy](index.md#defaults-and-small-expected-counts). + +Cuts need not be integers. The distribution defines the masses; the caller is +responsible for valid sample support when using this strategy directly. +At least two positive-probability categories must remain. This strategy declares +compatibility with discrete distributions and is rejected by Uniform +criteria. + +## Example + +```python +import numpy as np +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import DiscreteCategoryBins + +# Geometric here counts trials including the first success: 1, 2, ... +table = DiscreteCategoryBins((1, 3)).build([1, 1, 2, 3, 4, 5], stats.geom(0.5)) +np.testing.assert_array_equal(table.observed, [2, 2, 2]) +np.testing.assert_allclose(table.expected, 6 * np.array([0.5, 0.375, 0.125])) +``` + +## Scientific context + +[Cressie and Read (1984), *Multinomial Goodness-of-Fit Tests*](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), section 1, treats exhaustive categories through multinomial +probabilities. Right-closed cut points and this library's deterministic merging +policy are implementation choices rather than an algorithm claimed from the paper. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/equal-probability.md b/docs/criteria/goodness-of-fit/binning/equal-probability.md new file mode 100644 index 00000000..1351979b --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/equal-probability.md @@ -0,0 +1,45 @@ +# Equal-probability bins + +`EqualProbabilityBins(count=PowerCount(), min_expected=None, max_bins=1000)` +constructs cells with equal probability under a continuous null distribution. + +## Algorithm + +1. Resolve $k$ from the sample size and cap it by `max_bins`. +2. If `min_expected=m` is supplied, also cap it by $\lfloor n/m\rfloor$. + Reject the request if fewer than two bins remain. +3. Transform each observation to $u_j=F_0(x_j)$. +4. Count these values in $k$ equal intervals over $[0,1]$. +5. Set every expected count to $n/k$. + +This avoids evaluating an inverse CDF. The probability-space bins use NumPy's +left-closed convention; the final bin includes 1. The CDF must return finite +values in $[0,1]$ aligned with the sample. + +## Example + +```python +import numpy as np +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +null = stats.norm(loc=2, scale=3) +sample = null.ppf([0.1, 0.2, 0.4, 0.6, 0.8, 0.9]) +table = EqualProbabilityBins(count=4).build(sample, null) +np.testing.assert_array_equal(table.observed, [2, 1, 1, 2]) +np.testing.assert_allclose(table.expected, [1.5] * 4) +``` + +A descriptor-bound distribution can replace the SciPy frozen distribution. +The null parameters must already be specified; they are not fitted here. +Uniform criteria additionally reject observations outside their fixed support. + +Do not apply this strategy to a discrete CDF: jumps prevent the equal-probability +assumption. Use [DiscreteCategoryBins](discrete.md) instead. + +## Scientific source + +[Rolke and Gutierrez Gongora (2021), *A chi-square goodness-of-fit test for continuous distributions against a known alternative*](https://doi.org/10.1007/s00180-020-00997-x), [open preprint, §5.1](https://arxiv.org/html/2005.02793v1#S5.SS1), discusses equal-probability grouping. Our count resolution, +probability-space boundary convention and limits are implementation policies. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/equal-width.md b/docs/criteria/goodness-of-fit/binning/equal-width.md new file mode 100644 index 00000000..794b0fa0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/equal-width.md @@ -0,0 +1,44 @@ +# Equal-width bins with tails + +`EqualWidthBins(lower, upper, count=PowerCount(), min_expected=None, max_bins=1000)` +creates equal-width central intervals and preserves nonempty null tails. + +## Algorithm + +1. Require fixed finite bounds `lower < upper` with finite width. +2. Resolve and cap the number $k$ of **central** bins. +3. Place $k+1$ equally spaced edges between the bounds. +4. Add `-inf` if the null assigns probability below `lower`; add `inf` if it + assigns probability above `upper`. +5. Build an [explicit frequency table](explicit.md), including optional merging. + +The final count can be $k$, $k+1$, or $k+2$ before merging. Expected counts are +computed from the null CDF and generally differ across bins. `max_bins` limits +central bins, not the additional tails. + +## Example + +```python +import numpy as np +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualWidthBins + +null = stats.norm() +table = EqualWidthBins(-1, 1, count=2).build([-3, -0.5, 0.5, 3], null) +np.testing.assert_array_equal(table.observed, [1, 1, 1, 1]) +np.testing.assert_allclose( + table.expected, + 4 * np.diff(null.cdf([-np.inf, -1, 0, 1, np.inf])), +) +``` + +Set central bounds before testing. Selecting them from sample extrema introduces +another data-dependent step which this class does not implement. + +## Scientific source + +[Rolke and Gutierrez Gongora (2021), *A chi-square goodness-of-fit test for continuous distributions against a known alternative*](https://doi.org/10.1007/s00180-020-00997-x), [open preprint, §5.1](https://arxiv.org/html/2005.02793v1#S5.SS1), discusses equal-width grouping. +The separate tail categories and finite central-bound API are our implementation +policies, not a claim to reproduce every boundary convention in the paper. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/explicit.md b/docs/criteria/goodness-of-fit/binning/explicit.md new file mode 100644 index 00000000..53994767 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/explicit.md @@ -0,0 +1,41 @@ +# Explicit bin edges + +`ExplicitBins(edges, min_expected=None)` uses supplied continuous bin boundaries. +They must cover the full null probability and all observations. + +## Algorithm + +1. Require at least three strictly increasing edges, without NaNs. +2. Verify that the null probability below the first edge and above the last is zero. +3. Count observations using `[left, right)` cells; include the final right endpoint. +4. Calculate $E_i=n(F_0(b_{i+1})-F_0(b_i))$. +5. Remove empty zero-probability categories and apply optional expected-count merging. + +Upper-tail probabilities use survival-function differences to avoid subtracting +CDF values near one. A positive observation count in a zero-probability category +is an error. At least two categories must remain. + +## Example + +```python +import numpy as np +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import ExplicitBins + +strategy = ExplicitBins((-np.inf, 0, np.inf)) +table = strategy.build([-2, -0.5, 0.5, 2], stats.norm()) +np.testing.assert_array_equal(table.observed, [2, 2]) +np.testing.assert_allclose(table.expected, [2, 2]) +``` + +Choose boundaries independently of the tested observations, or calibrate any +additional boundary-selection procedure explicitly. Finite edges are appropriate +when they cover a bounded null support. + +## Scientific context + +[Cressie and Read (1984), *Multinomial Goodness-of-Fit Tests*](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), section 1, supplies the multinomial-category framework. +The explicit boundary API and the adjacent-cell merging algorithm are library +policies, not a bin-selection algorithm attributed to this paper. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/fixed-count.md b/docs/criteria/goodness-of-fit/binning/fixed-count.md new file mode 100644 index 00000000..00487a64 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/fixed-count.md @@ -0,0 +1,38 @@ +# Fixed number of bins + +`FixedCount(count)` returns a user-selected integer independently of sample size. +It is a count rule, not a partition of the sample. + +## Algorithm + +1. Require an integer `count >= 2`; booleans are rejected. +2. Require a positive integer sample size. +3. Return the configured count. + +A consuming strategy can reduce it because of `max_bins` or `min_expected`. +Passing an integer to a strategy is shorthand for `FixedCount`. + +## Example + +```python +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import FixedCount, EqualProbabilityBins + +rule = FixedCount(4) +assert rule.resolve(100) == 4 +strategy = EqualProbabilityBins(count=rule) +table = strategy.build([0.1, 0.2, 0.4, 0.6, 0.8, 0.9], stats.uniform()) +assert len(table.expected) == 4 +``` + +Choose this when a study specifies the grouping in advance. Increasing the +sample size does not increase the number of bins automatically. + +## Scientific context + +[Cressie and Read (1984), *Multinomial Goodness-of-Fit Tests*](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) treats observations as counts in specified categories. This provides +the multinomial context, not a formula for choosing this class's `count`. +The fixed-count setting is a user decision and is not attributed to an optimal +selection algorithm in that paper. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/index.md b/docs/criteria/goodness-of-fit/binning/index.md new file mode 100644 index 00000000..778014b9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/index.md @@ -0,0 +1,129 @@ +# Binning for frequency goodness-of-fit tests + +Binning converts a sample and a fully specified null distribution into observed +and expected category counts. A frequency statistic then measures the discrepancy +between those counts. Changing bins changes the test, even when its statistic +formula stays the same. + +## How it works + +```text +sample + fixed null parameters + | + v +count rule -> binning strategy -> observed / expected -> frequency statistic +``` + +For categories $C_1,\ldots,C_k$ and a sample of size $n$: + +$$ +O_i = \sum_{j=1}^{n}\mathbf{1}\{x_j\in C_i\},\qquad +E_i = n\,P_{H_0}(X\in C_i). +$$ + +A strategy's `build(sample, distribution)` returns a `FrequencyTable` with +`observed` and `expected` arrays. The arrays are read-only, have at least two +entries, and have matching totals. Observations must be a nonempty, finite, +one-dimensional real sample. Expected counts must be strictly positive. + +The criterion validates its family-specific sample support, binds the +null parameters, builds a fresh table, and calls the frequency kernel. Binning +does not fit missing parameters or calculate p-values. + +## All available methods + +Choose one **count rule** and one compatible **binning strategy**. Explicit and +discrete strategies take boundaries directly and do not need a count rule. + +| Method | Role | Rule or mechanism | Applicable input | +| --- | --- | --- | --- | +| [FixedCount](fixed-count.md) | Count | A specified integer $k\ge2$ | Strategies accepting a count | +| [SturgesCount](sturges-count.md) | Count | $\max(2,\lceil1+\log_2 n\rceil)$ | Strategies accepting a count | +| [SqrtCount](sqrt-count.md) | Count | $\max(2,\lceil\sqrt n\rceil)$ | Strategies accepting a count | +| [PowerCount](power-count.md) | Count | $\max(2,\lceil c n^p\rceil)$; default $c=2$, $p=0.4$ | Strategies accepting a count | +| [EqualProbabilityBins](equal-probability.md) | Strategy | Equal null probability; $E_i=n/k$ | Continuous null | +| [ExplicitBins](explicit.md) | Strategy | User-specified full-support edges | Continuous null | +| [EqualWidthBins](equal-width.md) | Strategy | Equal central widths plus nonempty null tails | Continuous null | +| [InterpolatedBins](interpolated.md) | Strategy | Interpolation of null-quantile and equal-width boundaries | Continuous null | +| [DiscreteCategoryBins](discrete.md) | Strategy | Right-closed categories with actual null masses | Discrete null | +| [AlternativeOptimizedBins](alternative-optimized.md) | Selection | Monte Carlo search over candidate strategies before testing | Compatible candidates and a specified alternative | + +`FixedCount` and `SqrtCount` are configuration/heuristic choices, not claims of +optimal GoF power. Statistical sources and differences from published methods +are given on the individual pages. + +## Quick start + +```python +from pysatl_criterion.distribution import UniformDistributionDescriptor as Uniform +from pysatl_criterion.statistics.goodness_of_fit.binning import ( + EqualProbabilityBins, + SturgesCount, +) +from pysatl_criterion.statistics.goodness_of_fit.continuous.uniform import ( + Chi2PearsonUniformGofStatistic, +) + +parameters = Uniform.DEFAULT.parse({"a": 0, "b": 1}) +criterion = Chi2PearsonUniformGofStatistic( + parameters, + binning=EqualProbabilityBins(count=SturgesCount()), +) +value = criterion.execute_statistic([0.1, 0.15, 0.4, 0.6, 0.8, 0.9]) +assert value >= 0 +``` + +The same `binning` argument is available on `FreemanTukeyUniformGofStatistic`, +`ModifiedLogLikelihoodUniformGofStatistic`, `NeymanChi2UniformGofStatistic`, and +`CressieReadUniformGofStatistic`. Choose the class for the desired formula; +the former `bins` and `lambda_` constructor arguments have been removed. + +All strategies and count rules are imported from +`pysatl_criterion.statistics.goodness_of_fit.binning`. Standalone examples on +method pages use SciPy frozen distributions, which provide the required CDF/SF +methods; a descriptor's `bind(parameters)` result can be used as well. + +## Defaults and small expected counts + +The default is `EqualProbabilityBins(count=PowerCount(), max_bins=1000, +min_expected=None)`. It permits sparse tables for simulation-based calibration. +Counts are resolved again for every sample size. `max_bins` caps even an explicit +fixed count; width-based methods can add up to two extra tail categories. + +Set `min_expected=5`, for example, to request a minimum expected-count policy. +For equal-probability bins, the count is capped by $\lfloor n/5\rfloor$. +Other strategies repeatedly merge the smallest expected category with its right +neighbor, or its left neighbor when last. Merging uses null expectations only. +If fewer than two valid categories remain, an error is raised. + +A zero-probability category with no observations is removed. Observations in a +zero-probability category raise an error. No sample observations or tail mass +may be silently dropped. Minimum expected counts do not by themselves guarantee +an accurate asymptotic calibration. + +## Calibration + +The Uniform criteria support fully fixed bounds. Parameters are never +estimated implicitly. Continuous equal-probability binning must not be applied +to a discrete CDF; use discrete category probabilities instead. + +Use `MonteCarloLimitDistributionResolver` to calibrate the configured criterion. +Every simulation rebuilds its bins. `StorageLimitDistributionResolver` retrieves +only an exact configuration match, including binning parameters. Legacy records +with unknown configuration do not match implicitly. See +[saving and retrieving calibrations](calibration.md) for examples and schema requirements. +A statistic value alone is not a p-value. + +Selection for a specified alternative uses synthetic data before observing the +tested sample. Calibrate the selected strategy using fresh null simulations; +its reported selection power is not an unbiased performance estimate. + +## Sources and related documentation + +The frequency-kernel family is described in [Cressie and Read (1984), *Multinomial Goodness-of-Fit Tests*](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). +Binning choices and alternative-specific selection are discussed in [Rolke and Gutierrez Gongora (2021), *A chi-square goodness-of-fit test for continuous distributions against a known alternative*](https://doi.org/10.1007/s00180-020-00997-x) +([open preprint, §5.1](https://arxiv.org/html/2005.02793v1#S5.SS1)). These sources motivate the methods; count caps, tail policies, +merging rules and the Monte Carlo candidate search are library choices. + +See [frequency binning guide](../../../frequency-binning.md) and +[universal goodness-of-fit statistics](../universal.md). diff --git a/docs/criteria/goodness-of-fit/binning/interpolated.md b/docs/criteria/goodness-of-fit/binning/interpolated.md new file mode 100644 index 00000000..a56b1009 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/interpolated.md @@ -0,0 +1,47 @@ +# Interpolated bins + +`InterpolatedBins(lower, upper, count=PowerCount(), min_expected=None, +max_bins=1000, kappa=0.5)` blends equal-probability and equal-width boundaries. + +## Algorithm + +For `0 < kappa < 1`: + +1. Construct equal-width central edges and any required tail cells. +2. Let $K$ be the total number of cells, including tails. +3. Find the null quantiles $q_i=F_0^{-1}(i/K)$ for interior indices. +4. Replace each interior equal-width edge $w_i$ by + $b_i=(1-\kappa)q_i+\kappa w_i$; keep the outer coverage edges. +5. Count observations and compute actual expected probabilities, then apply + optional merging. + +Null quantiles are found by numerical CDF inversion. The supplied finite bounds +seed a bracket that is expanded if needed. Failure to bracket a finite quantile +or obtain valid ordered edges raises an error. + +At `kappa=0` the implementation delegates to `EqualProbabilityBins`; at `kappa=1` +it delegates to `EqualWidthBins`. The number of cells can therefore change at +the zero endpoint when width-based grouping has extra tails. This is a library +policy, not a continuous fixed-cell-count interpolation across that endpoint. + +## Example + +```python +import numpy as np +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import InterpolatedBins + +strategy = InterpolatedBins(0, 4, count=2, kappa=0.5) +table = strategy.build([0.1, 0.5, 1.5, 3, 10], stats.expon()) +assert len(table.expected) == 3 # Two central bins and an upper tail. +assert table.observed.sum() == 5 +np.testing.assert_allclose(table.expected.sum(), 5) +``` + +## Scientific source + +[Rolke and Gutierrez Gongora (2021), *A chi-square goodness-of-fit test for continuous distributions against a known alternative*](https://doi.org/10.1007/s00180-020-00997-x), [open preprint, §5.1](https://arxiv.org/html/2005.02793v1#S5.SS1), equation (3), gives the boundary interpolation formula. +Numerical inversion, tail handling and endpoint delegation described above are +specific to this implementation. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/power-count.md b/docs/criteria/goodness-of-fit/binning/power-count.md new file mode 100644 index 00000000..9439c139 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/power-count.md @@ -0,0 +1,42 @@ +# Power count rule + +`PowerCount(coefficient=2.0, exponent=0.4)` provides an explicit sample-size +heuristic whose parameters can be changed. + +## Algorithm + +Require positive finite $c$ and $p$ and a positive integer sample size $n$: + +$$ +k=\max(2,\lceil c n^p\rceil). +$$ + +The default is $\lceil2n^{2/5}\rceil$ with a minimum of two. +The consuming strategy applies its caps. For example, `min_expected=5` in +equal-probability binning restricts $k\le\lfloor n/5\rfloor$. + +## Example + +```python +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import PowerCount, EqualProbabilityBins + +rule = PowerCount() +assert rule.resolve(100) == 13 +table = EqualProbabilityBins(count=rule, min_expected=5).build( + [0.2, 0.8] * 10, + stats.uniform(), +) +assert len(table.expected) == 4 # Expected-count policy reduces the requested 7. +``` + +## Sources and scope + +[NIST/SEMATECH handbook, §7.2.1.1](https://www.itl.nist.gov/div898/handbook/prc/section2/prc211.htm) gives $2n^{2/5}$ as a practical starting heuristic. It is a handbook, +not a research paper. Rounding and caps are implementation choices. + +[Mann and Wald (1942), *On the Choice of the Number of Class Intervals in the Application of the Chi Square Test*](https://doi.org/10.1214/aoms/1177731569) is historical scientific background on choosing class intervals. This +class does not implement a particular Mann–Wald optimality formula. Its general +coefficient/exponent API does not establish optimality for arbitrary settings. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/sqrt-count.md b/docs/criteria/goodness-of-fit/binning/sqrt-count.md new file mode 100644 index 00000000..0da21726 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/sqrt-count.md @@ -0,0 +1,35 @@ +# Square-root count rule + +`SqrtCount()` is a convenience heuristic based only on sample size. + +## Algorithm + +For a positive integer $n$, return + +$$ +k=\max(2,\lceil\sqrt n\rceil). +$$ + +The strategy then applies `max_bins` and, where applicable, `min_expected`. +The rule neither inspects the sample's dispersion nor constructs boundaries. + +## Example + +```python +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import SqrtCount, EqualProbabilityBins + +rule = SqrtCount() +assert rule.resolve(100) == 10 +table = EqualProbabilityBins(count=rule).build([0.2, 0.8] * 50, stats.uniform()) +assert len(table.expected) == 10 +``` + +## Scientific context + +This heuristic is not attributed to a specific research article and does not +carry a GoF optimality claim. For research on the separate problem of choosing +chi-square class intervals, see [Mann and Wald (1942), *On the Choice of the Number of Class Intervals in the Application of the Chi Square Test*](https://doi.org/10.1214/aoms/1177731569). That reference is background, not the +source of the square-root formula. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/binning/sturges-count.md b/docs/criteria/goodness-of-fit/binning/sturges-count.md new file mode 100644 index 00000000..20a81997 --- /dev/null +++ b/docs/criteria/goodness-of-fit/binning/sturges-count.md @@ -0,0 +1,39 @@ +# Sturges count rule + +`SturgesCount()` chooses a logarithmically growing number of bins. + +## Algorithm + +For a positive integer sample size $n$, return + +$$ +k=\max(2,\lceil1+\log_2 n\rceil). +$$ + +Ceiling and the minimum of two are library policies. A binning strategy applies +its own count cap and expected-count policy afterward. No sample values enter +the formula. + +## Example + +```python +from scipy import stats +from pysatl_criterion.statistics.goodness_of_fit.binning import SturgesCount, EqualProbabilityBins + +rule = SturgesCount() +assert rule.resolve(100) == 8 +strategy = EqualProbabilityBins(count=rule, min_expected=5) +table = strategy.build([0.25, 0.75] * 50, stats.uniform()) +assert len(table.expected) == 8 +``` + +The rule offers a simple grouping convention; it does not guarantee maximum +power against a particular alternative. + +## Scientific source + +[Sturges (1926), *The Choice of a Class Interval*](https://doi.org/10.1080/01621459.1926.10502161). Journal of the American Statistical Association, 21(153), 65–66. +[Open article scan](https://www.stat.rice.edu/~scottdw/stat550/DEMOS/09-14-hist/Sturges1926.pdf). +The original work motivates the logarithmic class-count relationship. + +[All binning methods](index.md) diff --git a/docs/criteria/goodness-of-fit/exponentiality/ahsanullah_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/ahsanullah_exp_criterion.md index 5161d4bf..71809092 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/ahsanullah_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/ahsanullah_exp_criterion.md @@ -1,70 +1,61 @@ -# Test for exponentiality based on Ahsanullah characterization +# Ahsanullah exponentiality criterion -## Description -Performs Ahsanullah test for the hypothesis of exponentiality, see e.g. Ahsanullah and Rahman (1972). -The Ahsanullah test is a statistical hypothesis test used to assess whether a given sample of data is consistent with an exponential distribution. This test is based on a characterization of the exponential distribution through properties of order statistics and related distributional identities. +`AhsanullahExponentialityGofStatistic` — short code `AHS`; right tail. -Hypothesis of Exponentiality -The hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution. The exponential distribution is widely used in reliability theory, survival analysis, queuing theory, and other fields where waiting times or lifetimes are modeled. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Ahsanullah test statistic is based on comparing two empirical probabilities formed from pairs and single observations in the sample. Under exponentiality, the compared quantities are expected to be close. Large positive values of the statistic indicate departure from the exponential model in the right-tailed direction. +## Hypothesis and formula -Calculate the Test Statistic: The test statistic counts, over all triples of observations, how often the absolute difference of two observations is smaller than a third observation and how often twice the smaller of two observations is smaller than a third observation. The normalized difference between these counts is used as the statistic. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The statistic uses a triple summation over the sample, so the direct computation can be expensive for large sample sizes. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The test is designed around the characterization of exponentiality and should be calibrated with appropriate critical values or simulation when exact finite-sample behavior is required. +$$ +n^{-3}\sum_{i,j,k}\left[\mathbf1\{|x_i-x_j|0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +-n-\frac1n\sum_i(2i-1)[\log u_i+\log(1-u_{n+1-i})] +$$ + +Unmodified A-squared. Zero observations produce positive infinity. Log-CDF and log-survival are evaluated separately to retain upper-tail information. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + AndersonDarlingExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = AndersonDarlingExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Anderson and Darling (1952), Asymptotic theory of certain goodness of fit criteria based on stochastic processes](https://doi.org/10.1214/aoms/1177729437). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/atkinson_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/atkinson_exp_criterion.md index 4f336cf2..df3542ff 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/atkinson_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/atkinson_exp_criterion.md @@ -1,71 +1,61 @@ -# Atkinson test for exponentiality +# Atkinson exponentiality criterion -## Description -Performs Atkinson test for the composite hypothesis of exponentiality, see e.g. Mimoto and Zitikis (2008). -The Atkinson test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is based on a moment ratio related to the Atkinson index and is designed to determine whether a given sample of data is consistent with an exponential distribution. +`AtkinsonExponentialityGofStatistic` — short code `ATK`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Atkinson statistic is scale invariant, so the unknown exponential scale is removed by dividing by the sample mean. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Atkinson test statistic compares a power mean of the sample with its arithmetic mean. Under exponentiality, the corresponding theoretical ratio is determined by the gamma function. The statistic measures the absolute difference between the empirical ratio and the theoretical exponential ratio. +## Hypothesis and formula -Calculate the Test Statistic: The test statistic is calculated from the sample mean, the sample mean of the powered observations, and the value of the gamma function at `1 + p`. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The choice of the power parameter `p` can affect the power of the test against different alternatives. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The asymptotic distribution is typically used for calibration, and simulation-based critical values may be preferable for small samples. +$$ +\sqrt n\left|\left(n^{-1}\sum_i y_i^p\right)^{1/p}-\Gamma(1+p)^{1/p}\right| +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - AtkinsonExponentialityGofStatistic, -) - - -test_statistic = AtkinsonExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -`p` - power parameter of the test statistic. Default value is `0.99`. - -## Details - -The Atkinson test is a test for the composite hypothesis of exponentiality. The test statistic is +Unstandardized absolute contrast. Constructor p=0.99; p>-1, p not in {0,1}. Negative powers at zero use the limiting power mean zero. The usual finite-variance asymptotics require p>-1/2; accepted values below this threshold still require their own Monte Carlo calibration. No unit-normal calibration is claimed. -$$ T_n(p) = \sqrt{n} \left| \frac{\left(n^{-1}\sum_{i=1}^{n}X_i^p\right)^{1/p}}{\overline{X}} - \left(\Gamma(1+p)\right)^{1/p} \right| $$ +## Input and calibration -where $n$ is the sample size, $\overline{X}$ is the sample mean, $p$ is the power parameter, and $\Gamma(\cdot)$ is the gamma function. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -Under exponentiality, the moment ratio +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ \frac{(E X^p)^{1/p}}{E X} $$ - -is equal to $(\Gamma(1+p))^{1/p}$. Large values of $T_n(p)$ indicate larger deviations from the exponential model. - -## Author(s) -Lev Golofastov - -## References -Mimoto, N. and Zitikis, R. (2008): The Atkinson index, the Moran statistic, and testing exponentiality. - Journal of the Japan Statistical Society, vol. 38, no. 2, pp. 187-205. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( AtkinsonExponentialityGofStatistic, ) - -test_statistic = AtkinsonExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = AtkinsonExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Mimoto and Zitikis (2008), The Atkinson index, the Moran statistic, and testing exponentiality](https://doi.org/10.14490/jjss.38.187). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/baringhaus_henze_bhc_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/baringhaus_henze_bhc_exp_criterion.md new file mode 100644 index 00000000..f7ddf378 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/baringhaus_henze_bhc_exp_criterion.md @@ -0,0 +1,61 @@ +# Baringhaus–Henze mean residual life exponentiality criterion + +`BaringhausHenzeBHCExponentialityGofStatistic` — short code `BH_BHC`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +n\int_0^\infty\left[n^{-1}\sum_i(y_i-t-1)\mathbf1\{y_i>t\}\right]^2e^{-at}\,dt +$$ + +Right tail; constructor 00$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +n\int_0^\infty[(1+t)L_n^\prime(t)+L_n(t)]^2e^{-at}\,dt,\quad L_n(t)=n^{-1}\sum_i e^{-ty_i} +$$ + +Right tail; constructor 00$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes positive lifetime-type observations, since the statistic uses logarithms of normalized data. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The asymptotic normal approximation may require moderate or large sample sizes; simulation-based calibration can be useful for small samples. +$$ +n+\sum_i(1-y_i)\log y_i +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CoxOakesExponentialityGofStatistic, -) - - -test_statistic = CoxOakesExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Cox and Oakes test is a test for the composite hypothesis of exponentiality. The test statistic is - -$$ CO_n = n + \sum_{j=1}^{n}(1-Y_j)\log(Y_j) $$ +Signed Weibull shape score at shape 1; both tails. Derived independently by differentiating the profiled Weibull log likelihood. Zero observations give negative infinity. Cox and Oakes, Analysis of Survival Data (1984), is the historical book source; the linked article is a comparison, not an original derivation. -where +## Input and calibration -$$ Y_j = \frac{X_j}{\overline{X}}. $$ +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -Here $n$ is the sample size and $\overline{X}$ is the sample mean. The statistic is scale invariant because it is calculated from the normalized observations $Y_j$. +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -Under the null hypothesis of exponentiality, - -$$ \left(\frac{6}{n}\right)^{1/2}\frac{CO_n}{\pi} $$ - -is asymptotically standard normal (see, e.g., Henze and Meintanis (2005, Sec. 2.5)). - -## Author(s) -Lev Golofastov - -## References -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -Cox, D.R. and Oakes, D. (1984): Analysis of Survival Data. - London: Chapman and Hall. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( CoxOakesExponentialityGofStatistic, ) - -test_statistic = CoxOakesExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = CoxOakesExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Henze and Meintanis (2005), Recent and classical tests for exponentiality: a partial review with comparisons](https://doi.org/10.1007/s001840400322). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/cressie_read_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/cressie_read_exp_criterion.md new file mode 100644 index 00000000..f417cae4 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/cressie_read_exp_criterion.md @@ -0,0 +1,73 @@ +# Cressie–Read exponentiality criterion + +`CressieReadExponentialityGofStatistic` — short code `CRESSIE_READ`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\frac95\sum_j O_j[(O_j/E_j)^{2/3}-1] +$$ + +Power-divergence parameter 2/3; an empty observed cell contributes zero. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +The `binning` keyword accepts a `BinningStrategy`. Default +`EqualProbabilityBins()` chooses the count from sample size; it is not fixed +at five. With unknown rate, built-in Monte Carlo requires this strategy; +other bins need external calibration at an explicit rate. Known-rate Pearson +has an asymptotic chi-square(k-1) law with suitable expected counts. After +fitting from ungrouped observations and moving bins, chi-square(k-2) is not +asserted. Empty-cell infinities are valid outcomes for Neyman and modified +log-likelihood; ties at infinity make rank calibration conservative. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + CressieReadExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = CressieReadExponentialityGofStatistic( + E.DEFAULT.parse({}), binning=EqualProbabilityBins(count=4) +) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Cressie and Read (1984), Multinomial goodness-of-fit tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/cvm_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/cvm_exp_criterion.md index 3cca6a82..cb770dbf 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/cvm_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/cvm_exp_criterion.md @@ -1,73 +1,61 @@ -# Cramer-von Mises test for exponentiality +# Cramér–von Mises exponentiality criterion -## Description -Performs Cramer-von Mises test for the hypothesis of exponentiality, see e.g. Cramer (1928), von Mises (1931), and Henze and Meintanis (2005). -The Cramer-von Mises test is a statistical goodness-of-fit test used to assess whether a given sample of data is consistent with an exponential distribution. This test is based on the empirical distribution function and measures the squared distance between the empirical cumulative distribution function and the theoretical cumulative distribution function of the exponential distribution. +`CramerVonMisesExponentialityGofStatistic` — short code `CVM`; right tail. -Hypothesis of Exponentiality -The hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with rate parameter -lambda. In the implementation the rate parameter is supplied by the user and is used to evaluate the theoretical exponential cumulative distribution function. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Cramer-von Mises test statistic is based on the integrated squared difference between the empirical distribution function and the theoretical cumulative distribution function. Compared with the Kolmogorov-Smirnov statistic, which uses the largest absolute discrepancy, the Cramer-von Mises statistic accumulates discrepancies over the whole sample. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, the exponential cumulative distribution function is evaluated at the ordered observations, and the squared deviations from the expected uniform plotting positions are summed. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The classical Cramer-von Mises test is most direct when the distribution parameters are fixed in advance. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -When the rate parameter is estimated from the same sample, the usual critical values are no longer directly applicable and adjusted critical values or simulation-based calibration may be required. +$$ +W^2=\frac1{12n}+\sum_i[u_i-(i-1/2)/n]^2 +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CramerVonMisesExponentialityGofStatistic, -) - - -test_statistic = CramerVonMisesExponentialityGofStatistic(lam=0.5) -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`lam` - rate parameter of the exponential distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Cramer-von Mises test is an empirical distribution function test for exponentiality. The test statistic is -$$ W_n^2 = \frac{1}{12n} + \sum_{i=1}^{n} \left(F_0(X_{(i)}) - \frac{2i - 1}{2n}\right)^2 $$ -where $X_{(i)}$ is the $i$-th order statistic, $n$ is the sample size, and $F_0$ is the cumulative distribution function of the reference exponential distribution. +## Input and calibration -For an exponential distribution with rate parameter $\lambda$, the cumulative distribution function is +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -$$ F_0(x) = 1 - exp(-\lambda x), \quad x \ge 0. $$ +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -Large values of $W_n^2$ indicate larger deviations from the exponential model. - -## Author(s) -Lev Golofastov - -## References -Cramer, H. (1928): On the composition of elementary errors. - Skandinavisk Aktuarietidskrift, vol. 11, pp. 141-180. - -von Mises, R. (1931): Wahrscheinlichkeitsrechnung und ihre Anwendung in der Statistik und theoretischen Physik. - Leipzig: Deuticke. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( CramerVonMisesExponentialityGofStatistic, ) - -test_statistic = CramerVonMisesExponentialityGofStatistic(lam=0.5) -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = CramerVonMisesExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/deshpande_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/deshpande_exp_criterion.md index d5560c14..a3704030 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/deshpande_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/deshpande_exp_criterion.md @@ -1,71 +1,61 @@ -# Deshpande test for exponentiality +# Deshpande exponentiality criterion -## Description -Performs Deshpande test for the composite hypothesis of exponentiality, see Deshpande (1983). -The Deshpande test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution against aging-type alternatives such as increasing failure rate average alternatives. +`DeshpandeExponentialityGofStatistic` — short code `DSP`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The statistic is based on pairwise comparisons and is scale invariant for positive rescaling of the data. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Deshpande test statistic is a U-statistic based on pairwise comparisons of observations. It counts how often one observation is larger than a fixed multiple of another observation. The multiplier is controlled by the parameter `b`. +## Hypothesis and formula -Calculate the Test Statistic: For every ordered pair of distinct observations, the indicator of the event $X_i > bX_j$ is evaluated, and the average of these indicators is used as the statistic. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The value of the parameter `b` can affect the power of the test against different alternatives. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The direct implementation uses all ordered pairs of observations, so the computational cost grows quadratically with the sample size. +$$ +\frac{1}{n(n-1)}\sum_{i\ne j}\mathbf1\{x_i>b x_j\} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DeshpandeExponentialityGofStatistic, -) - - -test_statistic = DeshpandeExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -`b` - threshold parameter for the pairwise comparison. Default value is `0.44`. - -## Details - -The Deshpande test is a test for the composite hypothesis of exponentiality. The test statistic is +Constructor 0 bX_j) $$ +## Input and calibration -where $I(\cdot)$ is the indicator function, $n$ is the sample size, and $b$ is a positive parameter of the test. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -Under exponentiality, +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ \sqrt{n}\left(J_n - \frac{1}{b+1}\right) $$ - -is asymptotically normal with variance depending on $b$ (see Deshpande (1983)). - -## Author(s) -Lev Golofastov - -## References -Deshpande, J.V. (1983): A class of tests for exponentiality against increasing failure rate average alternatives. - Biometrika, vol. 70, pp. 514-518. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( DeshpandeExponentialityGofStatistic, ) - -test_statistic = DeshpandeExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = DeshpandeExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Deshpande (1983), A class of tests for exponentiality against increasing failure rate average alternatives](https://doi.org/10.1093/biomet/70.2.514). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/epps_pulley_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/epps_pulley_exp_criterion.md index 6d42d5e7..9eb34852 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/epps_pulley_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/epps_pulley_exp_criterion.md @@ -1,39 +1,61 @@ -# Test for exponentiality of Epps and Pulley +# Epps–Pulley exponentiality criterion -## Description -Performs Epps and Pulley test for the composite hypothesis of exponentiality, see e.g. Henze and Meintanis (2005, Sec. 2.8.1). -The Epps and Pulley test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution, which is a common assumption in various fields such as reliability engineering, survival analysis, and queuing theory. +`EppsPulleyExponentialityGofStatistic` — short code `EP`; both tails. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -λ. Unlike a simple hypothesis, where the parameter λ is known, the composite hypothesis allows λ to be any positive value, making the test more flexible and widely applicable. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Epps and Pulley test statistic is based on the empirical characteristic function (ECF) of the data. The characteristic function of the exponential distribution has a specific form, and the test compares the ECF of the sample to the theoretical characteristic function of the exponential distribution. The test statistic measures the discrepancy between these two functions. +## Hypothesis and formula -Calculate the Test Statistic: The test statistic is derived from the integrated squared difference between the ECF and the theoretical characteristic function of the standard exponential distribution. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test may require large sample sizes to achieve high power. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The computation of the test statistic can be more complex compared to simpler tests like the Kolmogorov-Smirnov test. +$$ +\sqrt{48n}\left(n^{-1}\sum_i e^{-y_i}-\tfrac12\right) +$$ -## Usage +Signed contrast; both tails. This implementation uses the opposite sign to conventions based on 1/2 minus the empirical transform; a two-tail calibration is unchanged by that sign. -## Arguments +## Input and calibration -## Details +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -The Epps and Pulley test is a test for the composite hypothesis of exponentiality. The test statistic is +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ EP_n = (48n)^{1/2} [ \frac{1}{n} \sum_{j=1}^{n} exp(-Y_j) -\frac{1}{2} ] $$ +## Runnable example -where $Y_j=X_j/\overline{X}$. $EP_n$ is asymptotically standard normal (see, e.g., Henze and Meintanis (2005, Sec. 2.8.1). +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + EppsPulleyExponentialityGofStatistic, +) -## Author(s) -Lev Golofastov +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = EppsPulleyExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` -## References -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. — Metrika, vol. 61, pp. 29–45. +## Scientific references and verification status -## Examples +[Epps and Pulley (1986), A test of exponentiality vs. monotone-hazard alternatives derived from the empirical characteristic function](https://doi.org/10.1111/j.2517-6161.1986.tb01403.x). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/epstein_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/epstein_exp_criterion.md index 8fc76df0..c587b3bd 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/epstein_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/epstein_exp_criterion.md @@ -1,71 +1,61 @@ -# Epstein test for exponentiality +# Epstein spacing log contrast exponentiality criterion -## Description -Performs Epstein test for the composite hypothesis of exponentiality, see Epstein (1960a, 1960b). -The Epstein test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is based on normalized spacings between ordered observations and is designed to determine whether a given sample of lifetime data is consistent with an exponential distribution. +`EpsteinExponentialityGofStatistic` — short code `EPS`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Epstein statistic uses spacings between order statistics in a way that removes the unknown scale of the exponential distribution. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Epstein test statistic is based on the normalized spacings of the ordered sample. For exponential data, these normalized spacings have a structure that can be used to construct a goodness-of-fit statistic. Large values of the statistic indicate departures from exponentiality. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, the spacings between consecutive order statistics are multiplied by decreasing weights, and the statistic compares the logarithm of the arithmetic mean of these weighted spacings with the mean of their logarithms. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes positive lifetime-type observations, since the statistic uses logarithms of normalized spacings. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The chi-square approximation may require moderate or large sample sizes; small-sample calibration can require simulation or tabulated critical values. +$$ +\frac{2n\{\log\bar d-n^{-1}\sum_i\log d_i\}}{1+(n+1)/(6n)} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - EpsteinExponentialityGofStatistic, -) - - -test_statistic = EpsteinExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Epstein test is a test for the composite hypothesis of exponentiality. The test statistic is - -$$ EPS_n = \frac{2n\left(\log\left(n^{-1}\sum_{i=1}^{n}D_i\right) - n^{-1}\sum_{i=1}^{n}\log(D_i)\right)}{1+(n+1)/(6n)} $$ +Here d_i=(n-i+1)(x_(i)-x_(i-1)), x_(0)=0. The historical attribution and finite-n correction have not been verified against full primary text. The displayed local formula is checked independently; no chi-square null law is asserted. A zero spacing gives positive infinity. -where +## Input and calibration -$$ D_i = (n-i+1)(X_{(i)} - X_{(i-1)}), \quad X_{(0)} = 0, $$ +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -and $X_{(1)} \le \cdots \le X_{(n)}$ are the order statistics. +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -Under exponentiality, $EPS_n$ is approximately distributed as a chi-square random variable with $n-1$ degrees of freedom. - -## Author(s) -Lev Golofastov - -## References -Epstein, B. (1960a): Tests for the validity of the assumption that the underlying distribution of life is exponential. Part I. - Technometrics, vol. 2, no. 1, pp. 83-101. - -Epstein, B. (1960b): Tests for the validity of the assumption that the underlying distribution of life is exponential. Part II. - Technometrics, vol. 2, no. 2, pp. 167-183. - -Ascher, S. (1990): A survey of tests for exponentiality. - Communications in Statistics - Theory and Methods, vol. 19, pp. 1811-1825. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( EpsteinExponentialityGofStatistic, ) - -test_statistic = EpsteinExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = EpsteinExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Epstein (1960), Tests for the validity of the assumption that the underlying distribution of life is exponential: Part II](https://doi.org/10.1080/00401706.1960.10489892). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/freeman_tukey_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/freeman_tukey_exp_criterion.md new file mode 100644 index 00000000..c3c7b847 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/freeman_tukey_exp_criterion.md @@ -0,0 +1,73 @@ +# Freeman–Tukey exponentiality criterion + +`FreemanTukeyExponentialityGofStatistic` — short code `FREEMAN_TUKEY`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2 +$$ + +Power-divergence parameter -1/2; an empty observed cell contributes 4E_j. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +The `binning` keyword accepts a `BinningStrategy`. Default +`EqualProbabilityBins()` chooses the count from sample size; it is not fixed +at five. With unknown rate, built-in Monte Carlo requires this strategy; +other bins need external calibration at an explicit rate. Known-rate Pearson +has an asymptotic chi-square(k-1) law with suitable expected counts. After +fitting from ungrouped observations and moving bins, chi-square(k-2) is not +asserted. Empty-cell infinities are valid outcomes for Neyman and modified +log-likelihood; ties at infinity make rank calibration conservative. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + FreemanTukeyExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = FreemanTukeyExponentialityGofStatistic( + E.DEFAULT.parse({}), binning=EqualProbabilityBins(count=4) +) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Cressie and Read (1984), Multinomial goodness-of-fit tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/frozini_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/frozini_exp_criterion.md index 4aa1ed71..b66005ad 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/frozini_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/frozini_exp_criterion.md @@ -1,69 +1,61 @@ -# Frozini test for exponentiality +# Frozini EDF distance exponentiality criterion -## Description -Performs Frozini test for the composite hypothesis of exponentiality, see Frozini (1987). -The Frozini test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by comparing the empirical distribution function with the fitted exponential distribution function. +`FroziniExponentialityGofStatistic` — short code `FZ`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Frozini statistic estimates the unknown scale by the sample mean and then compares the fitted exponential cumulative distribution function with empirical plotting positions. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Frozini test statistic is based on absolute deviations between the fitted exponential cumulative distribution function and the expected empirical distribution function positions. Large values of the statistic indicate larger departures from exponentiality. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, the exponential cumulative distribution function with mean equal to the sample mean is evaluated at each order statistic, and the absolute differences from $(i-0.5)/n$ are summed and normalized by $\sqrt{n}$. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test is calibrated by the null distribution of the statistic, which is commonly obtained by Monte Carlo simulation. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic assumes lifetime-type observations and uses the fitted exponential distribution with scale equal to the sample mean. +$$ +n^{-1/2}\sum_i\left|u_i-\frac{i-1/2}{n}\right| +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - FroziniExponentialityGofStatistic, -) - - -test_statistic = FroziniExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Frozini test is a test for the composite hypothesis of exponentiality. The test statistic is +Fitted-rate EDF adaptation of the Frozini absolute discrepancy. Original reference: B. V. Frozini (1987), On the distribution and power of a goodness-of-fit statistic with parametric and nonparametric applications, in Goodness-of-fit, pp. 133–154. Exact primary-text attribution for this fitted convention remains unverified; the linked scientific article provides exponentiality context. -$$ B_n = \frac{1}{\sqrt{n}}\sum_{i=1}^{n}\left|1 - exp\left(-\frac{X_{(i)}}{\overline{X}}\right) - \frac{i - 0.5}{n}\right| $$ +## Input and calibration -where $X_{(i)}$ is the $i$-th order statistic, $n$ is the sample size, and $\overline{X}$ is the sample mean. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -The term +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ 1 - exp\left(-\frac{X_{(i)}}{\overline{X}}\right) $$ - -is the cumulative distribution function of the fitted exponential distribution evaluated at the ordered observation $X_{(i)}$. - -## Author(s) -Lev Golofastov - -## References -Frozini, B.V. (1987): On the distribution and power of a goodness-of-fit statistic with parametric and nonparametric applications. In: Revesz, P., Sarkadi, K. and Sen, P.K. (eds.) Goodness-of-fit. - Amsterdam-Oxford-New York: North-Holland, pp. 133-154. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( FroziniExponentialityGofStatistic, ) - -test_statistic = FroziniExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = FroziniExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Henze and Meintanis (2005), Recent and classical tests for exponentiality: a partial review with comparisons](https://doi.org/10.1007/s001840400322). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/gini_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/gini_exp_criterion.md index 3d9522df..0b2589c8 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/gini_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/gini_exp_criterion.md @@ -1,70 +1,61 @@ -# Test for exponentiality based on the Gini statistic +# Gini exponentiality criterion -## Description -Performs the Gini test for the composite hypothesis of exponentiality, see e.g. Gail and Gastwirth (1978) and Henze and Meintanis (2005). -The Gini test is a statistical goodness-of-fit test used to assess whether a given sample of data is consistent with an exponential distribution. This test is based on the sample Gini index, a scale-free measure constructed from the ordered spacings of the observations. +`GiniExponentialityGofStatistic` — short code `GINI`; both tails. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Gini statistic is scale invariant because it is normalized by the sample total, so the unknown exponential scale does not have to be specified. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Gini test statistic is based on Gini's mean difference and the associated Gini index. For exponential data the population Gini index is equal to one half, so deviations of the sample Gini index from this value indicate departures from exponentiality. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, consecutive spacings are weighted by the products of the numbers of observations below and above each spacing, and the result is normalized by the sample total. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test is intended for nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic is simple to compute, but critical values or p-values should be obtained from the appropriate exact, asymptotic, or simulation-based distribution for the chosen sample size. +$$ +\frac{\sum_{i0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The split point `r` can affect the sensitivity of the test. In the implementation the default value is `round(n / 2)`, where `n` is the sample size. +$$ +\frac{r^{-1}\sum_{i=1}^{r}d_i}{(n-r)^{-1}\sum_{i=r+1}^{n}d_i} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GnedenkoExponentialityGofStatistic, -) - - -test_statistic = GnedenkoExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -`r` - split point for the spacing ratio. Default value is `round(n / 2)`. - -## Details - -The Gnedenko F-test is a test for the composite hypothesis of exponentiality. Let -$X_{(1)} \leq \cdots \leq X_{(n)}$ denote the ordered sample and set $X_{(0)}=0$. Define the normalized spacings +Independent normalized exponential spacings give the exact F(2r,2(n-r)) null law. Constructor r=None selects max(1, round(n/2)); require 1<=r0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +2|E|/n +$$ + +Local graph statistic: vertices are observations; distinct vertices are adjacent iff abs(x_i-x_j)<(max(x)-min(x))/10. Both tails. n>=1, including all zeros; a constant sample gives an edgeless graph. No primary source validating this exact threshold/statistic as an exponentiality test was identified. Translation invariance prevents detection of a positive shift. Clique and independence computations exploit the one-dimensional threshold graph, checked against exhaustive graphs. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GraphAverageDegreeExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GraphAverageDegreeExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Dettmann and Georgiou (2016), Random geometric graphs with general connection functions](https://arxiv.org/abs/1411.3617). Background on geometric graphs, not a source for this exponentiality test or its range/10 threshold. + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/graph_clique_number_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/graph_clique_number_exp_criterion.md new file mode 100644 index 00000000..5f2cc3cf --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/graph_clique_number_exp_criterion.md @@ -0,0 +1,61 @@ +# Graph clique number exponentiality criterion + +`GraphCliqueNumberExponentialityGofStatistic` — short code `CLIQUENUMBER`; both tails. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\omega(G) +$$ + +Local graph statistic: vertices are observations; distinct vertices are adjacent iff abs(x_i-x_j)<(max(x)-min(x))/10. Both tails. n>=1, including all zeros; a constant sample gives an edgeless graph. No primary source validating this exact threshold/statistic as an exponentiality test was identified. Translation invariance prevents detection of a positive shift. Clique and independence computations exploit the one-dimensional threshold graph, checked against exhaustive graphs. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GraphCliqueNumberExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GraphCliqueNumberExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Dettmann and Georgiou (2016), Random geometric graphs with general connection functions](https://arxiv.org/abs/1411.3617). Background on geometric graphs, not a source for this exponentiality test or its range/10 threshold. + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/graph_connected_components_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/graph_connected_components_exp_criterion.md new file mode 100644 index 00000000..7f6dbb03 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/graph_connected_components_exp_criterion.md @@ -0,0 +1,61 @@ +# Graph connected components exponentiality criterion + +`GraphConnectedComponentsExponentialityGofStatistic` — short code `CONNECTEDCOMPONENTS`; both tails. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\#\{\text{connected components}\} +$$ + +Local graph statistic: vertices are observations; distinct vertices are adjacent iff abs(x_i-x_j)<(max(x)-min(x))/10. Both tails. n>=1, including all zeros; a constant sample gives an edgeless graph. No primary source validating this exact threshold/statistic as an exponentiality test was identified. Translation invariance prevents detection of a positive shift. Clique and independence computations exploit the one-dimensional threshold graph, checked against exhaustive graphs. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GraphConnectedComponentsExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GraphConnectedComponentsExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Dettmann and Georgiou (2016), Random geometric graphs with general connection functions](https://arxiv.org/abs/1411.3617). Background on geometric graphs, not a source for this exponentiality test or its range/10 threshold. + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/graph_edges_number_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/graph_edges_number_exp_criterion.md index b5f6fc28..adb96adc 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/graph_edges_number_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/graph_edges_number_exp_criterion.md @@ -1,16 +1,61 @@ -# Graph edges number test for exponentiality +# Graph edge count exponentiality criterion -## Description +`GraphEdgesNumberExponentialityGofStatistic` — short code `EDGESNUMBER`; both tails. -## Usage +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -## Arguments +## Hypothesis and formula -## Details +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -## Author(s) -Ivan Pokhabov +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -## References +$$ +|E| +$$ -## Examples +Local graph statistic: vertices are observations; distinct vertices are adjacent iff abs(x_i-x_j)<(max(x)-min(x))/10. Both tails. n>=1, including all zeros; a constant sample gives an edgeless graph. No primary source validating this exact threshold/statistic as an exponentiality test was identified. Translation invariance prevents detection of a positive shift. Clique and independence computations exploit the one-dimensional threshold graph, checked against exhaustive graphs. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GraphEdgesNumberExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GraphEdgesNumberExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Dettmann and Georgiou (2016), Random geometric graphs with general connection functions](https://arxiv.org/abs/1411.3617). Background on geometric graphs, not a source for this exponentiality test or its range/10 threshold. + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/graph_independence_number_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/graph_independence_number_exp_criterion.md new file mode 100644 index 00000000..0aece238 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/graph_independence_number_exp_criterion.md @@ -0,0 +1,61 @@ +# Graph independence number exponentiality criterion + +`GraphIndependenceNumberExponentialityGofStatistic` — short code `INDEPENDENCENUMBER`; both tails. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\alpha(G) +$$ + +Local graph statistic: vertices are observations; distinct vertices are adjacent iff abs(x_i-x_j)<(max(x)-min(x))/10. Both tails. n>=1, including all zeros; a constant sample gives an edgeless graph. No primary source validating this exact threshold/statistic as an exponentiality test was identified. Translation invariance prevents detection of a positive shift. Clique and independence computations exploit the one-dimensional threshold graph, checked against exhaustive graphs. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GraphIndependenceNumberExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GraphIndependenceNumberExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Dettmann and Georgiou (2016), Random geometric graphs with general connection functions](https://arxiv.org/abs/1411.3617). Background on geometric graphs, not a source for this exponentiality test or its range/10 threshold. + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/graph_max_degree_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/graph_max_degree_exp_criterion.md index 39feaa9a..014f0f8d 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/graph_max_degree_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/graph_max_degree_exp_criterion.md @@ -1,16 +1,61 @@ -# Graph max degree test for exponentiality +# Graph maximum degree exponentiality criterion -## Description +`GraphMaxDegreeExponentialityGofStatistic` — short code `MAXDEGREE`; both tails. -## Usage +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -## Arguments +## Hypothesis and formula -## Details +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -## Author(s) -Ivan Pokhabov +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -## References +$$ +\max_v\deg(v) +$$ -## Examples +Local graph statistic: vertices are observations; distinct vertices are adjacent iff abs(x_i-x_j)<(max(x)-min(x))/10. Both tails. n>=1, including all zeros; a constant sample gives an edgeless graph. No primary source validating this exact threshold/statistic as an exponentiality test was identified. Translation invariance prevents detection of a positive shift. Clique and independence computations exploit the one-dimensional threshold graph, checked against exhaustive graphs. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GraphMaxDegreeExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GraphMaxDegreeExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Dettmann and Georgiou (2016), Random geometric graphs with general connection functions](https://arxiv.org/abs/1411.3617). Background on geometric graphs, not a source for this exponentiality test or its range/10 threshold. + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/greenwood_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/greenwood_exp_criterion.md new file mode 100644 index 00000000..9aa84897 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/greenwood_exp_criterion.md @@ -0,0 +1,61 @@ +# Greenwood exponentiality criterion + +`GreenwoodExponentialityGofStatistic` — short code `GREENWOOD`; both tails. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +G=\frac{\sum_i x_i^2}{(\sum_i x_i)^2} +$$ + +Both tails. Normalized raw observations, not ordered spacings. Under the null, E(G)=2/(n+1), Var(G)=4(n-1)/[(n+1)^2(n+2)(n+3)]. This moment statistic is not universally consistent. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + GreenwoodExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = GreenwoodExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Arendarczyk, Kozubowski and Panorska (2022), The Greenwood statistic, stochastic dominance, clustering and heavy tails](https://doi.org/10.1111/sjos.12520). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/harris_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/harris_exp_criterion.md index d9c5aad2..1541f92c 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/harris_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/harris_exp_criterion.md @@ -1,76 +1,61 @@ -# Harris modification of Gnedenko F-test +# Harris F ratio exponentiality criterion -## Description -Performs Harris modification of Gnedenko F-test for the composite hypothesis of exponentiality, see e.g. Harris (1976). -The Harris modification is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by comparing tail groups of normalized spacings with the middle group of normalized spacings. +`HarrisExponentialityGofStatistic` — short code `HM`; both tails. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Harris statistic is based on normalized spacings, so the unknown exponential scale is removed from the comparison. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Harris modification improves the Gnedenko F-test by using a symmetric spacing comparison. Instead of comparing only the first group of spacings with the remaining spacings, it combines the first and last `r` normalized spacings and compares their average with the average of the middle spacings. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted after adding zero as the lower endpoint, normalized spacings are calculated, the first and last `r` spacings are averaged, and the result is divided by the average of the middle spacings. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The split point `r` can affect the sensitivity of the test. In the implementation the default value is `round(n / 4)`, where `n` is the sample size. +$$ +\frac{(2r)^{-1}\left(\sum_{i=1}^{r}d_i+\sum_{i=n-r+1}^{n}d_i\right)}{(n-2r)^{-1}\sum_{i=r+1}^{n-r}d_i} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - HarrisExponentialityGofStatistic, -) - - -test_statistic = HarrisExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -`r` - split point for the symmetric spacing comparison. Default value is `round(n / 4)`. - -## Details - -The Harris modification of Gnedenko F-test is a test for the composite hypothesis of exponentiality. Let -$X_{(1)} \leq \cdots \leq X_{(n)}$ denote the ordered sample and set $X_{(0)}=0$. Define the normalized spacings - -$$ D_i = (n-i+1)(X_{(i)}-X_{(i-1)}), \quad i=1,\ldots,n. $$ +Exact F(4r,2(n-2r)) null law follows from disjoint exponential spacings. Constructor r=None selects max(1, round(n/4)); require 1<=2r0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -## Author(s) -Lev Golofastov +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -## References +$$ +n^{-1}\sum_i\left|y_{(i)}+\log(1-i/(n+1))\right|^1 +$$ -## Examples +The exponential HG1 and HG2 tests are described by Ushakov and Ushakov in the scientific article cited below. Their scientific attribution is established; they are not listed as tests with unconfirmed provenance. Calibrate under the fitted exponential null. Historical publication priority is separate from verification of the implemented formula and calibration. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + HegazyGreen1ExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = HegazyGreen1ExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Ushakov and Ushakov, On sensitivity of exponentiality tests to data rounding: a Monte Carlo simulation study](https://doi.org/10.1080/03610918.2021.2009868). + +[Hegazy and Green (1975), Some new goodness-of-fit tests using order statistics](https://doi.org/10.2307/2347090). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/hegazy2_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/hegazy2_exp_criterion.md index d0be0003..61031f42 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/hegazy2_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/hegazy2_exp_criterion.md @@ -1,16 +1,63 @@ -# Hegazy-Green test for exponentiality +# Hegazy–Green 2 exponentiality criterion -## Description +`HegazyGreen2ExponentialityGofStatistic` — short code `HG2`; right tail. -## Usage +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -## Arguments +## Hypothesis and formula -## Details +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -## Author(s) -Lev Golofastov +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -## References +$$ +n^{-1}\sum_i\left|y_{(i)}+\log(1-i/(n+1))\right|^2 +$$ -## Examples +The exponential HG1 and HG2 tests are described by Ushakov and Ushakov in the scientific article cited below. Their scientific attribution is established; they are not listed as tests with unconfirmed provenance. Calibrate under the fitted exponential null. Historical publication priority is separate from verification of the implemented formula and calibration. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + HegazyGreen2ExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = HegazyGreen2ExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Ushakov and Ushakov, On sensitivity of exponentiality tests to data rounding: a Monte Carlo simulation study](https://doi.org/10.1080/03610918.2021.2009868). + +[Hegazy and Green (1975), Some new goodness-of-fit tests using order statistics](https://doi.org/10.2307/2347090). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/holander_proshan_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/holander_proshan_exp_criterion.md index 65054080..b6ecebe0 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/holander_proshan_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/holander_proshan_exp_criterion.md @@ -1,69 +1,61 @@ -# Hollander-Proshan test for exponentiality +# Hollander–Proschan exponentiality criterion -## Description -Performs Hollander-Proshan test for the composite hypothesis of exponentiality, see e.g. Hollander and Proschan (1972). -The Hollander-Proshan test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by using a U-statistic based on the comparison of one lifetime with the sum of two other lifetimes. +`HollanderProshanExponentialityGofStatistic` — short code `HP`; left tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Hollander-Proshan statistic is scale invariant because it uses only comparisons of sample observations and their sums. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Hollander-Proshan test statistic is based on the new-better-than-used property from reliability theory. For an exponential distribution, a new item is stochastically equivalent to a used item of any age. The statistic counts how often one observation is greater than the sum of two other observations. +## Hypothesis and formula -Calculate the Test Statistic: For all triples of distinct observations with the second and third indices ordered as `j < k`, count the indicator of the event $X_i > X_j + X_k$ and normalize this count by the number of possible triples. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The computation uses a triple loop over the sample and can be expensive for large samples. +$$ +\frac{\sum_{i,j,k\ \mathrm{distinct}}\mathbf1\{x_i>x_j+x_k\}}{n(n-1)(n-2)} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - HollanderProshanExponentialityGofStatistic, -) - - -test_statistic = HollanderProshanExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Hollander-Proshan test is a test for the composite hypothesis of exponentiality. The test statistic implemented here is +Raw probability U-statistic with null mean 1/4. For NBU alternatives P(X>Y+Z)<=1/4, so the criterion rejects in the left tail. Name spelling Proshan is retained for API compatibility. -$$ HP_n = \frac{2}{n(n-1)(n-2)} \sum_{i\ne j,\, i\ne k,\, j X_j + X_k). $$ +## Input and calibration -Here $n$ is the sample size and $I(\cdot)$ is the indicator function. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -Under exponentiality, +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ \sqrt{n}\left(HP_n-\frac{1}{4}\right) \xrightarrow{d} N\left(0,\frac{5}{432}\right). $$ - -Large values of $HP_n$ indicate larger deviations from the exponential model in the direction used by the implemented right-sided alternative. - -## Author(s) -Lev Golofastov - -## References -Hollander, M. and Proschan, F. (1972): Testing whether new is better than used. - Annals of Mathematical Statistics, vol. 43, no. 4, pp. 1136-1146. https://doi.org/10.1214/aoms/1177692466 - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( HollanderProshanExponentialityGofStatistic, ) - -test_statistic = HollanderProshanExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = HollanderProshanExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Hollander and Proschan (1972), Testing whether new is better than used](https://doi.org/10.1214/aoms/1177692466). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/index.md b/docs/criteria/goodness-of-fit/exponentiality/index.md new file mode 100644 index 00000000..5880d8ed --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/index.md @@ -0,0 +1,119 @@ +# Exponential goodness-of-fit criteria + +`continuous/exponent` exports **50 concrete criteria**: 14 generated EDF +classes (including fitted-rate Lilliefors), 5 generated frequency classes and +31 specialized classes. Every criterion is linked below with its class name, +short code, hypothesis and example. See [mathematical verification](mathematical-validation.md) +for formulas, evidence and explicit provenance limitations, including the +[scientific bibliography with article links](mathematical-validation.md#scientific-bibliography). + +## Model and use + +The origin is zero; `lam` is the positive **rate**, not the scale. The mean is +`1/lam`. Pass `ExponentialDistributionDescriptor.DEFAULT.parse({'lam': 2})` +for a specified rate or `parse({})` for an unknown rate where supported. +The latter is fitted within each generated criterion call. KS D+/D−/D accept +only a fixed rate; Lilliefors accepts only an unknown rate. Other generated +criteria accept both. Specialized criteria accept the unknown-rate model. + +Full codes append `_EXPONENTIALITY_GOODNESS_OF_FIT` to the short code. +Class prefixes in the tables append `ExponentialityGofStatistic`. +`fixed` means a specified rate, `unknown` means a composite hypothesis. +Right-tail discrepancies reject large values; both-tail rules use both +extremes. Not all named legacy classes are established omnibus tests: +**Six graph criteria are local constructions**. WE uses the published +normalization $G-1/n$, where $G$ is Greenwood. Several historical +conventions remain qualified in the report. Hollander–Proschan uses the left tail against NBU alternatives. + +## Edf criteria + +| Criterion | Class prefix | Code | Rate | Rejection | +|---|---|---|---|---| +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_exp_criterion.md) | `KolmogorovSmirnovDPlus` | `KS_PLUS` | fixed | right tail | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_exp_criterion.md) | `KolmogorovSmirnovDMinus` | `KS_MINUS` | fixed | right tail | +| [Kolmogorov–Smirnov](kolmogorov_smirnov_exp_criterion.md) | `KolmogorovSmirnov` | `KS` | fixed | right tail | +| [Lilliefors exponential](lilliefors_exp_criterion.md) | `Lilliefors` | `LILLIE` | unknown | right tail | +| [Anderson–Darling](anderson_darling_exp_criterion.md) | `AndersonDarling` | `AD` | unknown/fixed | right tail | +| [Cramér–von Mises](cvm_exp_criterion.md) | `CramerVonMises` | `CVM` | fixed/unknown | right tail | +| [Liao–Shimokawa](liao_shimokawa_exp_criterion.md) | `LiaoShimokawa` | `LS` | unknown/fixed | right tail | +| [Watson](watson_exp_criterion.md) | `Watson` | `W` | unknown/fixed | right tail | +| [Kuiper](kuiper_exp_criterion.md) | `Kuiper` | `KUIPER` | unknown/fixed | right tail | +| [Scaled Kuiper](kuiper_scaled_exp_criterion.md) | `KuiperScaled` | `KUIPER_SCALED` | unknown/fixed | right tail | +| [Corrected Kuiper](kuiper_corrected_exp_criterion.md) | `KuiperCorrected` | `KUIPER_CORRECTED` | unknown/fixed | right tail | +| [Zhang Z_K](zhang_k_exp_criterion.md) | `ZhangK` | `ZHANG_ZK` | unknown/fixed | right tail | +| [Zhang Z_A](zhang_a_exp_criterion.md) | `ZhangA` | `ZHANG_ZA` | unknown/fixed | right tail | +| [Zhang Z_C](zhang_c_exp_criterion.md) | `ZhangC` | `ZHANG_ZC` | unknown/fixed | right tail | + +## Frequency criteria + +| Criterion | Class prefix | Code | Rate | Rejection | +|---|---|---|---|---| +| [Pearson chi-square](pearson_exp_criterion.md) | `Chi2Pearson` | `CHI2_PEARSON` | unknown/fixed | right tail | +| [Freeman–Tukey](freeman_tukey_exp_criterion.md) | `FreemanTukey` | `FREEMAN_TUKEY` | unknown/fixed | right tail | +| [Modified log-likelihood](modified_log_likelihood_exp_criterion.md) | `ModifiedLogLikelihood` | `MODIFIED_LOG_LIKELIHOOD` | unknown/fixed | right tail | +| [Neyman chi-square](neyman_chi2_exp_criterion.md) | `NeymanChi2` | `CHI2_NEYMAN` | unknown/fixed | right tail | +| [Cressie–Read](cressie_read_exp_criterion.md) | `CressieRead` | `CRESSIE_READ` | unknown/fixed | right tail | + +## Specialized criteria + +| Criterion | Class prefix | Code | Rate | Rejection | +|---|---|---|---|---| +| [Epps–Pulley](epps_pulley_exp_criterion.md) | `EppsPulley` | `EP` | unknown | both tails | +| [Ahsanullah](ahsanullah_exp_criterion.md) | `Ahsanullah` | `AHS` | unknown | right tail | +| [Atkinson](atkinson_exp_criterion.md) | `Atkinson` | `ATK` | unknown | right tail | +| [Cox–Oakes](cox_oakes_exp_criterion.md) | `CoxOakes` | `CO` | unknown | both tails | +| [Deshpande](deshpande_exp_criterion.md) | `Deshpande` | `DSP` | unknown | right tail | +| [Epstein spacing log contrast](epstein_exp_criterion.md) | `Epstein` | `EPS` | unknown | right tail | +| [Frozini EDF distance](frozini_exp_criterion.md) | `Frozini` | `FZ` | unknown | right tail | +| [Gini](gini_exp_criterion.md) | `Gini` | `GINI` | unknown | both tails | +| [Gnedenko F ratio](gnedenko_exp_criterion.md) | `Gnedenko` | `GD` | unknown | both tails | +| [Harris F ratio](harris_exp_criterion.md) | `Harris` | `HM` | unknown | both tails | +| [Hegazy–Green 1](hegazy1_exp_criterion.md) | `HegazyGreen1` | `HG1` | unknown | right tail | +| [Hegazy–Green 2](hegazy2_exp_criterion.md) | `HegazyGreen2` | `HG2` | unknown | right tail | +| [Hollander–Proschan](holander_proshan_exp_criterion.md) | `HollanderProshan` | `HP` | unknown | left tail | +| [Kimber–Michael](kimber_michael_exp_criterion.md) | `KimberMichael` | `KM` | unknown | right tail | +| [Kochar exponential scores](kochar_exp_criterion.md) | `Kochar` | `KC` | unknown | right tail | +| [Lorenz ordinate](lorenz_exp_criterion.md) | `Lorenz` | `LZ` | unknown | right tail | +| [Moran log-mean contrast](moran_exp_criterion.md) | `Moran` | `MN` | unknown | both tails | +| [Pietra](pietra_exp_criterion.md) | `Pietra` | `PT` | unknown | both tails | +| [Shapiro–Wilk exponential W](shapiro_wilk_exp_criterion.md) | `ShapiroWilk` | `SW` | unknown | both tails | +| [Rossberg integral contrast](rossberg_exp_criterion.md) | `Rossberg` | `RS` | unknown | right tail | +| [WE](we_exp_criterion.md) | `We` | `WE` | unknown | right tail | +| [Wong–Wong extremal quotient](wong_wong_exp_criterion.md) | `WongWong` | `WW` | unknown | right tail | +| [Greenwood](greenwood_exp_criterion.md) | `Greenwood` | `GREENWOOD` | unknown | both tails | +| [Baringhaus–Henze empirical Laplace transform](baringhaus_henze_elt_exp_criterion.md) | `BaringhausHenzeELT` | `BH_ELT` | unknown | right tail | +| [Baringhaus–Henze mean residual life](baringhaus_henze_bhc_exp_criterion.md) | `BaringhausHenzeBHC` | `BH_BHC` | unknown | right tail | +| [Graph edge count](graph_edges_number_exp_criterion.md) | `GraphEdgesNumber` | `EDGESNUMBER` | unknown | both tails | +| [Graph maximum degree](graph_max_degree_exp_criterion.md) | `GraphMaxDegree` | `MAXDEGREE` | unknown | both tails | +| [Graph average degree](graph_average_degree_exp_criterion.md) | `GraphAverageDegree` | `AVGDEGREE` | unknown | both tails | +| [Graph connected components](graph_connected_components_exp_criterion.md) | `GraphConnectedComponents` | `CONNECTEDCOMPONENTS` | unknown | both tails | +| [Graph clique number](graph_clique_number_exp_criterion.md) | `GraphCliqueNumber` | `CLIQUENUMBER` | unknown | both tails | +| [Graph independence number](graph_independence_number_exp_criterion.md) | `GraphIndependenceNumber` | `INDEPENDENCENUMBER` | unknown | both tails | + +## Calibration example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + AndersonDarlingExponentialityGofStatistic, +) +from pysatl_criterion.hypothesis_testing.exponential_monte_carlo import monte_carlo_exponential + +criterion = AndersonDarlingExponentialityGofStatistic(E.DEFAULT.parse({})) +result = monte_carlo_exponential( + criterion, + [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80], + n_resamples=199, + random_state=20261015, +) +print(result.statistic, result.p_value) +``` + +Every replicate repeats fitting and preserves settings. Rank p-values retain +infinite boundary penalties and include ties. `binning=EqualProbabilityBins(count=5)` +reproduces the old Pearson bin count; its current code is `CHI2_PEARSON`. +Use the separate D+ and D− classes in place of `alternative_type` on KS. + +The examples use ordinary public imports. The audit records a pre-existing +aggregate-import error in this checkout and describes the isolated test run; +that run does not establish package-wide import health. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kimber_michael_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kimber_michael_exp_criterion.md index 2858014d..4f320509 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/kimber_michael_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/kimber_michael_exp_criterion.md @@ -1,74 +1,61 @@ -# Kimber-Michael test for exponentiality +# Kimber–Michael exponentiality criterion -## Description -Performs Kimber-Michael test for the composite hypothesis of exponentiality, see e.g. Michael (1983) and Kimber (1985). -The Kimber-Michael test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is based on the stabilized probability plot and is designed to determine whether a given sample of data is consistent with an exponential distribution. +`KimberMichaelExponentialityGofStatistic` — short code `KM`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Kimber-Michael statistic removes the unknown exponential scale by evaluating the exponential distribution at observations normalized by the sample mean. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Kimber-Michael test statistic is based on an arcsine square-root transformation of probabilities. This transformation stabilizes the variance of probability plot points, and the statistic measures the maximum absolute distance between transformed empirical plotting positions and transformed fitted exponential probabilities. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, divided by the sample mean, transformed through the fitted exponential distribution function, mapped to the stabilized probability scale, and compared with the stabilized plotting positions. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic is a supremum-type distance, so it is most sensitive to the largest stabilized probability plot discrepancy. +$$ +\max_i\left|A(u_i)-A((i-1/2)/n)\right|,\quad A(u)=2\arcsin(\sqrt u)/\pi +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KimberMichaelExponentialityGofStatistic, -) - - -test_statistic = KimberMichaelExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Kimber-Michael test is a test for the composite hypothesis of exponentiality. Let -$X_{(1)} \leq \cdots \leq X_{(n)}$ denote the ordered sample. The test statistic implemented here is - -$$ KM_n = \max_{1 \leq i \leq n} \left| \frac{2}{\pi}\arcsin\sqrt{\frac{i-1/2}{n}} - \frac{2}{\pi}\arcsin\sqrt{1-exp(-X_{(i)}/\overline{X})} \right|. $$ +The 2/pi multiplier and midpoint plotting positions are part of the convention; rate is re-estimated for each sample. Published critical values require matching fitting and normalization. -Here $n$ is the sample size and $\overline{X}$ is the sample mean. +## Input and calibration -The function +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -$$ p \mapsto \frac{2}{\pi}\arcsin\sqrt{p} $$ +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -is the stabilized probability scale introduced by Michael (1983). Kimber (1985) applied this idea to tests for the exponential, Weibull, and Gumbel distributions. - -The implementation uses a left-sided alternative, so unusually small values of $KM_n$ are treated as evidence in the direction used by this statistic. - -## Author(s) -Lev Golofastov - -## References -Michael, J.R. (1983): The stabilized probability plot. - Biometrika, vol. 70, no. 1, pp. 11-17. https://doi.org/10.1093/biomet/70.1.11 - -Kimber, A.C. (1985): Tests for the exponential, Weibull and Gumbel distributions based on the stabilized probability plot. - Biometrika, vol. 72, no. 3, pp. 661-663. https://doi.org/10.1093/biomet/72.3.661 - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( KimberMichaelExponentialityGofStatistic, ) - -test_statistic = KimberMichaelExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KimberMichaelExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Kimber (1985), Tests for the exponential, Weibull and Gumbel distributions based on the stabilized probability plot](https://doi.org/10.1093/biomet/72.3.661). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kochar_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kochar_exp_criterion.md index e3130305..b80b1fac 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/kochar_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/kochar_exp_criterion.md @@ -1,70 +1,61 @@ -# Kochar test for exponentiality +# Kochar exponential scores exponentiality criterion -## Description -Performs Kochar test for the composite hypothesis of exponentiality, see e.g. Kochar (1985). -The Kochar test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution against monotone failure rate average alternatives. +`KocharExponentialityGofStatistic` — short code `KC`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Kochar statistic is scale invariant because it is normalized by the sample total. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Kochar test statistic is based on a weighted linear combination of order statistics. The weights are defined by a score function evaluated at the plotting positions $i/(n+1)$, and the resulting weighted sum is standardized to have an asymptotic standard normal distribution under exponentiality. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, Kochar scores are calculated at the plotting positions, the weighted sum of the ordered observations is divided by the sample total, and the result is multiplied by the normalizing factor. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The test is designed for monotone failure rate average alternatives, so it may be less sensitive to other departures from exponentiality. +$$ +\sqrt{108n/17}\frac{\sum_i J(i/(n+1))x_{(i)}}{\sum_i x_i},\quad J(u)=2(1-u)[1-\log(1-u)]-1 +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KocharExponentialityGofStatistic, -) - - -test_statistic = KocharExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Kochar test is a test for the composite hypothesis of exponentiality. Let -$X_{(1)} \leq \cdots \leq X_{(n)}$ denote the ordered sample. The test statistic implemented here is +Right-tail score statistic with the i/(n+1) convention. Finite-n normality is not exact; use Monte Carlo. Formula verified against direct score summation; full primary-text/table equivalence remains unverified. -$$ KC_n = \sqrt{\frac{108n}{17}}\frac{\sum_{i=1}^{n}J(i/(n+1))X_{(i)}}{\sum_{i=1}^{n}X_i}, $$ +## Input and calibration -where +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -$$ J(u) = 2(1-u)(1-\log(1-u)) - 1. $$ +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -Here $n$ is the sample size. Under the null hypothesis of exponentiality, $KC_n$ is asymptotically standard normal. - -Large values of $KC_n$ indicate larger deviations from the exponential model in the direction used by the implemented right-sided alternative. - -## Author(s) -Lev Golofastov - -## References -Kochar, S.C. (1985): Testing exponenttality against monotone failure rate average. - Communications in Statistics - Theory and Methods, vol. 14, no. 2, pp. 381-392. https://doi.org/10.1080/03610928508828919 - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( KocharExponentialityGofStatistic, ) - -test_statistic = KocharExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KocharExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Kochar (1985), Testing exponentiality against monotone failure rate average](https://doi.org/10.1080/03610928508828919). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_d_minus_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_d_minus_exp_criterion.md new file mode 100644 index 00000000..5fc5bfe9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_d_minus_exp_criterion.md @@ -0,0 +1,61 @@ +# Kolmogorov–Smirnov D− exponentiality criterion + +`KolmogorovSmirnovDMinusExponentialityGofStatistic` — short code `KS_MINUS`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed rate only: pass `E.DEFAULT.parse({"lam": rate})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +D^-=\max_i(u_i-(i-1)/n) +$$ + + + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + KolmogorovSmirnovDMinusExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KolmogorovSmirnovDMinusExponentialityGofStatistic(E.DEFAULT.parse({"lam": 1.0})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_d_plus_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_d_plus_exp_criterion.md new file mode 100644 index 00000000..a98111f3 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_d_plus_exp_criterion.md @@ -0,0 +1,61 @@ +# Kolmogorov–Smirnov D+ exponentiality criterion + +`KolmogorovSmirnovDPlusExponentialityGofStatistic` — short code `KS_PLUS`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed rate only: pass `E.DEFAULT.parse({"lam": rate})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +D^+=\max_i(i/n-u_i) +$$ + + + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + KolmogorovSmirnovDPlusExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KolmogorovSmirnovDPlusExponentialityGofStatistic(E.DEFAULT.parse({"lam": 1.0})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_exp_criterion.md index 0ec87a94..25fbb545 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/kolmogorov_smirnov_exp_criterion.md @@ -1,63 +1,61 @@ -# Test for exponentiality of Kolmogorov and Smirnov +# Kolmogorov–Smirnov exponentiality criterion -## Description -Performs Kolmogorov-Smirnov test for the hypothesis of exponentiality. -The Kolmogorov-Smirnov test is a classical empirical distribution function test used to assess whether a given sample of data is consistent with a specified theoretical distribution. In the case of exponentiality, the test compares the empirical distribution function of the sample with the cumulative distribution function of the exponential distribution. +`KolmogorovSmirnovExponentialityGofStatistic` — short code `KS`; right tail. -Hypothesis of Exponentiality -The hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution. The exponential distribution is widely used in reliability theory, survival analysis, queuing theory, and other fields where waiting times or lifetimes are modeled. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Kolmogorov-Smirnov test statistic is based on the maximum absolute difference between the empirical distribution function and the theoretical cumulative distribution function of the exponential distribution. Large values of the statistic indicate that the sample distribution differs from the exponential model. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, the theoretical exponential cumulative distribution function is evaluated at the ordered observations, and the largest positive or negative deviation from the empirical distribution function is used as the test statistic. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed rate only: pass `E.DEFAULT.parse({"lam": rate})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The classical Kolmogorov-Smirnov test is most direct when the distribution parameters are fixed in advance. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -When parameters are estimated from the same sample, the usual Kolmogorov-Smirnov critical values are no longer directly applicable and adjusted critical values or simulation-based calibration may be required. +$$ +D=\max(D^+,D^-) +$$ -## Usage +Use the separate D+ and D− classes instead of the removed alternative_type constructor keyword. -## Arguments +## Input and calibration -## Details +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -The Kolmogorov-Smirnov test is an empirical distribution function test for exponentiality. The two-sided test statistic is +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ D_n = \max(D_n^+, D_n^-) $$ - -where - -$$ D_n^+ = \max_{1 \le i \le n} \left( \frac{i}{n} - F_0(X_{(i)}) \right) $$ - -and - -$$ D_n^- = \max_{1 \le i \le n} \left( F_0(X_{(i)}) - \frac{i - 1}{n} \right). $$ - -Here $X_{(i)}$ is the $i$-th order statistic and $F_0$ is the cumulative distribution function of the reference exponential distribution. In the implementation, $F_0$ is the standard exponential cumulative distribution function. - -For one-sided alternatives, the statistic is $D_n^+$ or $D_n^-$ respectively. - -## Author(s) -Lev Golofastov - -## References -Kolmogorov, A.N. (1933): Sulla determinazione empirica di una legge di distribuzione. — Giornale dell'Istituto Italiano degli Attuari, vol. 4, pp. 83-91. - -Smirnov, N.V. (1948): Table for estimating the goodness of fit of empirical distributions. — Annals of Mathematical Statistics, vol. 19, pp. 279-281. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. — Metrika, vol. 61, pp. 29–45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( KolmogorovSmirnovExponentialityGofStatistic, ) - -test_statistic = KolmogorovSmirnovExponentialityGofStatistic(lam=0.5) -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KolmogorovSmirnovExponentialityGofStatistic(E.DEFAULT.parse({"lam": 1.0})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kuiper_corrected_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kuiper_corrected_exp_criterion.md new file mode 100644 index 00000000..918d6bf3 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/kuiper_corrected_exp_criterion.md @@ -0,0 +1,61 @@ +# Corrected Kuiper exponentiality criterion + +`KuiperCorrectedExponentialityGofStatistic` — short code `KUIPER_CORRECTED`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +V_c=(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-) +$$ + +The multiplier defines this variant; it is not an exact finite-sample correction for a fitted exponential null. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + KuiperCorrectedExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KuiperCorrectedExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kuiper_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kuiper_exp_criterion.md new file mode 100644 index 00000000..d5097f38 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/kuiper_exp_criterion.md @@ -0,0 +1,61 @@ +# Kuiper exponentiality criterion + +`KuiperExponentialityGofStatistic` — short code `KUIPER`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +V=D^++D^- +$$ + + + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + KuiperExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KuiperExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Kuiper (1960), Tests concerning random points on a circle](https://doi.org/10.1016/S1385-7258(60)50006-0). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/kuiper_scaled_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/kuiper_scaled_exp_criterion.md new file mode 100644 index 00000000..84122be0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/kuiper_scaled_exp_criterion.md @@ -0,0 +1,61 @@ +# Scaled Kuiper exponentiality criterion + +`KuiperScaledExponentialityGofStatistic` — short code `KUIPER_SCALED`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +V_s=\sqrt n(D^++D^-) +$$ + +Scaling does not supply a p-value or remove the need to account for fitted parameters. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + KuiperScaledExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = KuiperScaledExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Lemeshko et al. (2014), Using the Kuiper and Watson tests of goodness-of-fit for composite hypotheses](https://doi.org/10.3103/S875669901401004X). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/liao_shimokawa_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/liao_shimokawa_exp_criterion.md new file mode 100644 index 00000000..c5183ae9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/liao_shimokawa_exp_criterion.md @@ -0,0 +1,61 @@ +# Liao–Shimokawa exponentiality criterion + +`LiaoShimokawaExponentialityGofStatistic` — short code `LS`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\frac1{\sqrt n}\sum_i\frac{\max(i/n-u_i,u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}} +$$ + +Exponential application of a shared EDF functional. The original estimated Weibull/extreme-value critical values do not apply to this fitting problem. Endpoints give positive infinity. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + LiaoShimokawaExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = LiaoShimokawaExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Liao and Shimokawa (1999), A new goodness-of-fit test for Type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/lilliefors_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/lilliefors_exp_criterion.md new file mode 100644 index 00000000..3e04cc81 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/lilliefors_exp_criterion.md @@ -0,0 +1,61 @@ +# Lilliefors exponential exponentiality criterion + +`LillieforsExponentialityGofStatistic` — short code `LILLIE`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +D=\max(D^+,D^-),\quad u_i=1-e^{-x_{(i)}/\bar x} +$$ + +The rate is unknown and fitted. Fixed-null KS tables are invalid here. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + LillieforsExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = LillieforsExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Lilliefors (1969), On the Kolmogorov–Smirnov test for the exponential distribution with mean unknown](https://doi.org/10.1080/01621459.1969.10500983). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/lorenz_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/lorenz_exp_criterion.md index b876c188..3c215446 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/lorenz_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/lorenz_exp_criterion.md @@ -1,74 +1,61 @@ -# Lorenz test for exponentiality +# Lorenz ordinate exponentiality criterion -## Description -Performs Lorenz test for the composite hypothesis of exponentiality, see e.g. Gail and Gastwirth (1978). -The Lorenz test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by comparing the sample Lorenz curve with the Lorenz curve of the exponential distribution. +`LorenzExponentialityGofStatistic` — short code `LZ`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Lorenz statistic is scale invariant because it is calculated as a ratio of partial sums to the sample total. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Lorenz test statistic is based on the sample Lorenz curve. For a fixed value `p`, the statistic measures the share of the sample total contributed by the smallest fraction `p` of the ordered observations. +## Hypothesis and formula -Calculate the Test Statistic: The observations are sorted, the first `int(n * p)` ordered observations are summed, and this partial sum is divided by the full sample sum. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The choice of the Lorenz curve point `p` can affect the power of the test. In the implementation the default value is `0.5`. +$$ +\frac{\sum_{i=1}^{\lfloor np\rfloor}x_{(i)}}{\sum_i x_i} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LorenzExponentialityGofStatistic, -) - - -test_statistic = LorenzExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -`p` - Lorenz curve point used by the statistic. Default value is `0.5`. - -## Details - -The Lorenz test is a test for the composite hypothesis of exponentiality. Let -$X_{(1)} \leq \cdots \leq X_{(n)}$ denote the ordered sample. The test statistic implemented here is +Constructor 00$, +with known origin zero. `lam` is a **rate**, with scale $1/\lambda$. +For unknown rate, $\widehat\lambda=1/\bar x$ and $y_i=x_i/\bar x$. + +| Classes | Accepted parameters | Fitting/calibration | +|---|---|---| +| KS D+, D− and D | Fixed `lam` | No fit; continuous fixed-null probability transform | +| Lilliefors | Empty schema | Fit rate on every sample, including every replicate | +| Other 10 generated EDF classes | Fixed `lam` or empty schema | Fixed CDF or per-sample MLE | +| Five frequency classes | Fixed `lam` or empty schema | Bind specified/fitted distribution; preserve binning | +| 31 specialized classes | Empty schema | Scale-invariant definition; no fitted parameters stored | + +Every concrete class declares its supported hypotheses. Omitted parameters +are not filled with defaults. The family base supplies no support declaration. +For fitted criteria, Exp(1) simulation is justified by positive-scale invariance, +not by treating the fitted sample as independent uniform observations. + +`EqualProbabilityBins()` uses a sample-size-dependent count. Explicit counts, +count rules and binning strategies belong to the criterion configuration. +Fitted-rate frequency calibration with an arbitrary fixed set of raw-unit +edges is not scale invariant; the built-in helper rejects it. A known-rate +criterion may use those edges because simulation uses that specified rate. + +## Formula inventory: every concrete class + +The linked pages contain full class names, short codes, parameter settings, +input limits, examples and scientific links. Notation: $x_{(i)}$ are ordered +observations, $y_i=x_i/\bar x$, $u_i=F(x_{(i)})$, $r_i=i-1/2$, +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$ and +$d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ with $x_{(0)}=0$. +$O_j$ and $E_j=np_j>0$ are aligned cell counts. + +### Edf definitions + +| Criterion | Implemented scalar | API rejection | Scientific source | +|---|---|---|---| +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_exp_criterion.md) | $D^+=\max_i(i/n-u_i)$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_exp_criterion.md) | $D^-=\max_i(u_i-(i-1)/n)$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [Kolmogorov–Smirnov](kolmogorov_smirnov_exp_criterion.md) | $D=\max(D^+,D^-)$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [Lilliefors exponential](lilliefors_exp_criterion.md) | $D=\max(D^+,D^-),\quad u_i=1-e^{-x_{(i)}/\bar x}$ | right tail | [Lilliefors (1969)](https://doi.org/10.1080/01621459.1969.10500983) | +| [Anderson–Darling](anderson_darling_exp_criterion.md) | $-n-\frac1n\sum_i(2i-1)[\log u_i+\log(1-u_{n+1-i})]$ | right tail | [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437) | +| [Cramér–von Mises](cvm_exp_criterion.md) | $W^2=\frac1{12n}+\sum_i[u_i-(i-1/2)/n]^2$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [Liao–Shimokawa](liao_shimokawa_exp_criterion.md) | $\frac1{\sqrt n}\sum_i\frac{\max(i/n-u_i,u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}}$ | right tail | [Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965) — original models differ; recalibration required | +| [Watson](watson_exp_criterion.md) | $U^2=W^2-n(\bar u-1/2)^2$ | right tail | [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109) | +| [Kuiper](kuiper_exp_criterion.md) | $V=D^++D^-$ | right tail | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60) | +| [Scaled Kuiper](kuiper_scaled_exp_criterion.md) | $V_s=\sqrt n(D^++D^-)$ | right tail | [Lemeshko et al. (2014)](https://doi.org/10.3103/S875669901401004X) | +| [Corrected Kuiper](kuiper_corrected_exp_criterion.md) | $V_c=(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-)$ | right tail | [Lemeshko et al. (2014)](https://doi.org/10.3103/S875669901401004X) | +| [Zhang Z_K](zhang_k_exp_criterion.md) | $\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right],\quad r_i=i-1/2$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [Zhang Z_A](zhang_a_exp_criterion.md) | $-\sum_i\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right]$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [Zhang Z_C](zhang_c_exp_criterion.md) | $\sum_i\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2$ | right tail | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | + +### Frequency definitions + +| Criterion | Implemented scalar | API rejection | Scientific source | +|---|---|---|---| +| [Pearson chi-square](pearson_exp_criterion.md) | $\sum_j(O_j-E_j)^2/E_j$ | right tail | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [Freeman–Tukey](freeman_tukey_exp_criterion.md) | $4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2$ | right tail | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [Modified log-likelihood](modified_log_likelihood_exp_criterion.md) | $2\sum_j E_j\log(E_j/O_j)$ | right tail | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [Neyman chi-square](neyman_chi2_exp_criterion.md) | $\sum_j(O_j-E_j)^2/O_j$ | right tail | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [Cressie–Read](cressie_read_exp_criterion.md) | $\frac95\sum_j O_j[(O_j/E_j)^{2/3}-1]$ | right tail | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | + +### Specialized definitions + +| Criterion | Implemented scalar | API rejection | Scientific source | +|---|---|---|---| +| [Epps–Pulley](epps_pulley_exp_criterion.md) | $\sqrt{48n}\left(n^{-1}\sum_i e^{-y_i}-\tfrac12\right)$ | both tails | [Epps and Pulley (1986)](https://doi.org/10.1111/j.2517-6161.1986.tb01403.x) | +| [Ahsanullah](ahsanullah_exp_criterion.md) | $n^{-3}\sum_{i,j,k}\left[\mathbf1\{\vert x_i-x_j\vert b x_j\}$ | right tail | [Deshpande (1983)](https://doi.org/10.1093/biomet/70.2.514) | +| [Epstein spacing log contrast](epstein_exp_criterion.md) | $\frac{2n\{\log\bar d-n^{-1}\sum_i\log d_i\}}{1+(n+1)/(6n)}$ | right tail | [Epstein (1960)](https://doi.org/10.1080/00401706.1960.10489892) — finite-sample correction not verified | +| [Frozini EDF distance](frozini_exp_criterion.md) | $n^{-1/2}\sum_i\left\vert u_i-\frac{i-1/2}{n}\right\vert $ | right tail | [Henze and Meintanis (2005)](https://doi.org/10.1007/s001840400322) — review; original attribution not verified | +| [Gini](gini_exp_criterion.md) | $\frac{\sum_{ix_j+x_k\}}{n(n-1)(n-2)}$ | left tail | [Hollander and Proschan (1972)](https://doi.org/10.1214/aoms/1177692466) — lower-tail NBU direction | +| [Kimber–Michael](kimber_michael_exp_criterion.md) | $\max_i\left\vert A(u_i)-A((i-1/2)/n)\right\vert ,\quad A(u)=2\arcsin(\sqrt u)/\pi$ | right tail | [Kimber (1985)](https://doi.org/10.1093/biomet/72.3.661) | +| [Kochar exponential scores](kochar_exp_criterion.md) | $\sqrt{108n/17}\frac{\sum_i J(i/(n+1))x_{(i)}}{\sum_i x_i},\quad J(u)=2(1-u)[1-\log(1-u)]-1$ | right tail | [Kochar (1985)](https://doi.org/10.1080/03610928508828919) | +| [Lorenz ordinate](lorenz_exp_criterion.md) | $\frac{\sum_{i=1}^{\lfloor np\rfloor}x_{(i)}}{\sum_i x_i}$ | right tail | [Gail and Gastwirth (1978)](https://doi.org/10.1080/01621459.1978.10480100) | +| [Moran log-mean contrast](moran_exp_criterion.md) | $\gamma+n^{-1}\sum_i\log y_i$ | both tails | [Mimoto and Zitikis (2008)](https://doi.org/10.14490/jjss.38.187) | +| [Pietra](pietra_exp_criterion.md) | $\frac{1}{2n}\sum_i\vert y_i-1\vert $ | both tails | [Gail and Gastwirth (1978)](https://doi.org/10.1080/01621459.1978.10480100) — inequality context; exact attribution not verified | +| [Shapiro–Wilk exponential W](shapiro_wilk_exp_criterion.md) | $\frac{n(\bar x-x_{(1)})^2}{(n-1)\sum_i(x_i-\bar x)^2}$ | both tails | [Shapiro and Wilk (1972)](https://doi.org/10.1080/00401706.1972.10488921); [Spinelli and Stephens (1987)](https://www.stat.cmu.edu/technometrics/80-89/VOL-29-04/v2904471.pdf) | +| [Rossberg integral contrast](rossberg_exp_criterion.md) | $n^{-1}\sum_k[H_n(x_k)-G_n(x_k)]$ | right tail | [Volkova (2009/2010)](https://doi.org/10.1007/s10958-010-9934-9) — finite-sample convention qualified below | +| [WE](we_exp_criterion.md) | $\frac{\sum_i(x_i-\bar x)^2}{(\sum_i x_i)^2}$ | right tail | [Ascher (1990)](https://doi.org/10.1080/03610929008830292); [later formula](https://doi.org/10.1080/03610918.2021.2009868) — published normalization; historical tail not verified | +| [Wong–Wong extremal quotient](wong_wong_exp_criterion.md) | $x_{(n)}/x_{(1)}$ | right tail | [Wong and Wong (1979)](https://doi.org/10.1007/BF01893465) | +| [Greenwood](greenwood_exp_criterion.md) | $G=\frac{\sum_i x_i^2}{(\sum_i x_i)^2}$ | both tails | [Arendarczyk, Kozubowski and Panorska (2022)](https://doi.org/10.1111/sjos.12520) | +| [Baringhaus–Henze empirical Laplace transform](baringhaus_henze_elt_exp_criterion.md) | $n\int_0^\infty[(1+t)L_n^\prime(t)+L_n(t)]^2e^{-at}\,dt,\quad L_n(t)=n^{-1}\sum_i e^{-ty_i}$ | right tail | [Baringhaus and Henze (1991)](https://www.ism.ac.jp/editsec/aism/pdf/043_3_0551.pdf) | +| [Baringhaus–Henze mean residual life](baringhaus_henze_bhc_exp_criterion.md) | $n\int_0^\infty\left[n^{-1}\sum_i(y_i-t-1)\mathbf1\{y_i>t\}\right]^2e^{-at}\,dt$ | right tail | [Ebner (2023)](https://arxiv.org/abs/2209.05153); [Baringhaus and Henze (2008)](https://doi.org/10.1016/j.spl.2007.09.060) | +| [Graph edge count](graph_edges_number_exp_criterion.md) | $\vert E\vert $ | both tails | [Dettmann and Georgiou (2016)](https://arxiv.org/abs/1411.3617) — graph background only; exact test has no identified source | +| [Graph maximum degree](graph_max_degree_exp_criterion.md) | $\max_v\deg(v)$ | both tails | [Dettmann and Georgiou (2016)](https://arxiv.org/abs/1411.3617) — graph background only; exact test has no identified source | +| [Graph average degree](graph_average_degree_exp_criterion.md) | $2\vert E\vert /n$ | both tails | [Dettmann and Georgiou (2016)](https://arxiv.org/abs/1411.3617) — graph background only; exact test has no identified source | +| [Graph connected components](graph_connected_components_exp_criterion.md) | $\#\{\text{connected components}\}$ | both tails | [Dettmann and Georgiou (2016)](https://arxiv.org/abs/1411.3617) — graph background only; exact test has no identified source | +| [Graph clique number](graph_clique_number_exp_criterion.md) | $\omega(G)$ | both tails | [Dettmann and Georgiou (2016)](https://arxiv.org/abs/1411.3617) — graph background only; exact test has no identified source | +| [Graph independence number](graph_independence_number_exp_criterion.md) | $\alpha(G)$ | both tails | [Dettmann and Georgiou (2016)](https://arxiv.org/abs/1411.3617) — graph background only; exact test has no identified source | + +For Rossberg, $H_n(t)$ averages the indicator that the first spacing of a +three-observation subsample is below $t$; $G_n(t)$ averages the indicator that +a two-observation minimum is below $t$. Subsamples contain distinct indices, +but the final empirical integral reuses all original observations. Ahsanullah, +in contrast, deliberately uses a V-statistic including repeated indices. + +## Independent derivations and numerical references + +### EDF and frequency definitions + +KS and its one-sided variants were checked against SciPy's continuous fixed-CDF +test; Lilliefors was checked against KS evaluated at the fitted exponential CDF. +Cramér–von Mises was compared with SciPy and with integration of the squared +step-CDF discrepancy. Anderson–Darling and Watson were independently integrated +on each probability interval, including both support tails. Kuiper and its two +multipliers were compared with independently computed one-sided deviations. + +The shared Zhang definitions match equations (3.1)–(3.3) of +[Zhang (2002)](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf); independent +high-precision fixtures and direct scalar logarithms check rank offsets and +normalization. Exponential log-survival is $-\lambda x$, avoiding loss of the +upper tail when the CDF rounds to one. Liao–Shimokawa's functional is checked +by direct summation, but its original estimated-Weibull critical values do not +apply to fitted exponential observations. Finite-sample Kuiper multipliers do +not constitute an exact fitted-null p-value. + +For frequencies, the five kernels agree with the power-divergence family at +parameters $1,-1/2,-1,-2,2/3$, independently evaluated by SciPy from histogram +counts. Empty-cell contributions are, respectively, $E_j$, $4E_j$, $+\infty$, +$+\infty$, and zero. Known-rate Pearson has an asymptotic chi-square(k-1) limit +under suitable cell conditions; fitting by ungrouped MLE with moving cells does +not justify automatically subtracting another degree of freedom. + +### Scores, moments and spacings + +Differentiating the profiled Weibull log likelihood at shape 1 gives +$n+\sum_i(1-y_i)\log y_i$, verifying the Cox–Oakes sign and factor. The test +compares that analytic score with a central finite difference of the likelihood. +Its raw value is not standardized; a conventional asymptotic standardization +multiplies it by $\sqrt{6/n}/\pi$. + +Atkinson uses an absolute power-mean contrast. The accepted computational +range $p>-1$ is broader than the usual finite-variance asymptotic range +$p>-1/2$. Near zero its geometric-mean limit is used; $p=1$ is excluded as +degenerate. Normal calibration of an unstandardized raw value is unjustified. +The [Mimoto–Zitikis paper](https://www.jstage.jst.go.jp/article/jjss/38/2/38_2_187/_article) +is linked for provenance; full-text verification was unavailable in this audit. + +Under an exponential sample, $P_i=X_i/\sum_jX_j$ has Dirichlet(1,...,1) +distribution. Direct Dirichlet moment calculations give + +$$ +E(G)=\frac2{n+1},\qquad +\operatorname{Var}(G)=\frac{4(n-1)}{(n+1)^2(n+2)(n+3)}. +$$ + +They also give Moran's exact mean $\log n-\psi(n)$ and variance +$\psi_1(1)/n-\psi_1(n)$ for the centered value used here. Integrating a +Beta(1,n-1) marginal gives the exact Pietra mean $(1-1/n)^n$, rather than its +asymptotic center $1/e$. Gini uses denominator $n-1$, with exact null mean +$1/2$ and variance $1/[12(n-1)]$. WE is exactly + +$$ +WE=G-\frac1n. +$$ + +For normalized ordered spacings, independence and exponentiality imply that +sums over disjoint groups are independent gamma variables. Their ratios of +means yield F(2r,2(n-r)) for Gnedenko and F(4r,2(n-2r)) for Harris. These +identities validate the scalar ratios independently of historical attribution. +Both criteria now use `TwoSidedAlternative`, with equal probabilities in the +lower and upper tails. Regression checks construct samples from prescribed +spacings and verify rejection for both small and large ratios, and acceptance +for a ratio of one, through Monte Carlo calibration. Epstein's logarithmic spacing +contrast and correction were checked algebraically, but its attribution and +purported finite-sample approximation are not certified. + +### Characterizations, direction and graph limitations + +For independent continuous observations, the raw Hollander–Proschan statistic +estimates $P(X>Y+Z)$. Under NBU, +$\bar F(y+z)\le\bar F(y)\bar F(z)$, hence + +$$ +P(X>Y+Z)\le\left[\int\bar F(y)\,dF(y)\right]^2=\frac14. +$$ + +Thus the original [NBU procedure](https://doi.org/10.1214/aoms/1177692466) +rejects small values. The API now uses `LeftAlternative`. Uniform(1,2) +supplies a concrete regression case: its statistic is zero. A deterministic +sample in (1,2) checks the scalar and rejection through lower-tail Monte Carlo +calibration. The former upper-tail rule missed this NBU departure. +Deshpande's raw expectation $1/(1+b)$ follows by integrating +$P(X>bY)$; its upper-tail choice is compatible with the IFRA alternative. + +Ahsanullah and Rossberg were checked against exhaustive indicator enumeration, +including repeated-index versus distinct-index conventions and strict ties. +Characterization identities alone do not establish consistency of a particular +signed integral against every alternative. Their exact original finite-sample +conventions remain qualified, rather than assigning unverified normal laws. + +The six graph algorithms were compared with explicit NetworkX graphs, maximal +cliques and complement cliques. Their proximity threshold is data range/10. +Translation leaves every edge unchanged. Shapiro–Wilk W also cancels a shift +in both numerator and denominator, as discussed by +[Spinelli and Stephens (1987), §3](https://www.stat.cmu.edu/technometrics/80-89/VOL-29-04/v2904471.pdf). +Neither construction can consistently detect a positive location shift while +the declared origin is fixed at zero. The graph reference on each page is +background, not evidence for this exact exponentiality procedure. + +### Transform criteria + +The ELT definition was compared with the normalized differential-equation +construction in [Baringhaus and Henze (1991), pp. 552–553](https://www.ism.ac.jp/editsec/aism/pdf/043_3_0551.pdf). +Independent numerical quadrature verifies the implemented pair sum. For the +mean-residual-life family, direct integration and the independent pair +representation in [Ebner (2023), equations (4)–(5)](https://arxiv.org/html/2209.05153v2) +verify the piecewise implementation. Both keep tuning fixed; they refit the +mean for every sample. The accepted $00$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +2\sum_j E_j\log(E_j/O_j) +$$ + +Power-divergence parameter -1; an empty observed cell gives positive infinity, retained in Monte Carlo ranks. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +The `binning` keyword accepts a `BinningStrategy`. Default +`EqualProbabilityBins()` chooses the count from sample size; it is not fixed +at five. With unknown rate, built-in Monte Carlo requires this strategy; +other bins need external calibration at an explicit rate. Known-rate Pearson +has an asymptotic chi-square(k-1) law with suitable expected counts. After +fitting from ungrouped observations and moving bins, chi-square(k-2) is not +asserted. Empty-cell infinities are valid outcomes for Neyman and modified +log-likelihood; ties at infinity make rank calibration conservative. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + ModifiedLogLikelihoodExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = ModifiedLogLikelihoodExponentialityGofStatistic( + E.DEFAULT.parse({}), binning=EqualProbabilityBins(count=4) +) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Cressie and Read (1984), Multinomial goodness-of-fit tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/moran_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/moran_exp_criterion.md index ab476620..9b9adbaa 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/moran_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/moran_exp_criterion.md @@ -1,75 +1,61 @@ -# Moran test for exponentiality +# Moran log-mean contrast exponentiality criterion -## Description -Performs Moran test for the composite hypothesis of exponentiality, see e.g. Moran (1951). -The Moran test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by using a logarithmic ratio of the geometric mean to the arithmetic mean. +`MoranExponentialityGofStatistic` — short code `MN`; both tails. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Moran statistic is scale invariant because it is calculated from the normalized observations $X_i/\overline{X}$. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Moran test statistic is based on a logarithmic moment identity for the exponential distribution. If the data are exponential, then the expected value of $\log(X/\mu)$ is $-\gamma$, where $\gamma$ is the Euler-Mascheroni constant. +## Hypothesis and formula -Calculate the Test Statistic: The observations are divided by the sample mean, their logarithms are averaged, and the Euler-Mascheroni constant is added. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes strictly positive lifetime-type observations because logarithms are used. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic can be sensitive to rounding, truncation, or very small observations. +$$ +\gamma+n^{-1}\sum_i\log y_i +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MoranExponentialityGofStatistic, -) - - -test_statistic = MoranExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Moran test is a test for the composite hypothesis of exponentiality. The test statistic implemented here is - -$$ MN_n = \gamma + \frac{1}{n}\sum_{i=1}^{n}\log\left(\frac{X_i}{\overline{X}}\right), $$ - -where $n$ is the sample size, $\overline{X}$ is the sample mean, and $\gamma$ is the Euler-Mascheroni constant. +Signed, unstandardized contrast, both tails. Exact null mean gamma+digamma(1)-digamma(n)+log(n); variance trigamma(1)/n-trigamma(n). Zero observations give negative infinity. Do not treat the raw statistic as standard normal. -Equivalently, using the geometric mean $G_n=(\prod_{i=1}^{n}X_i)^{1/n}$, +## Input and calibration -$$ MN_n = \gamma + \log\left(\frac{G_n}{\overline{X}}\right). $$ +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -Under exponentiality, +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ \sqrt{n}MN_n \xrightarrow{d} N\left(0,\frac{\pi^2}{6}-1\right). $$ - -Large values of $MN_n$ indicate larger deviations from the exponential model in the direction used by the implemented right-sided alternative. - -## Author(s) -Lev Golofastov - -## References -Moran, P.A.P. (1951): The random division of an interval - Part II. - Journal of the Royal Statistical Society. Series B (Methodological), vol. 13, pp. 147-150. - -Tchirina, A.V. (2005): Bahadur efficiency and local optimality of a test for exponentiality based on the Moran statistics. - Journal of Mathematical Sciences, vol. 127, no. 1, pp. 1812-1819. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( MoranExponentialityGofStatistic, ) - -test_statistic = MoranExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = MoranExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Mimoto and Zitikis (2008), The Atkinson index, the Moran statistic, and testing exponentiality](https://doi.org/10.14490/jjss.38.187). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/neyman_chi2_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/neyman_chi2_exp_criterion.md new file mode 100644 index 00000000..68aab484 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/neyman_chi2_exp_criterion.md @@ -0,0 +1,73 @@ +# Neyman chi-square exponentiality criterion + +`NeymanChi2ExponentialityGofStatistic` — short code `CHI2_NEYMAN`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\sum_j(O_j-E_j)^2/O_j +$$ + +Power-divergence parameter -2; an empty observed cell gives positive infinity, retained in Monte Carlo ranks. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +The `binning` keyword accepts a `BinningStrategy`. Default +`EqualProbabilityBins()` chooses the count from sample size; it is not fixed +at five. With unknown rate, built-in Monte Carlo requires this strategy; +other bins need external calibration at an explicit rate. Known-rate Pearson +has an asymptotic chi-square(k-1) law with suitable expected counts. After +fitting from ungrouped observations and moving bins, chi-square(k-2) is not +asserted. Empty-cell infinities are valid outcomes for Neyman and modified +log-likelihood; ties at infinity make rank calibration conservative. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + NeymanChi2ExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = NeymanChi2ExponentialityGofStatistic( + E.DEFAULT.parse({}), binning=EqualProbabilityBins(count=4) +) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Cressie and Read (1984), Multinomial goodness-of-fit tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/pearson_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/pearson_exp_criterion.md new file mode 100644 index 00000000..32311f37 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/pearson_exp_criterion.md @@ -0,0 +1,73 @@ +# Pearson chi-square exponentiality criterion + +`Chi2PearsonExponentialityGofStatistic` — short code `CHI2_PEARSON`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\sum_j(O_j-E_j)^2/E_j +$$ + +Power-divergence parameter 1. Code CHI2_PEARSON replaces CHI2. Use binning=EqualProbabilityBins(count=5) to reproduce the old five-cell setting. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +The `binning` keyword accepts a `BinningStrategy`. Default +`EqualProbabilityBins()` chooses the count from sample size; it is not fixed +at five. With unknown rate, built-in Monte Carlo requires this strategy; +other bins need external calibration at an explicit rate. Known-rate Pearson +has an asymptotic chi-square(k-1) law with suitable expected counts. After +fitting from ungrouped observations and moving bins, chi-square(k-2) is not +asserted. Empty-cell infinities are valid outcomes for Neyman and modified +log-likelihood; ties at infinity make rank calibration conservative. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + Chi2PearsonExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = Chi2PearsonExponentialityGofStatistic( + E.DEFAULT.parse({}), binning=EqualProbabilityBins(count=4) +) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Cressie and Read (1984), Multinomial goodness-of-fit tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/pietra_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/pietra_exp_criterion.md index 166df21b..c6e7faaa 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/pietra_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/pietra_exp_criterion.md @@ -1,73 +1,61 @@ -# Test for exponentiality based on the Pietra statistic +# Pietra exponentiality criterion -## Description -Performs a test for the composite hypothesis of exponentiality based on the Pietra statistic, see e.g. Ascher (1990). -The Pietra test is a statistical goodness-of-fit test used to assess whether a given sample of data is consistent with an exponential distribution. This test is based on the Pietra index, also known as half the relative mean absolute deviation. +`PietraExponentialityGofStatistic` — short code `PT`; both tails. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Pietra statistic is scale invariant because it divides the mean absolute deviation from the sample mean by the sample mean. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Pietra test statistic is based on the average absolute deviation of observations from the sample mean. Under exponentiality, the corresponding population quantity has a fixed value that does not depend on the unknown scale parameter. +## Hypothesis and formula -Calculate the Test Statistic: The sample mean is calculated, absolute deviations from that mean are summed, and the result is normalized by twice the sample size and the sample mean. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic is a single dispersion measure, so it may be less sensitive to departures that do not strongly change relative mean absolute deviation. +$$ +\frac{1}{2n}\sum_i|y_i-1| +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - PietraExponentialityGofStatistic, -) - - -test_statistic = PietraExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Pietra test is a test for the composite hypothesis of exponentiality. The test statistic implemented here is - -$$ PT_n = \frac{\sum_{i=1}^{n}|X_i-\overline{X}|}{2n\overline{X}}, $$ +Both tails. Exact finite-n null mean (1-1/n)^n, converging to 1/e; the identity follows by integrating a Beta(1,n-1) marginal of normalized observations. The article is inequality/Lorenz context; exact attribution of this convention to a named published test remains qualified. -where $n$ is the sample size and $\overline{X}$ is the sample mean. +## Input and calibration -Equivalently, $PT_n$ is the sample mean absolute deviation about the mean divided by twice the sample mean. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -For an exponential distribution, +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -$$ PT = \frac{1}{e}. $$ - -The implemented test uses a two-sided alternative, so values of $PT_n$ that are too small or too large relative to the exponential reference distribution are evidence against exponentiality. - -## Author(s) -Lev Golofastov - -## References -Pietra, G. (1915): Delle relazioni tra gli indici di variabilita (Nota I). - Atti del Reale Istituto Veneto di Scienze, Lettere ed Arti, vol. 74, pp. 775-792. - -Ascher, S. (1990): A survey of tests for exponentiality. - Communications in Statistics - Theory and Methods, vol. 19, pp. 1811-1825. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( PietraExponentialityGofStatistic, ) - -test_statistic = PietraExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = PietraExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Gail and Gastwirth (1978), A scale-free goodness-of-fit test for the exponential distribution based on the Lorenz curve](https://doi.org/10.1080/01621459.1978.10480100). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/rossberg_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/rossberg_exp_criterion.md index 0a668af9..82a0bb09 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/rossberg_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/rossberg_exp_criterion.md @@ -1,79 +1,61 @@ -# Test for exponentiality based on Rossberg characterization +# Rossberg integral contrast exponentiality criterion -## Description -Performs a test for the composite hypothesis of exponentiality based on Rossberg characterization, see e.g. Rossberg (1972) and Volkova (2010). -The Rossberg test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by comparing empirical distributions motivated by a characterization involving differences of order statistics. +`RossbergExponentialityGofStatistic` — short code `RS`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Rossberg statistic is scale invariant because the characterization uses comparisons between sample observations and differences of order statistics. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Rossberg test statistic is based on a characterization of the exponential distribution using order statistics. It compares the empirical distribution of the difference between the first two order statistics in triples with the empirical distribution of the minimum of pairs. +## Hypothesis and formula -Calculate the Test Statistic: For each observation, count the proportion of sample triples for which the second order statistic minus the first order statistic is smaller than that observation, subtract the corresponding proportion of sample pairs for which the pair minimum is smaller than that observation, and average the differences over the sample. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The implementation uses nested loops over triples and pairs, so computation can be expensive for large samples. +$$ +n^{-1}\sum_k[H_n(x_k)-G_n(x_k)] +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - RossbergExponentialityGofStatistic, -) - - -test_statistic = RossbergExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Rossberg test is a test for the composite hypothesis of exponentiality. Let $F_n$ be the empirical distribution function. Define - -$$ H_n(t) = {n \choose 3}^{-1}\sum_{1 \leq i0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic requires at least two distinct observations because the denominator is based on the centered sum of squares. +$$ +\frac{n(\bar x-x_{(1)})^2}{(n-1)\sum_i(x_i-\bar x)^2} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ShapiroWilkExponentialityGofStatistic, -) - - -test_statistic = ShapiroWilkExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Shapiro-Wilk test is a test for the composite hypothesis of exponentiality. Let $X_{(1)}$ denote the sample minimum. The test statistic implemented here is - -$$ SW_n = \frac{n(\overline{X}-X_{(1)})^2}{(n-1)\sum_{i=1}^{n}(X_i-\overline{X})^2}, $$ +n>=3 and nonconstant observations; both tails. Translation invariance means that this statistic cannot detect a positive shift of an exponential distribution, despite the zero-origin input model. This is not the normality Shapiro–Wilk statistic. -where $n$ is the sample size and $\overline{X}$ is the sample mean. +## Input and calibration -The statistic is scale invariant and is bounded between its lower endpoint and 1 for nonconstant samples. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -The implementation uses a left-sided alternative, so small values of $SW_n$ indicate larger deviations from the exponential model in the direction used by this statistic. +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -## Author(s) -Lev Golofastov - -## References -Shapiro, S.S. and Wilk, M.B. (1972): An analysis of variance test for the exponential distribution (complete samples). - Technometrics, vol. 14, no. 2, pp. 355-370. https://doi.org/10.1080/00401706.1972.10488921 - -Shapiro, S.S. and Wilk, M.B. (1965): An analysis of variance test for normality (complete samples). - Biometrika, vol. 52, no. 3/4, pp. 591-611. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( ShapiroWilkExponentialityGofStatistic, ) - -test_statistic = ShapiroWilkExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = ShapiroWilkExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Shapiro and Wilk (1972), An analysis of variance test for the exponential distribution (complete samples)](https://doi.org/10.1080/00401706.1972.10488921). + +[Spinelli and Stephens (1987), Tests for exponentiality when origin and scale parameters are unknown, §3](https://www.stat.cmu.edu/technometrics/80-89/VOL-29-04/v2904471.pdf). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/watson_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/watson_exp_criterion.md new file mode 100644 index 00000000..6d384785 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/watson_exp_criterion.md @@ -0,0 +1,61 @@ +# Watson exponentiality criterion + +`WatsonExponentialityGofStatistic` — short code `W`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +U^2=W^2-n(\bar u-1/2)^2 +$$ + +Short code W is retained. This is a probability-scale application of the circular EDF functional; rate fitting requires its own calibration. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + WatsonExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = WatsonExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Watson (1961), Goodness-of-fit tests on a circle](https://doi.org/10.1093/biomet/48.1-2.109). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/we_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/we_exp_criterion.md index 28c9927e..eed48708 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/we_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/we_exp_criterion.md @@ -1,75 +1,78 @@ -# WE test for exponentiality +# WE exponentiality criterion -## Description -Performs WE test for the composite hypothesis of exponentiality, see e.g. Ascher (1990). -The WE test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is based on the squared coefficient of variation, a scale-free measure of dispersion that has a characteristic value for an exponential distribution. +`WeExponentialityGofStatistic` — short code `WE`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The WE statistic is scale invariant because it is calculated from the ratio of the sample variance to the squared sample mean. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The WE test statistic is based on the coefficient of variation. For an exponential distribution, the population coefficient of variation is equal to one, so departures from this value indicate departures from exponentiality. +## Hypothesis and formula -Calculate the Test Statistic: The sample mean and population-form sample variance are calculated, the variance is divided by the squared mean, and the result is multiplied by the factor `(n - 1) / n**2`. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes nonnegative lifetime-type observations. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The coefficient of variation can be strongly affected by outlying observations and by samples with a small mean. +$$ +\frac{\sum_i(x_i-\bar x)^2}{(\sum_i x_i)^2} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WeExponentialityGofStatistic, -) - - -test_statistic = WeExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The WE test is a test for the composite hypothesis of exponentiality. The test statistic implemented here is - -$$ WE_n = \frac{(n-1)\widehat{\sigma}_n^2}{n^2\overline{X}^2}, $$ +WE is a published test name associated with Ascher (1990), not an invented local name. +The later rounding study cited below gives the definition -where $n$ is the sample size, $\overline{X}$ is the sample mean, and +$$ +WE_{\mathrm{published}}=\frac{\sum_i(x_i-\bar x)^2}{(\sum_i x_i)^2}=G-\frac1n. +$$ -$$ \widehat{\sigma}_n^2 = \frac{1}{n}\sum_{i=1}^{n}(X_i-\overline{X})^2. $$ +The implementation now returns this published formula. The former extra +factor $(n-1)/n$ has been removed. WE is an increasing affine function of +Greenwood for fixed sample size, but this +class currently uses the right tail while Greenwood uses both tails. +The full text of Ascher was not accessible during this follow-up; the formula +comparison uses the later article, which explicitly cites Ascher for WE. +The historical rejection-tail convention has not been verified here. -Equivalently, +## Input and calibration -$$ WE_n = \frac{n-1}{n^2}CV_n^2, $$ +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -where $CV_n^2$ is the squared sample coefficient of variation calculated with the population-form variance. +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -Large values of $WE_n$ indicate larger deviations from the exponential model in the direction used by the implemented right-sided alternative. +## Runnable example -## Author(s) -Lev Golofastov +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + WeExponentialityGofStatistic, +) -## References -Ascher, S. (1990): A survey of tests for exponentiality. - Communications in Statistics - Theory and Methods, vol. 19, pp. 1811-1825. +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = WeExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` -Holland, B. (1989): Monte Carlo simulation of the power of a test for the exponential distribution of survival times. - Computer Methods and Programs in Biomedicine, vol. 29, no. 4, pp. 245-250. https://doi.org/10.1016/0169-2607(89)90109-0 +## Scientific references and verification status -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. +[Ascher (1990), A survey of tests for exponentiality, 19(5), 1811–1825](https://doi.org/10.1080/03610929008830292). -## Examples +[On sensitivity of exponentiality tests to data rounding: a Monte Carlo simulation study](https://doi.org/10.1080/03610918.2021.2009868). -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WeExponentialityGofStatistic, -) +[Arendarczyk, Kozubowski and Panorska (2022), The Greenwood statistic, stochastic dominance, clustering and heavy tails](https://doi.org/10.1111/sjos.12520). - -test_statistic = WeExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/wong_wong_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/wong_wong_exp_criterion.md index a62cf0c1..c6d57ead 100644 --- a/docs/criteria/goodness-of-fit/exponentiality/wong_wong_exp_criterion.md +++ b/docs/criteria/goodness-of-fit/exponentiality/wong_wong_exp_criterion.md @@ -1,70 +1,61 @@ -# Test for exponentiality of Wong and Wong +# Wong–Wong extremal quotient exponentiality criterion -## Description -Performs Wong and Wong test for the composite hypothesis of exponentiality, see e.g. Wong and Wong (1979). -The Wong and Wong test is a statistical hypothesis test used to assess the composite hypothesis of exponentiality. This test is designed to determine whether a given sample of data is consistent with an exponential distribution by using the extremal quotient of the sample. +`WongWongExponentialityGofStatistic` — short code `WW`; right tail. -Composite Hypothesis of Exponentiality -The composite hypothesis of exponentiality refers to the null hypothesis that the data comes from an exponential distribution with an unspecified rate parameter -lambda. The Wong and Wong statistic is scale invariant because it is calculated as a ratio of the largest and smallest order statistics. +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) -Test Statistic -The Wong and Wong test statistic is based on the extremal quotient. It compares the maximum observation with the minimum observation and uses the resulting ratio as evidence about departure from exponentiality. +## Hypothesis and formula -Calculate the Test Statistic: The smallest and largest observations are found, and the largest observation is divided by the smallest observation. +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Unknown rate only: pass `E.DEFAULT.parse({})`. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. -Limitations -The test assumes strictly positive lifetime-type observations because the sample minimum is used as the denominator. +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. -The statistic depends only on the two extreme observations and can be sensitive to outliers or measurement errors at the sample extremes. +$$ +x_{(n)}/x_{(1)} +$$ -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WongWongExponentialityGofStatistic, -) - - -test_statistic = WongWongExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) -``` - -## Arguments -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details - -The Wong and Wong test is a test for the composite hypothesis of exponentiality. Let -$X_{(1)} \leq \cdots \leq X_{(n)}$ denote the ordered sample. The test statistic implemented here is +Raw ratio, without logarithm; zero minimum gives positive infinity. The implementation uses the upper tail only. The source establishes an extremal-quotient procedure; equivalence of the local tail rule to the original procedure was not verified. -$$ WW_n = \frac{X_{(n)}}{X_{(1)}}. $$ +## Input and calibration -Here $n$ is the sample size, $X_{(1)}$ is the sample minimum, and $X_{(n)}$ is the sample maximum. +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. -The statistic is scale free because multiplying all observations by the same positive constant leaves $WW_n$ unchanged. +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. -Large values of $WW_n$ indicate larger deviations from the exponential model in the direction used by the implemented right-sided alternative. - -## Author(s) -Lev Golofastov - -## References -Wong, P.G. and Wong, S.P. (1979): An extremal quotient test for exponential distributions. - Metrika, vol. 26, pp. 1-4. - -Ascher, S. (1990): A survey of tests for exponentiality. - Communications in Statistics - Theory and Methods, vol. 19, pp. 1811-1825. - -Henze, N. and Meintanis, S.G. (2005): Recent and classical tests for exponentiality: a partial review with comparisons. - Metrika, vol. 61, pp. 29-45. - -## Examples +## Runnable example ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( WongWongExponentialityGofStatistic, ) - -test_statistic = WongWongExponentialityGofStatistic() -statistic_result = test_statistic.execute_statistic([1, 2, 3, 4, 5, 6, 7]) -print(statistic_result) +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = WongWongExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) ``` + +## Scientific references and verification status + +[Wong and Wong (1979), An extremal quotient test for exponential distributions](https://doi.org/10.1007/BF01893465). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/zhang_a_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/zhang_a_exp_criterion.md new file mode 100644 index 00000000..6fe4f856 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/zhang_a_exp_criterion.md @@ -0,0 +1,61 @@ +# Zhang Z_A exponentiality criterion + +`ZhangAExponentialityGofStatistic` — short code `ZHANG_ZA`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +-\sum_i\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right] +$$ + +Equation (3.2). Endpoints give positive infinity. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + ZhangAExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = ZhangAExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/zhang_c_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/zhang_c_exp_criterion.md new file mode 100644 index 00000000..c836a904 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/zhang_c_exp_criterion.md @@ -0,0 +1,61 @@ +# Zhang Z_C exponentiality criterion + +`ZhangCExponentialityGofStatistic` — short code `ZHANG_ZC`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\sum_i\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2 +$$ + +Equation (3.3). Endpoints give positive infinity. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + ZhangCExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = ZhangCExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiality/zhang_k_exp_criterion.md b/docs/criteria/goodness-of-fit/exponentiality/zhang_k_exp_criterion.md new file mode 100644 index 00000000..df4ea2b0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiality/zhang_k_exp_criterion.md @@ -0,0 +1,61 @@ +# Zhang Z_K exponentiality criterion + +`ZhangKExponentialityGofStatistic` — short code `ZHANG_ZK`; right tail. + +[All exponential criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and formula + +The model is $F(x)=1-\exp(-\lambda x)$ for $x\ge0$, with known origin zero and $\lambda>0$. +Fixed or unknown rate: pass `E.DEFAULT.parse({"lam": rate})` or `E.DEFAULT.parse({})`, respectively. +Omitted parameters remain unknown. Where fitting is needed, $\widehat\lambda=1/\bar x$ +is recomputed for each sample; no fitted state is retained. + +Write $y_i=x_i/\bar x$, $u_i=1-\exp(-\lambda x_{(i)})$ with the specified or +fitted rate, $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. +For spacing statistics, $d_i=(n-i+1)(x_{(i)}-x_{(i-1)})$ and $x_{(0)}=0$. +For frequency statistics, $O_j$ and $E_j=np_j>0$ are aligned counts. + +$$ +\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right],\quad r_i=i-1/2 +$$ + +Equation (3.1). Endpoints give positive infinity. Fitted exponential calibration must repeat fitting. + +## Input and calibration + +Observations must be finite, real, nonnegative and one-dimensional. Masked +observations are rejected. Fixed-rate generated criteria accept $n\ge1$; +unknown-rate EDF/frequency criteria require $n\ge2$ and positive total. +Specialized criteria may require more observations, distinct spacings or a +nonconstant sample, as stated above and in the class contract. Ties are not +silently jittered. Infinite mathematical boundary penalties are retained. + +`execute_statistic` returns a statistic, not a p-value. Use +`monte_carlo_exponential` with the same sample size and constructor settings. +It refits each simulated sample for a composite hypothesis. Rescaling to +Exp(1) is justified only for a scale-invariant statistic. A continuous-null +calibration does not model rounding, censoring or dependence. + +## Runnable example + +```python +from pysatl_criterion.distribution import ExponentialDistributionDescriptor as E +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponent import ( + ZhangKExponentialityGofStatistic, +) + +sample = [0.12, 0.30, 0.55, 0.90, 1.40, 2.10, 3.20, 4.80] +criterion = ZhangKExponentialityGofStatistic(E.DEFAULT.parse({})) +value = criterion.execute_statistic(sample) +print(value) +``` + +## Scientific references and verification status + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). + +The formula and input behavior are tested independently; that does not by +itself certify a historical name, an asymptotic approximation or published +critical values. Source qualifications above are part of this criterion's +contract. See the [audit](mathematical-validation.md) for evidence and open items. diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/anderson_darling_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/anderson_darling_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..dbac80b9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/anderson_darling_exponentiated_weibull_criterion.md @@ -0,0 +1,57 @@ +# Anderson–Darling for exponentiated Weibull + +`AndersonDarlingExponentiatedWeibullGofStatistic` + +Short code: `AD`. Full code: `AD_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1)\{\log u_i+\log(1-u_{n+1-i})\}. +$$ + +No fitted-parameter or finite-sample correction is applied. Logarithmic CDF and survival values prevent premature rounding to 0 or 1. + +An exact zero observation gives positive infinity. Finite tail penalties are retained using log probabilities when the CDF rounds to one; the statistic may still overflow when its true magnitude exceeds float64. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + AndersonDarlingExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = AndersonDarlingExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/chi2_pearson_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/chi2_pearson_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..11cb2efc --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/chi2_pearson_exponentiated_weibull_criterion.md @@ -0,0 +1,68 @@ +# Pearson chi-squared for exponentiated Weibull + +`Chi2PearsonExponentiatedWeibullGofStatistic` + +Short code: `CHI2_PEARSON`. Full code: `CHI2_PEARSON_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Here $O_j$ and $E_j=np_j>0$ are observed and expected counts in exhaustive, +mutually exclusive cells, with $\sum_jO_j=\sum_jE_j=n$. +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: +$B=\min(1000,\max(2,\lceil2n^{0.4}\rceil))$, and $p_j=1/B$. +Thus the default has two cells even for a singleton sample. The old +$\lceil\sqrt n\rceil$ rule and its one-cell singleton result no longer apply. + +The example chooses three equal-probability cells explicitly. You can instead use +`ExplicitBins((0, b1, b2, float("inf")))` for fixed full-support edges; then +$p_j=F(b_{j+1})-F(b_j)$. See [binning strategies](../binning/index.md). + +$$ +X^2=\sum_{j=1}^B\frac{(O_j-E_j)^2}{E_j}. +$$ + +Power divergence at lambda=1. A zero observed count contributes E_j. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. For fixed B and sufficiently large expected counts the usual reference is chi-squared with B−1 degrees of freedom; no parameters are fitted. Small or empty cells and a sample-size-dependent B require appropriate calibration, preferably Monte Carlo. Repeat the chosen binning procedure in every replicate. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + Chi2PearsonExponentiatedWeibullGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = Chi2PearsonExponentiatedWeibullGofStatistic( + parameters, binning=EqualProbabilityBins(count=3) +) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); [full text](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/cressie_read_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/cressie_read_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..b2c38ca9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/cressie_read_exponentiated_weibull_criterion.md @@ -0,0 +1,68 @@ +# Cressie–Read for exponentiated Weibull + +`CressieReadExponentiatedWeibullGofStatistic` + +Short code: `CRESSIE_READ`. Full code: `CRESSIE_READ_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Here $O_j$ and $E_j=np_j>0$ are observed and expected counts in exhaustive, +mutually exclusive cells, with $\sum_jO_j=\sum_jE_j=n$. +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: +$B=\min(1000,\max(2,\lceil2n^{0.4}\rceil))$, and $p_j=1/B$. +Thus the default has two cells even for a singleton sample. The old +$\lceil\sqrt n\rceil$ rule and its one-cell singleton result no longer apply. + +The example chooses three equal-probability cells explicitly. You can instead use +`ExplicitBins((0, b1, b2, float("inf")))` for fixed full-support edges; then +$p_j=F(b_{j+1})-F(b_j)$. See [binning strategies](../binning/index.md). + +$$ +T_{CR}=\frac95\sum_{j=1}^B O_j\left[\left(\frac{O_j}{E_j}\right)^{2/3}-1\right]. +$$ + +Power divergence at lambda=2/3. A term with O_j=0 is defined as zero by continuity. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. For fixed B and sufficiently large expected counts the usual reference is chi-squared with B−1 degrees of freedom; no parameters are fitted. Small or empty cells and a sample-size-dependent B require appropriate calibration, preferably Monte Carlo. Repeat the chosen binning procedure in every replicate. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + CressieReadExponentiatedWeibullGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = CressieReadExponentiatedWeibullGofStatistic( + parameters, binning=EqualProbabilityBins(count=3) +) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); [full text](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/cvm_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/cvm_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..3dfc9544 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/cvm_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Cramér–von Mises for exponentiated Weibull + +`CrammerVonMisesExponentiatedWeibullGofStatistic` + +Short code: `CVM`. Full code: `CVM_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +W^2=\frac{1}{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2. +$$ + +The historical public class spelling `CrammerVonMises` is retained. Returns W², without additional scaling. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + CrammerVonMisesExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = CrammerVonMisesExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/freeman_tukey_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/freeman_tukey_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..bfff9f68 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/freeman_tukey_exponentiated_weibull_criterion.md @@ -0,0 +1,68 @@ +# Freeman–Tukey for exponentiated Weibull + +`FreemanTukeyExponentiatedWeibullGofStatistic` + +Short code: `FREEMAN_TUKEY`. Full code: `FREEMAN_TUKEY_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Here $O_j$ and $E_j=np_j>0$ are observed and expected counts in exhaustive, +mutually exclusive cells, with $\sum_jO_j=\sum_jE_j=n$. +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: +$B=\min(1000,\max(2,\lceil2n^{0.4}\rceil))$, and $p_j=1/B$. +Thus the default has two cells even for a singleton sample. The old +$\lceil\sqrt n\rceil$ rule and its one-cell singleton result no longer apply. + +The example chooses three equal-probability cells explicitly. You can instead use +`ExplicitBins((0, b1, b2, float("inf")))` for fixed full-support edges; then +$p_j=F(b_{j+1})-F(b_j)$. See [binning strategies](../binning/index.md). + +$$ +T_{FT}=4\sum_{j=1}^B(\sqrt{O_j}-\sqrt{E_j})^2. +$$ + +Power divergence at lambda=−1/2. The factor 4 is required. A zero observed count contributes 4E_j. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. For fixed B and sufficiently large expected counts the usual reference is chi-squared with B−1 degrees of freedom; no parameters are fitted. Small or empty cells and a sample-size-dependent B require appropriate calibration, preferably Monte Carlo. Repeat the chosen binning procedure in every replicate. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + FreemanTukeyExponentiatedWeibullGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = FreemanTukeyExponentiatedWeibullGofStatistic( + parameters, binning=EqualProbabilityBins(count=3) +) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); [full text](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/index.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/index.md new file mode 100644 index 00000000..32a6248c --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/index.md @@ -0,0 +1,65 @@ +# Exponentiated Weibull goodness-of-fit criteria + +All **18 criteria** below test the same fully specified continuous null. + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +See [mathematical verification](mathematical-validation.md) for sources, independent numerical checks, corrections and limitations. + +## EDF criteria (13) + +| Criterion | Public class | Short code | +|---|---|---| +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_exponentiated_weibull_criterion.md) | `KolmogorovSmirnovDPlusExponentiatedWeibullGofStatistic` | `KS_PLUS` | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_exponentiated_weibull_criterion.md) | `KolmogorovSmirnovDMinusExponentiatedWeibullGofStatistic` | `KS_MINUS` | +| [Kolmogorov–Smirnov](kolmogorov_smirnov_exponentiated_weibull_criterion.md) | `KolmogorovSmirnovExponentiatedWeibullGofStatistic` | `KS` | +| [Anderson–Darling](anderson_darling_exponentiated_weibull_criterion.md) | `AndersonDarlingExponentiatedWeibullGofStatistic` | `AD` | +| [Cramér–von Mises](cvm_exponentiated_weibull_criterion.md) | `CrammerVonMisesExponentiatedWeibullGofStatistic` | `CVM` | +| [Liao–Shimokawa](liao_shimokawa_exponentiated_weibull_criterion.md) | `LiaoShimokawaExponentiatedWeibullGofStatistic` | `LS` | +| [Watson](watson_exponentiated_weibull_criterion.md) | `WatsonExponentiatedWeibullGofStatistic` | `WATSON` | +| [Kuiper](kuiper_exponentiated_weibull_criterion.md) | `KuiperExponentiatedWeibullGofStatistic` | `KUIPER` | +| [Scaled Kuiper](kuiper_scaled_exponentiated_weibull_criterion.md) | `KuiperScaledExponentiatedWeibullGofStatistic` | `KUIPER_SCALED` | +| [Corrected Kuiper](kuiper_corrected_exponentiated_weibull_criterion.md) | `KuiperCorrectedExponentiatedWeibullGofStatistic` | `KUIPER_CORRECTED` | +| [Zhang Z_K](zhang_k_exponentiated_weibull_criterion.md) | `ZhangKExponentiatedWeibullGofStatistic` | `ZHANG_ZK` | +| [Zhang Z_A](zhang_a_exponentiated_weibull_criterion.md) | `ZhangAExponentiatedWeibullGofStatistic` | `ZHANG_ZA` | +| [Zhang Z_C](zhang_c_exponentiated_weibull_criterion.md) | `ZhangCExponentiatedWeibullGofStatistic` | `ZHANG_ZC` | + +## Frequency criteria (5) + +| Criterion | Public class | Short code | +|---|---|---| +| [Pearson chi-squared](chi2_pearson_exponentiated_weibull_criterion.md) | `Chi2PearsonExponentiatedWeibullGofStatistic` | `CHI2_PEARSON` | +| [Freeman–Tukey](freeman_tukey_exponentiated_weibull_criterion.md) | `FreemanTukeyExponentiatedWeibullGofStatistic` | `FREEMAN_TUKEY` | +| [Modified log-likelihood](modified_log_likelihood_exponentiated_weibull_criterion.md) | `ModifiedLogLikelihoodExponentiatedWeibullGofStatistic` | `MODIFIED_LOG_LIKELIHOOD` | +| [Neyman modified chi-squared](neyman_chi2_exponentiated_weibull_criterion.md) | `NeymanChi2ExponentiatedWeibullGofStatistic` | `CHI2_NEYMAN` | +| [Cressie–Read](cressie_read_exponentiated_weibull_criterion.md) | `CressieReadExponentiatedWeibullGofStatistic` | `CRESSIE_READ` | + +All rejection regions are right-tailed, including D+ and D−. The three Kuiper normalizations have different critical values. The Liao–Shimokawa criterion uses the shared EDF kernel. + +Here $O_j$ and $E_j=np_j>0$ are observed and expected counts in exhaustive, +mutually exclusive cells, with $\sum_jO_j=\sum_jE_j=n$. +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: +$B=\min(1000,\max(2,\lceil2n^{0.4}\rceil))$, and $p_j=1/B$. +Thus the default has two cells even for a singleton sample. The old +$\lceil\sqrt n\rceil$ rule and its one-cell singleton result no longer apply. + +The example chooses three equal-probability cells explicitly. You can instead use +`ExplicitBins((0, b1, b2, float("inf")))` for fixed full-support edges; then +$p_j=F(b_{j+1})-F(b_j)$. See [binning strategies](../binning/index.md). + +The full identifier appends `_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT` to the short code. Frequency `configuration()` includes the binning strategy. Historical square-root-bin calibrations and the old Watson `W` identifier are incompatible with the current catalog. Storage loading remains explicitly blocked by this family. + +For EDF statistics and fixed equal-probability cells the continuous fixed null is distribution-free through the probability integral transform. Fitting any parameter from the same observations changes the null distribution and is outside this API contract. diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_d_minus_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_d_minus_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..be445356 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_d_minus_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Kolmogorov–Smirnov D− for exponentiated Weibull + +`KolmogorovSmirnovDMinusExponentiatedWeibullGofStatistic` + +Short code: `KS_MINUS`. Full code: `KS_MINUS_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +D^-=\max_{1\le i\le n}\left(u_i-\frac{i-1}{n}\right). +$$ + +D− measures the excess of the specified CDF over the empirical CDF. Its rejection region is the right tail. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + KolmogorovSmirnovDMinusExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = KolmogorovSmirnovDMinusExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_d_plus_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_d_plus_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..fd9e1742 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_d_plus_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Kolmogorov–Smirnov D+ for exponentiated Weibull + +`KolmogorovSmirnovDPlusExponentiatedWeibullGofStatistic` + +Short code: `KS_PLUS`. Full code: `KS_PLUS_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +D^+=\max_{1\le i\le n}\left(\frac{i}{n}-u_i\right). +$$ + +D+ measures the excess of the empirical CDF over the specified CDF. Its rejection region is the right tail. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + KolmogorovSmirnovDPlusExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = KolmogorovSmirnovDPlusExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..2a1c1887 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/kolmogorov_smirnov_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Kolmogorov–Smirnov for exponentiated Weibull + +`KolmogorovSmirnovExponentiatedWeibullGofStatistic` + +Short code: `KS`. Full code: `KS_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +D=\max(D^+,D^-),\qquad D^+=\max_i(i/n-u_i),\quad D^-=\max_i(u_i-(i-1)/n). +$$ + +Returns the unsquared, unscaled D. The optional `alternative_type` accepts `AlternativeType.TWO_TAILED` (D), `RIGHT` (D+) or `LEFT` (D−). These are CDF directions; all three reject for large values. `mode` accepts `auto`, `exact`, `asymp`, `approx` for compatibility and does not change the statistic. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + KolmogorovSmirnovExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = KolmogorovSmirnovExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_corrected_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_corrected_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..8639bf4f --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_corrected_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Corrected Kuiper for exponentiated Weibull + +`KuiperCorrectedExponentiatedWeibullGofStatistic` + +Short code: `KUIPER_CORRECTED`. Full code: `KUIPER_CORRECTED_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +V_{\mathrm{corrected}}=\left(\sqrt n+0.155+\frac{0.24}{\sqrt n}\right)(D^++D^-). +$$ + +This is the empirical finite-sample normalization of Kuiper, not an exact finite-sample p-value. D+ and D− are the directional KS deviations. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + KuiperCorrectedExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = KuiperCorrectedExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..df5fc5df --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Kuiper for exponentiated Weibull + +`KuiperExponentiatedWeibullGofStatistic` + +Short code: `KUIPER`. Full code: `KUIPER_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +V=D^++D^-,\qquad D^+=\max_i(i/n-u_i),\quad D^-=\max_i(u_i-(i-1)/n). +$$ + +This is the unscaled Kuiper statistic. Do not interchange its critical values with those for the scaled or corrected classes. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + KuiperExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = KuiperExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_scaled_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_scaled_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..6288a8b6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/kuiper_scaled_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Scaled Kuiper for exponentiated Weibull + +`KuiperScaledExponentiatedWeibullGofStatistic` + +Short code: `KUIPER_SCALED`. Full code: `KUIPER_SCALED_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +V_{\mathrm{scaled}}=\sqrt n\,(D^++D^-). +$$ + +Here D+ and D− are the directional KS deviations. The factor is sqrt(n), not n. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + KuiperScaledExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = KuiperScaledExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/liao_shimokawa_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/liao_shimokawa_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..7fdd2f63 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/liao_shimokawa_exponentiated_weibull_criterion.md @@ -0,0 +1,57 @@ +# Liao–Shimokawa for exponentiated Weibull + +`LiaoShimokawaExponentiatedWeibullGofStatistic` + +Short code: `LS`. Full code: `LS_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +L_n=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,\ u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}}. +$$ + +This is the weighted EDF expression applied to a **fixed** CDF. The original paper estimates parameters; its fitted-Weibull critical values do not apply here. The original full text was unavailable in this audit; eq. (13) in Al-Zahrani provides the formula cross-check, not calibration for this family. + +An exact zero observation gives positive infinity. Finite tail penalties are retained using log probabilities when the CDF rounds to one; the statistic may still overflow when its true magnitude exceeds float64. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + LiaoShimokawaExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = LiaoShimokawaExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Liao and Shimokawa (1999), A new goodness-of-fit test for type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). Formula cross-check: [Al-Zahrani (2012), Goodness-of-fit for the Topp-Leone distribution, eq. (13)](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/mathematical-validation.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/mathematical-validation.md new file mode 100644 index 00000000..c1106169 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/mathematical-validation.md @@ -0,0 +1,227 @@ +# Mathematical verification of exponentiated Weibull statistics + +The [18 public criteria](index.md) were audited: **13 EDF statistics and five +frequency statistics**. This report follows the structure of the +[uniformity audit](../uniformity/mathematical-validation.md). + +## Hypothesis and scope + +The independent observations have the fully specified null + +$$ +F_{a,k,s}(x)=[1-\exp(-(x/s)^k)]^a,\quad x\ge0,\qquad a,k,s>0. +$$ + +The location is zero. `exponent`, `shape` and `scale` must all be fixed before +observing the data; partial parameter sets are rejected. The exponent is not the +ordinary Weibull shape. At $a=1$ this distribution reduces to ordinary Weibull. +The parameterization agrees with [SciPy's `exponweib`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.exponweib.html) +(`a=exponent`, `c=shape`, `scale=scale`, `loc=0`). + +Write $u_i=F_{a,k,s}(x_{(i)})$, $r_i=i-1/2$, and +$D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$. +The probability integral transform supplies the fixed uniform null. All classes +return statistics, not p-values; all use right-tail rejection, including D+ and D−. +No parameter fitting or fitted-Weibull critical-value correction is performed. + +## Formula checks + +| Criterion | Verified definition or normalization | Scientific source | +|---|---|---| +| Kolmogorov–Smirnov D+ | $D^+$; no square or $\sqrt n$ factor | Zhang (2002), §2.1 | +| Kolmogorov–Smirnov D− | $D^-$; right-tail rejection | Zhang (2002), §2.1 | +| Kolmogorov–Smirnov | $\max(D^+,D^-)$; legacy direction options select the same directional statistics | Zhang (2002), §2.1 | +| Anderson–Darling | $-n-n^{-1}\sum_i(2i-1)[\log u_i+\log(1-u_{n+1-i})]$ | Zhang (2002), §2.2 | +| Cramér–von Mises | $1/(12n)+\sum_i(u_i-r_i/n)^2$ | Zhang (2002), §2.3 | +| Liao–Shimokawa | $n^{-1/2}\sum_i\max(i/n-u_i,u_i-(i-1)/n)/\sqrt{u_i(1-u_i)}$ | Liao and Shimokawa (1999); cross-check in Al-Zahrani (2012), eq. (13) | +| Watson | $W^2-n(\bar u-1/2)^2$, computed as centered squared deviations | Lemeshko et al. (2014), eq. (6); Watson (1961) | +| Kuiper | $V=D^++D^-$ | Lemeshko et al. (2014), eq. (1) | +| Scaled Kuiper | $\sqrt n V$ | Lemeshko et al. (2014), discussion before eq. (2) | +| Corrected Kuiper | $(\sqrt n+0.155+0.24/\sqrt n)V$ | Lemeshko et al. (2014), eq. (3) | +| Zhang K | $\max_i[r_i\log(r_i/(nu_i))+(n-r_i)\log((n-r_i)/(n(1-u_i)))]$ | Zhang (2002), eq. (3.1) | +| Zhang A | $-\sum_i[\log u_i/(n-r_i)+\log(1-u_i)/r_i]$ | Zhang (2002), eq. (3.2) | +| Zhang C | $\sum_i[\log((1-u_i)/u_i)-\log((n-i+1/4)/(i-3/4))]^2$ | Zhang (2002), eq. (3.3) | +| Pearson | $\sum_j(O_j-E_j)^2/E_j$, power divergence $\lambda=1$ | Cressie and Read (1984) | +| Freeman–Tukey | $4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2$, $\lambda=-1/2$ | Cressie and Read (1984) | +| Modified log-likelihood | $2\sum_jE_j\log(E_j/O_j)$, $\lambda=-1$ | Cressie and Read (1984) | +| Neyman modified chi-squared | $\sum_j(O_j-E_j)^2/O_j$, $\lambda=-2$ | Cressie and Read (1984) | +| Cressie–Read | $(9/5)\sum_jO_j[(O_j/E_j)^{2/3}-1]$, $\lambda=2/3$ | Cressie and Read (1984) | + +The shared EDF and divergence kernels match these definitions. The audit found +numerical errors in the family probability calculations, rather than incorrect +normalizations in these kernels; the corrections are described below. + +## Sources and verification limits + +- [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). +- [Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), [authors' university copy](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). +- [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), [full text](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). +- [Liao and Shimokawa (1999), A new goodness-of-fit test for type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). +- [Al-Zahrani (2012), Goodness-of-Fit for the Topp-Leone Distribution with Unknown Parameters](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf), eq. (13). +- [Watson (1961), Goodness-of-fit tests on a circle](https://doi.org/10.1093/biomet/48.1-2.109). + +Zhang and Lemeshko were checked in accessible full texts. The power-divergence +family and its parameter correspondences were checked against the accessible +text of Cressie and Read. The original Liao–Shimokawa full text was unavailable: +its bibliographic record and abstract were checked, and the implemented weighted +EDF expression was cross-checked in Al-Zahrani's application. That latter paper +is not used as a reference for the other EDF formulas or for exponentiated +Weibull critical values. + +The original Liao–Shimokawa procedure estimates parameters, whereas this family uses +a specified CDF. Its fitted-null tables are therefore unsuitable here. +Zhang C implements the published quarter-rank approximation in eq. (3.3), not +the preceding integrated statistic with its constants. Corrected Kuiper uses +an empirical normalization, not an exact finite-sample distribution. + +## Numerical corrections + +1. **False infinite logarithmic penalties for tiny exponents.** For + `exponent=1e-320`, `shape=scale=1` and sample `[1, 2, 10]`, the old + Anderson–Darling calculation returned infinity. An 800-digit Decimal + evaluation gives approximately **2214.0422443729744**. Multiplication by + the exponent rounded $\log F$ to a subnormal value or zero before computing + $\log(1-F)$. The family probability kernel now computes + $\log q=\log a+\log[-\log(1-e^{-t})]$, where $t=(x/s)^k$ and + $q=-\log F$, and uses $\log(1-e^{-q})\simeq\log q$ for tiny $q$. + The regression also covers Liao–Shimokawa and all three Zhang statistics. +2. **Overflow before a compensating exponent.** For `shape=1e308`, + `exponent=1e-308`, `scale=1` and positive observations below one, + $k\log(x/s)$ can overflow negatively even though $ak\log(x/s)$ is finite. + The lower-tail branch now evaluates the latter product directly. The + limiting CDF in the regression is $F(x)\simeq x$; KS is checked against + an independent uniform reference. +3. **Frequency cells computed from an underflowed intermediate CDF.** At + `shape=1000`, `exponent=0.001`, `scale=1`, directly evaluating the ordinary + Weibull CDF before exponentiation can round it to zero. For sample + `[0.01, 0.1, 0.4, 0.8]`, the correct two-cell Pearson value is **1**. + Frequency binning now uses the same stable CDF and logarithmic tails as + EDF evaluation. Both equal-probability and explicit-edge bins are checked. + +These are floating-point corrections to the specified mathematical model. +Exact zero observations still give infinite logarithmic EDF penalties. +Statistics whose true magnitudes exceed float64 can still be infinite. +Extreme parameter combinations may also be unsuitable for sampling with the +SciPy-backed generator; this audit does not certify that generator across the +entire floating-point parameter range. + +## Frequency bins and calibration + +The current default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: + +$$ +B=\min(1000,\max(2,\lceil2n^{0.4}\rceil)),\qquad E_j=n/B. +$$ + +The previous Pearson documentation incorrectly retained $\lceil\sqrt n\rceil$ +and a one-cell singleton. The pages now describe the actual default, its cap, +and explicit binning options. At $n=1$ the default has two cells: Pearson is 1, +not 0. Zero observed cells produce infinity for modified log-likelihood and +Neyman; Freeman–Tukey, Pearson and Cressie–Read have finite limits. + +For fixed exhaustive cells with positive probabilities, the large-sample +chi-squared reference has $B-1$ degrees of freedom because no parameters are +estimated. This does not establish accuracy with small expected counts or +sample-size-dependent bins. Monte Carlo must reproduce the chosen statistic, +sample size and binning. The family still rejects stored unversioned critical +values. Changing the binning or statistic identifier requires recalibration; +the current Watson short code is `WATSON`, not the historical `W`. + +## Package and type declarations + +The public package follows the uniform family layout: + +```text +continuous/exponentiated_weibull/ + __init__.py + __init__.pyi + exponentiated_weibull_statistics.py +``` + +`__init__.py` re-exports all 19 public classes (one abstract family base and +18 criteria). The public import paths and class module identifiers remain +unchanged, including compatibility with existing pickle references. +`__init__.pyi` describes the generated classes, per-criterion hypotheses, +frequency `binning` arguments, and the legacy KS direction and mode options. +Regenerate and check it without importing the package: + +```bash +python scripts/generate_exponentiated_weibull_stub.py +python scripts/generate_exponentiated_weibull_stub.py --check +``` + +## Numba implementation + +All 18 criteria use the compiled shared EDF or frequency statistic kernels. +`AbstractExponentiatedWeibullGofStatistic.do_log_probabilities` additionally uses +`@jit(nopython=True, cache=True)` to evaluate the family probabilities in one +pass. It avoids intermediate masks and arrays, and computes survival logs only +when required. EDF criteria without logarithmic kernels and frequency CDF +binning use the CDF-only path. Validation, sorting, strategy selection and +parameter objects remain outside the compiled kernel, as in the uniform family. + +All family callbacks are class methods; the module has no module-level function +definitions. No `fastmath` is enabled: NaNs, infinities and the tail safeguards +above retain their intended meaning. Compilation has a first-call cost; timings +of repeated evaluations must exclude compilation. Tests check nopython dispatch +for every criterion and compare compiled results with the Python kernel at +ordinary and extreme parameter values. + +## Numerical verification and documentation coverage + +The dedicated suite is +`tests/statistics/test_exponentiated_weibull_mathematical_validation.py`. +It checks all 18 formulas using independent EDF quadrature, SciPy KS and +multinomial power divergences, direct rank formulas, and 800-digit Decimal +references. It includes zero observations, ties, singletons, empty cells, +legacy KS directions, extreme exponents, intermediate overflow, and the +probability adapter's scalar/array and support contracts. + +Every criterion has a dedicated page, explicit formula, scientific links and +an executable example. The coverage test matches pages against the actual +runtime catalog, checks the index and MkDocs navigation, and executes all 18 +examples. Public class docstrings also contain examples and scientific links. + +The focused isolated run passed **275 tests**, including execution of all 18 +page examples and all 72 docstring example steps. Ruff passed for the changed +Python files. MkDocs built successfully; existing warnings concern other +sections, with no warnings for exponentiated Weibull pages. + +The ordinary pytest invocation is currently blocked during package import by +an unrelated obsolete `AbstractChi2Statistic` import in `inverse_gamma.py`. +The focused run bypasses only the eager `continuous/__init__.py` imports; it +loads the real family, factories, kernels, distributions and binning code. +Consequently the results verify these calculations and documentation, but do +not establish that ordinary package initialization works. + +A reproducible isolated invocation from the repository root is: + +```python +import sys +import types +from pathlib import Path +import pytest + +name = "pysatl_criterion.statistics.goodness_of_fit.continuous" +package = types.ModuleType(name) +package.__path__ = [ + str(Path("src/pysatl_criterion/statistics/goodness_of_fit/continuous").resolve()) +] +sys.modules[name] = package +raise SystemExit( + pytest.main( + [ + "tests/statistics/test_exponentiated_weibull_mathematical_validation.py", + "tests/statistics/test_exponentiated_weibull_dynamic.py", + "tests/distributions/test_weibull_families.py", + "tests/statistics/test_exponentiated_weibull_numba.py", + "-q", + ] + ) +) +``` + +The checks establish agreement with the stated formulas on the tested cases. +They are not a proof of exact rejection probabilities, a power study, or a +certification of all possible float64 parameter combinations. diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/modified_log_likelihood_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/modified_log_likelihood_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..3928bae4 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/modified_log_likelihood_exponentiated_weibull_criterion.md @@ -0,0 +1,68 @@ +# Modified log-likelihood for exponentiated Weibull + +`ModifiedLogLikelihoodExponentiatedWeibullGofStatistic` + +Short code: `MODIFIED_LOG_LIKELIHOOD`. Full code: `MODIFIED_LOG_LIKELIHOOD_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Here $O_j$ and $E_j=np_j>0$ are observed and expected counts in exhaustive, +mutually exclusive cells, with $\sum_jO_j=\sum_jE_j=n$. +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: +$B=\min(1000,\max(2,\lceil2n^{0.4}\rceil))$, and $p_j=1/B$. +Thus the default has two cells even for a singleton sample. The old +$\lceil\sqrt n\rceil$ rule and its one-cell singleton result no longer apply. + +The example chooses three equal-probability cells explicitly. You can instead use +`ExplicitBins((0, b1, b2, float("inf")))` for fixed full-support edges; then +$p_j=F(b_{j+1})-F(b_j)$. See [binning strategies](../binning/index.md). + +$$ +T_{ML}=2\sum_{j=1}^B E_j\log\frac{E_j}{O_j}. +$$ + +Power divergence at lambda=−1. This reverses the usual likelihood-ratio divergence. Any zero O_j with E_j>0 gives positive infinity. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. For fixed B and sufficiently large expected counts the usual reference is chi-squared with B−1 degrees of freedom; no parameters are fitted. Small or empty cells and a sample-size-dependent B require appropriate calibration, preferably Monte Carlo. Repeat the chosen binning procedure in every replicate. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + ModifiedLogLikelihoodExponentiatedWeibullGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = ModifiedLogLikelihoodExponentiatedWeibullGofStatistic( + parameters, binning=EqualProbabilityBins(count=3) +) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); [full text](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/neyman_chi2_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/neyman_chi2_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..e5866d44 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/neyman_chi2_exponentiated_weibull_criterion.md @@ -0,0 +1,66 @@ +# Neyman modified chi-squared for exponentiated Weibull + +`NeymanChi2ExponentiatedWeibullGofStatistic` + +Short code: `CHI2_NEYMAN`. Full code: `CHI2_NEYMAN_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Here $O_j$ and $E_j=np_j>0$ are observed and expected counts in exhaustive, +mutually exclusive cells, with $\sum_jO_j=\sum_jE_j=n$. +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`: +$B=\min(1000,\max(2,\lceil2n^{0.4}\rceil))$, and $p_j=1/B$. +Thus the default has two cells even for a singleton sample. The old +$\lceil\sqrt n\rceil$ rule and its one-cell singleton result no longer apply. + +The example chooses three equal-probability cells explicitly. You can instead use +`ExplicitBins((0, b1, b2, float("inf")))` for fixed full-support edges; then +$p_j=F(b_{j+1})-F(b_j)$. See [binning strategies](../binning/index.md). + +$$ +T_N=\sum_{j=1}^B\frac{(O_j-E_j)^2}{O_j}. +$$ + +Power divergence at lambda=−2. The denominator is the observed count. Any zero O_j with E_j>0 gives positive infinity. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. For fixed B and sufficiently large expected counts the usual reference is chi-squared with B−1 degrees of freedom; no parameters are fitted. Small or empty cells and a sample-size-dependent B require appropriate calibration, preferably Monte Carlo. Repeat the chosen binning procedure in every replicate. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + NeymanChi2ExponentiatedWeibullGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = NeymanChi2ExponentiatedWeibullGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); [full text](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/watson_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/watson_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..1ffa7e1f --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/watson_exponentiated_weibull_criterion.md @@ -0,0 +1,55 @@ +# Watson for exponentiated Weibull + +`WatsonExponentiatedWeibullGofStatistic` + +Short code: `WATSON`. Full code: `WATSON_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +U^2=W^2-n(\bar u-1/2)^2=\frac1{12n}+\sum_{i=1}^n(d_i-\bar d)^2,\quad d_i=u_i-\frac{i-1/2}{n}. +$$ + +The implementation centers deviations before squaring to avoid cancellation. No finite-sample correction is used. The current short code is `WATSON`; historical `W` calibrations must not be reused. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + WatsonExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = WatsonExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). Original: [Watson (1961), Goodness-of-fit tests on a circle](https://doi.org/10.1093/biomet/48.1-2.109). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_a_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_a_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..5f8ebd67 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_a_exponentiated_weibull_criterion.md @@ -0,0 +1,57 @@ +# Zhang Z_A for exponentiated Weibull + +`ZhangAExponentiatedWeibullGofStatistic` + +Short code: `ZHANG_ZA`. Full code: `ZHANG_ZA_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +Z_A=-\sum_{i=1}^n\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right]. +$$ + +Uses eq. (3.2), including its rank-dependent denominators; no additional factor n is applied. + +An exact zero observation gives positive infinity. Finite tail penalties are retained using log probabilities when the CDF rounds to one; the statistic may still overflow when its true magnitude exceeds float64. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + ZhangAExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = ZhangAExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_c_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_c_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..5a68b127 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_c_exponentiated_weibull_criterion.md @@ -0,0 +1,57 @@ +# Zhang Z_C for exponentiated Weibull + +`ZhangCExponentiatedWeibullGofStatistic` + +Short code: `ZHANG_ZC`. Full code: `ZHANG_ZC_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +Z_C=\sum_{i=1}^n\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2. +$$ + +Uses the quarter-rank approximation in eq. (3.3). It is not the preceding exact integrated expression with sample-size constants in the paper. Log odds are evaluated as differences of logarithms. + +An exact zero observation gives positive infinity. Finite tail penalties are retained using log probabilities when the CDF rounds to one; the statistic may still overflow when its true magnitude exceeds float64. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + ZhangCExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = ZhangCExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_k_exponentiated_weibull_criterion.md b/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_k_exponentiated_weibull_criterion.md new file mode 100644 index 00000000..3d3c7568 --- /dev/null +++ b/docs/criteria/goodness-of-fit/exponentiated-weibull/zhang_k_exponentiated_weibull_criterion.md @@ -0,0 +1,57 @@ +# Zhang Z_K for exponentiated Weibull + +`ZhangKExponentiatedWeibullGofStatistic` + +Short code: `ZHANG_ZK`. Full code: `ZHANG_ZK_EXPONENTIATED_WEIBULL_GOODNESS_OF_FIT`. + +## Hypothesis and input + +The null is fully specified: + +$$ +F_{a,k,s}(x)=\left[1-\exp\left(-(x/s)^k\right)\right]^a,\quad x\ge0, +\qquad a,k,s>0. +$$ + +Fix `exponent=a`, `shape=k`, `scale=s` in +`ExponentiatedWeibullDistributionDescriptor.DEFAULT.parse(...)`; location is zero. +All three parameters are required and are never estimated from the observations. +`execute_statistic` accepts a nonempty one-dimensional finite nonnegative sample; +ties and constant samples are allowed. It returns a scalar statistic, not a p-value, +and leaves the sample and parameters unchanged. + +## Formula + +Write $u_i=F_{a,k,s}(x_{(i)})$ for the sorted observations, $i=1,\ldots,n$. + +$$ +Z_K=\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right],\qquad r_i=i-\tfrac12. +$$ + +Uses the half-rank convention of eq. (3.1), without an extra factor 2. Logarithms are computed separately. + +An exact zero observation gives positive infinity. Finite tail penalties are retained using log probabilities when the CDF rounds to one; the statistic may still overflow when its true magnitude exceeds float64. + +## Calibration + +Reject for large values (right tail). Use the same sample size and statistic normalization when calibrating the fixed null. The probability integral transform gives a Uniform(0,1) null in exact arithmetic. Critical values from tests that estimate Weibull parameters are unsuitable. The family currently rejects stored unversioned calibrations; regenerate them and do not assume storage loading is enabled. + +## Example + +```python +from pysatl_criterion.distribution import ExponentiatedWeibullDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.exponentiated_weibull import ( + ZhangKExponentiatedWeibullGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"exponent": 1, "shape": 2, "scale": 1}) +test = ZhangKExponentiatedWeibullGofStatistic(parameters) +value = test.execute_statistic([0.1, 0.25, 0.4, 0.55, 0.7, 0.9, 1.2, 1.5, 2.0]) +print(value) +``` + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/gamma/anderson_darling_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/anderson_darling_gamma_criterion.md index 10ce9e1c..429decac 100644 --- a/docs/criteria/goodness-of-fit/gamma/anderson_darling_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/anderson_darling_gamma_criterion.md @@ -1,48 +1,37 @@ -# Anderson-Darling test for gamma distribution +# Anderson–Darling for Gamma -## Description -Performs Anderson-Darling goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The test gives additional weight to discrepancies in the tails. +`AndersonDarlingGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - AndersonDarlingGammaGofStatistic, -) +## Definition +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -test_statistic = AndersonDarlingGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1)[\log u_i+\log(1-u_{n+1-i})] +$$ -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +Evaluated with log-CDF and log-survival values. A zero observation gives infinity; no finite-sample correction is applied. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -`rvs` - array-like sample data passed to `execute_statistic`. +## Source -## Details -The implementation evaluates gamma `logcdf` and `logsf` values for the ordered sample and passes them to the common Anderson-Darling statistic implementation. +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337); [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437).. -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Anderson, T.W. and Darling, D.A. (1952): Asymptotic theory of certain goodness of fit criteria based on stochastic processes. - Annals of Mathematical Statistics, vol. 23, pp. 193-212. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( AndersonDarlingGammaGofStatistic, ) - -test_statistic = AndersonDarlingGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = AndersonDarlingGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/chi2_pearson_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/chi2_pearson_gamma_criterion.md index c54857fe..6e7e52c1 100644 --- a/docs/criteria/goodness-of-fit/gamma/chi2_pearson_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/chi2_pearson_gamma_criterion.md @@ -1,51 +1,42 @@ -# Pearson chi-squared test for gamma distribution +# Pearson chi-squared for Gamma -## Description -Performs Pearson chi-squared goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The implementation bins observations using equiprobable gamma quantile bins. +`Chi2PearsonGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Chi2PearsonGammaGofStatistic, -) +## Definition +Here $O_j$ and $E_j=np_j$ are observed and expected cell counts. With k equal-probability cells, $E_j=n/k$. -test_statistic = Chi2PearsonGammaGofStatistic(bins=4, alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +$$ +X^2=\sum_j (O_j-E_j)^2/E_j +$$ -## Arguments -`bins` - number of equiprobable gamma bins. Default value is `8`. -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +The constructor accepts `binning`, a `BinningStrategy`. The default is `EqualProbabilityBins()` with `PowerCount()`: k is ceil(2*n**0.4), bounded to 2…1000. To fix k, use `EqualProbabilityBins(count=k)`. Counts use the intervals of the transformed CDF; the last interval includes 1. Other strategies use their own null probabilities. Binning configuration is included in storage keys. -`rvs` - array-like sample data passed to `execute_statistic`. +For fixed null-probability bins, use multinomial/Monte Carlo calibration with the same n and bins. The chi-square(k−1) approximation needs sufficiently large expected counts and fixed k; sparse cells or sample-dependent rules require separate calibration. -## Details -The bin edges are gamma quantiles, so each bin has equal theoretical probability under the null model. -Observed bin counts are compared with equal expected counts. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -## Author(s) -Sergey Golovachev, Alexey Mironov +## Source -## References -Pearson, K. (1900): On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling. - Philosophical Magazine, vol. 50, pp. 157-175. +[Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( Chi2PearsonGammaGofStatistic, ) - -test_statistic = Chi2PearsonGammaGofStatistic(bins=4, alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = Chi2PearsonGammaGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/cressie_read_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/cressie_read_gamma_criterion.md index 94b9af10..bd6bff4b 100644 --- a/docs/criteria/goodness-of-fit/gamma/cressie_read_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/cressie_read_gamma_criterion.md @@ -1,52 +1,42 @@ -# Cressie-Read test for gamma distribution +# Cressie–Read for Gamma -## Description -Performs Cressie-Read power-divergence goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic generalizes Pearson chi-squared and likelihood-ratio statistics. +`CressieReadGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CressieReadGammaGofStatistic, -) +## Definition +Here $O_j$ and $E_j=np_j$ are observed and expected cell counts. With k equal-probability cells, $E_j=n/k$. -test_statistic = CressieReadGammaGofStatistic(power=2 / 3, bins=4, alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +$$ +T=\frac95\sum_j O_j[(O_j/E_j)^{2/3}-1] +$$ -## Arguments -`power` - Cressie-Read power-divergence parameter. Default value is `2 / 3`. +The power is fixed at 2/3; there is no `power` constructor argument. Empty observed cells contribute zero. -`bins` - number of equiprobable gamma bins. Default value is `8`. +The constructor accepts `binning`, a `BinningStrategy`. The default is `EqualProbabilityBins()` with `PowerCount()`: k is ceil(2*n**0.4), bounded to 2…1000. To fix k, use `EqualProbabilityBins(count=k)`. Counts use the intervals of the transformed CDF; the last interval includes 1. Other strategies use their own null probabilities. Binning configuration is included in storage keys. -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +For fixed null-probability bins, use multinomial/Monte Carlo calibration with the same n and bins. The chi-square(k−1) approximation needs sufficiently large expected counts and fixed k; sparse cells or sample-dependent rules require separate calibration. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -`rvs` - array-like sample data passed to `execute_statistic`. +## Source -## Details -The implementation uses equiprobable gamma quantile bins and passes observed and expected counts to the common chi-squared statistic implementation with the selected power-divergence parameter. +[Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Cressie, N. and Read, T.R.C. (1984): Multinomial goodness-of-fit tests. - Journal of the Royal Statistical Society, Series B, vol. 46, pp. 440-464. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( CressieReadGammaGofStatistic, ) - -test_statistic = CressieReadGammaGofStatistic(power=2 / 3, bins=4, alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = CressieReadGammaGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/cvm_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/cvm_gamma_criterion.md index bc3f39f9..b379810b 100644 --- a/docs/criteria/goodness-of-fit/gamma/cvm_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/cvm_gamma_criterion.md @@ -1,54 +1,37 @@ -# Cramer-von Mises test for gamma distribution +# Cramér–von Mises for Gamma -## Description -Performs Cramer-von Mises goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic accumulates squared differences between empirical plotting positions and gamma cumulative distribution function values. +`CramerVonMisesGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CramerVonMisesGammaGofStatistic, -) +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. +## Definition -test_statistic = CramerVonMisesGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +$$ +W^2=\frac1{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2 +$$ -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. -`rvs` - array-like sample data passed to `execute_statistic`. -## Details -The Cramer-von Mises statistic is +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -$$ W_n^2 = \frac{1}{12n} + \sum_{i=1}^{n} \left(F_0(X_{(i)}) - \frac{2i - 1}{2n}\right)^2 $$ +## Source -where $F_0$ is the reference gamma cumulative distribution function. +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Cramer, H. (1928): On the composition of elementary errors. - Skandinavisk Aktuarietidskrift, vol. 11, pp. 141-180. - -von Mises, R. (1931): Wahrscheinlichkeitsrechnung und ihre Anwendung in der Statistik und theoretischen Physik. - Leipzig: Deuticke. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( CramerVonMisesGammaGofStatistic, ) - -test_statistic = CramerVonMisesGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = CramerVonMisesGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/freeman_tukey_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/freeman_tukey_gamma_criterion.md new file mode 100644 index 00000000..4295a58b --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/freeman_tukey_gamma_criterion.md @@ -0,0 +1,42 @@ +# Freeman–Tukey for Gamma + +`FreemanTukeyGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Here $O_j$ and $E_j=np_j$ are observed and expected cell counts. With k equal-probability cells, $E_j=n/k$. + +$$ +T=4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2 +$$ + +An empty observed cell contributes $4E_j$. + +The constructor accepts `binning`, a `BinningStrategy`. The default is `EqualProbabilityBins()` with `PowerCount()`: k is ceil(2*n**0.4), bounded to 2…1000. To fix k, use `EqualProbabilityBins(count=k)`. Counts use the intervals of the transformed CDF; the last interval includes 1. Other strategies use their own null probabilities. Binning configuration is included in storage keys. + +For fixed null-probability bins, use multinomial/Monte Carlo calibration with the same n and bins. The chi-square(k−1) approximation needs sufficiently large expected counts and fixed k; sparse cells or sample-dependent rules require separate calibration. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + FreemanTukeyGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = FreemanTukeyGammaGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/graph_average_degree_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/graph_average_degree_gamma_criterion.md index 2e91fb88..4c14d27b 100644 --- a/docs/criteria/goodness-of-fit/gamma/graph_average_degree_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/graph_average_degree_gamma_criterion.md @@ -1,48 +1,37 @@ -# Graph average degree test for gamma distribution +# Graph average degree for Gamma -## Description -Performs graph average degree goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic computes the mean vertex degree in a proximity graph built on gamma CDF transformed observations. +`GraphAverageDegreeGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphAverageDegreeGammaGofStatistic, -) +## Definition +Vertices are the transformed observations $u_i$. Join distinct vertices exactly when $|u_i-u_j| 0`, rate `beta > 0` and origin zero: + +$$ +f(x)=\frac{\beta^\alpha}{\Gamma(\alpha)}x^{\alpha-1}e^{-\beta x},\qquad x>0. +$$ + +Supply both parameters via `GammaDistributionDescriptor.DEFAULT.parse(...)`. +`beta` is a rate, not a scale. Estimating parameters from the tested sample changes +the null law and is outside these criteria's supported hypotheses. + +## Catalog + +| Criterion | Public class | Family | +|---|---|---| +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_gamma_criterion.md) | `KolmogorovSmirnovDPlusGammaGofStatistic` | edf | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_gamma_criterion.md) | `KolmogorovSmirnovDMinusGammaGofStatistic` | edf | +| [Kolmogorov–Smirnov](kolmogorov_smirnov_gamma_criterion.md) | `KolmogorovSmirnovGammaGofStatistic` | edf | +| [Anderson–Darling](anderson_darling_gamma_criterion.md) | `AndersonDarlingGammaGofStatistic` | edf | +| [Cramér–von Mises](cvm_gamma_criterion.md) | `CramerVonMisesGammaGofStatistic` | edf | +| [Watson](watson_gamma_criterion.md) | `WatsonGammaGofStatistic` | edf | +| [Kuiper](kuiper_gamma_criterion.md) | `KuiperGammaGofStatistic` | edf | +| [Scaled Kuiper](kuiper_scaled_gamma_criterion.md) | `KuiperScaledGammaGofStatistic` | edf | +| [Corrected Kuiper](kuiper_corrected_gamma_criterion.md) | `KuiperCorrectedGammaGofStatistic` | edf | +| [Liao–Shimokawa](liao_shimokawa_gamma_criterion.md) | `LiaoShimokawaGammaGofStatistic` | edf | +| [Zhang K](zhang_k_gamma_criterion.md) | `ZhangKGammaGofStatistic` | edf | +| [Zhang A](zhang_a_gamma_criterion.md) | `ZhangAGammaGofStatistic` | edf | +| [Zhang C](zhang_c_gamma_criterion.md) | `ZhangCGammaGofStatistic` | edf | +| [Greenwood](greenwood_gamma_criterion.md) | `GreenwoodGammaGofStatistic` | spacing | +| [Moran](moran_gamma_criterion.md) | `MoranGammaGofStatistic` | spacing | +| [Pearson chi-squared](chi2_pearson_gamma_criterion.md) | `Chi2PearsonGammaGofStatistic` | frequency | +| [Freeman–Tukey](freeman_tukey_gamma_criterion.md) | `FreemanTukeyGammaGofStatistic` | frequency | +| [Modified log-likelihood](modified_log_likelihood_gamma_criterion.md) | `ModifiedLogLikelihoodGammaGofStatistic` | frequency | +| [Neyman modified chi-squared](neyman_chi2_gamma_criterion.md) | `NeymanChi2GammaGofStatistic` | frequency | +| [Cressie–Read](cressie_read_gamma_criterion.md) | `CressieReadGammaGofStatistic` | frequency | +| [Likelihood ratio](likelihood_ratio_gamma_criterion.md) | `LikelihoodRatioGammaGofStatistic` | likelihood | +| [Probability plot correlation](probability_plot_correlation_gamma_criterion.md) | `ProbabilityPlotCorrelationGammaGofStatistic` | ppcc | +| [Graph edge count](graph_edges_number_gamma_criterion.md) | `GraphEdgesNumberGammaGofStatistic` | graph | +| [Graph maximum degree](graph_max_degree_gamma_criterion.md) | `GraphMaxDegreeGammaGofStatistic` | graph | +| [Graph average degree](graph_average_degree_gamma_criterion.md) | `GraphAverageDegreeGammaGofStatistic` | graph | +| [Graph connected components](graph_connected_components_gamma_criterion.md) | `GraphConnectedComponentsGammaGofStatistic` | graph | +| [Graph clique number](graph_clique_number_gamma_criterion.md) | `GraphCliqueNumberGammaGofStatistic` | graph | +| [Graph independence number](graph_independence_number_gamma_criterion.md) | `GraphIndependenceNumberGammaGofStatistic` | graph | + +## Calibration and limitations + +For a specified continuous Gamma CDF, its probability transform is uniform. +EDF, spacing and CDF-graph null distributions therefore do not depend on Gamma +parameters in exact arithmetic. PPCC instead depends on shape and cannot detect +positive affine changes of the sample. Graph criteria use a local range/10 rule; +their formulas are verified, but a Gamma-specific published calibration was not +established. Simulate the actual statistic and sample size when calibrating them. + +Generated frequency criteria accept `binning=EqualProbabilityBins(count=k)`; +Cressie–Read has fixed power 2/3. Only the local likelihood-ratio class retains +`bins=k` (default 8). Its storage lookup remains blocked. Generated frequency +classes serialize binning configuration for storage. Watson and Kuiper now use +short codes `WATSON` and `KUIPER`; old calibration identifiers must not be assumed +to refer to the new classes. + +All classes accept finite nonnegative observations, including zero. Logarithmic +criteria can return infinity at boundaries or ties; PPCC rejects constant samples. +Log-CDF/log-survival evaluation reduces tail cancellation but does not provide +arbitrary precision: extreme Gamma probabilities may underflow and ordinary CDF +values may saturate at 0 or 1. No epsilon clipping changes the mathematical null. + +See [mathematical verification](mathematical-validation.md) for evidence, +independent checks and limitations of this audit. diff --git a/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_d_minus_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_d_minus_gamma_criterion.md new file mode 100644 index 00000000..e7e0fb8f --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_d_minus_gamma_criterion.md @@ -0,0 +1,37 @@ +# Kolmogorov–Smirnov D− for Gamma + +`KolmogorovSmirnovDMinusGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D^-=\max_i(u_i-(i-1)/n) +$$ + + + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + KolmogorovSmirnovDMinusGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = KolmogorovSmirnovDMinusGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_d_plus_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_d_plus_gamma_criterion.md new file mode 100644 index 00000000..ead81649 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_d_plus_gamma_criterion.md @@ -0,0 +1,37 @@ +# Kolmogorov–Smirnov D+ for Gamma + +`KolmogorovSmirnovDPlusGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D^+=\max_i(i/n-u_i) +$$ + + + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + KolmogorovSmirnovDPlusGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = KolmogorovSmirnovDPlusGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_gamma_criterion.md index bb2012e4..11146caa 100644 --- a/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/kolmogorov_smirnov_gamma_criterion.md @@ -1,61 +1,37 @@ -# Kolmogorov-Smirnov test for gamma distribution +# Kolmogorov–Smirnov for Gamma -## Description -Performs Kolmogorov-Smirnov goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic compares the empirical distribution function with the theoretical gamma cumulative distribution function. +`KolmogorovSmirnovGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -Test Statistic -The statistic is based on the maximum distance between the empirical distribution function and the reference gamma cumulative distribution function. +## Definition -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KolmogorovSmirnovGammaGofStatistic, -) - - -test_statistic = KolmogorovSmirnovGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` - -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +$$ +D=\max(D^+,D^-) +$$ -`alternative_type` - alternative hypothesis type used by the Kolmogorov-Smirnov statistic. +The default is the two-sided CDF discrepancy. Legacy `alternative_type=RIGHT` selects D+ and `LEFT` selects D−; each statistic rejects for large values. `mode` does not change the statistic. Nondefault directions cannot use stored calibration. -`mode` - calculation mode passed to the Kolmogorov-Smirnov statistic. Default value is `auto`. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -`rvs` - array-like sample data passed to `execute_statistic`. +## Source -## Details -The implementation evaluates the gamma cumulative distribution function using `scale=1 / beta`: +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). -$$ F_0(x) = F_{\Gamma(\alpha, 1 / \beta)}(x). $$ - -The transformed ordered observations are passed to the common Kolmogorov-Smirnov statistic implementation. - -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Kolmogorov, A.N. (1933): Sulla determinazione empirica di una legge di distribuzione. - Giornale dell'Istituto Italiano degli Attuari, vol. 4, pp. 83-91. - -Smirnov, N.V. (1948): Table for estimating the goodness of fit of empirical distributions. - Annals of Mathematical Statistics, vol. 19, pp. 279-281. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( KolmogorovSmirnovGammaGofStatistic, ) - -test_statistic = KolmogorovSmirnovGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = KolmogorovSmirnovGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/kuiper_corrected_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/kuiper_corrected_gamma_criterion.md new file mode 100644 index 00000000..ec7055c6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/kuiper_corrected_gamma_criterion.md @@ -0,0 +1,37 @@ +# Corrected Kuiper for Gamma + +`KuiperCorrectedGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V_c=(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-) +$$ + +This is a finite-sample scaling, not an exact finite-sample p-value. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Lemeshko et al. (2014), eqs. (1)–(6)](https://doi.org/10.3103/S875669901401004X). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + KuiperCorrectedGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = KuiperCorrectedGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/kuiper_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/kuiper_gamma_criterion.md index 713a1f92..e7428594 100644 --- a/docs/criteria/goodness-of-fit/gamma/kuiper_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/kuiper_gamma_criterion.md @@ -1,52 +1,35 @@ -# Kuiper test for gamma distribution +# Kuiper for Gamma -## Description -Performs Kuiper goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic combines the largest positive and negative empirical distribution deviations. +`KuiperGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KuiperGammaGofStatistic, -) - - -test_statistic = KuiperGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +## Definition -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +$$ +V=D^++D^- +$$ -`rvs` - array-like sample data passed to `execute_statistic`. +The current short code is `KUIPER`. -## Details -The implementation computes +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -$$ V = D^+ + D^- $$ +## Source -where $D^+$ and $D^-$ are one-sided deviations between empirical plotting positions and gamma CDF values. +[Lemeshko et al. (2014), eqs. (1)–(6)](https://doi.org/10.3103/S875669901401004X). -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Kuiper, N.H. (1960): Tests concerning random points on a circle. - Proceedings of the Koninklijke Nederlandse Akademie van Wetenschappen, Series A, vol. 63, pp. 38-47. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KuiperGammaGofStatistic, -) +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import KuiperGammaGofStatistic - -test_statistic = KuiperGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = KuiperGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/kuiper_scaled_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/kuiper_scaled_gamma_criterion.md new file mode 100644 index 00000000..377c93f7 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/kuiper_scaled_gamma_criterion.md @@ -0,0 +1,37 @@ +# Scaled Kuiper for Gamma + +`KuiperScaledGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V_s=\sqrt n(D^++D^-) +$$ + + + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Lemeshko et al. (2014), eqs. (1)–(6)](https://doi.org/10.3103/S875669901401004X). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + KuiperScaledGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = KuiperScaledGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/liao_shimokawa_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/liao_shimokawa_gamma_criterion.md new file mode 100644 index 00000000..dfb887ed --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/liao_shimokawa_gamma_criterion.md @@ -0,0 +1,37 @@ +# Liao–Shimokawa for Gamma + +`LiaoShimokawaGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +L_n=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}} +$$ + +Logarithmic tail probabilities are used. A zero observation gives infinity. The original fitted Weibull/extreme-value critical values do not apply to the fixed Gamma null. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + LiaoShimokawaGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = LiaoShimokawaGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/likelihood_ratio_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/likelihood_ratio_gamma_criterion.md index ced8eee5..90d79420 100644 --- a/docs/criteria/goodness-of-fit/gamma/likelihood_ratio_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/likelihood_ratio_gamma_criterion.md @@ -1,50 +1,39 @@ -# Likelihood-ratio test for gamma distribution +# Likelihood ratio for Gamma -## Description -Performs likelihood-ratio goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The test is a G-test variant of the binned chi-squared family. +`LikelihoodRatioGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LikelihoodRatioGammaGofStatistic, -) +## Definition +Here $O_j$ and $E_j=np_j$ are observed and expected cell counts. With k equal-probability cells, $E_j=n/k$. -test_statistic = LikelihoodRatioGammaGofStatistic(bins=4, alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +$$ +G^2=2\sum_{j:O_j>0}O_j\log(O_j/E_j) +$$ -## Arguments -`bins` - number of equiprobable gamma bins. Default value is `8`. +Empty observed cells contribute zero. This local class retains `bins=8` by default (integer >=2), unlike the generated frequency classes. Gamma quantile bins cover the support. Storage calibration is blocked; use simulation of the configured instance. -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +For fixed null-probability bins, use multinomial/Monte Carlo calibration with the same n and bins. The chi-square(k−1) approximation needs sufficiently large expected counts and fixed k; sparse cells or sample-dependent rules require separate calibration. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -`rvs` - array-like sample data passed to `execute_statistic`. +## Source -## Details -The implementation uses equiprobable gamma quantile bins and the power-divergence statistic with `lambda = 0`. +[Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Wilks, S.S. (1935): The likelihood test of independence in contingency tables. - Annals of Mathematical Statistics, vol. 6, pp. 190-196. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( LikelihoodRatioGammaGofStatistic, ) - -test_statistic = LikelihoodRatioGammaGofStatistic(bins=4, alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = LikelihoodRatioGammaGofStatistic(parameters, bins=3) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/lilliefors_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/lilliefors_gamma_criterion.md deleted file mode 100644 index 9d9198f0..00000000 --- a/docs/criteria/goodness-of-fit/gamma/lilliefors_gamma_criterion.md +++ /dev/null @@ -1,52 +0,0 @@ -# Lilliefors test for gamma distribution - -## Description -Performs Lilliefors-type goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The implementation estimates gamma parameters from the sample before computing a Kolmogorov-Smirnov type statistic. - -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsGammaGofStatistic, -) - - -test_statistic = LillieforsGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` - -## Arguments -`alpha` - positive shape parameter stored in the statistic hypothesis. Default value is `1.0`. - -`beta` - positive rate parameter stored in the statistic hypothesis. Default value is `1.0`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation estimates gamma parameters with - -$$ \hat\alpha = \frac{\bar X^2}{S^2}, \quad \hat\theta = \frac{S^2}{\bar X}. $$ - -The sorted sample is then transformed by the estimated gamma cumulative distribution function. - -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Lilliefors, H.W. (1967): On the Kolmogorov-Smirnov test for normality with mean and variance unknown. - Journal of the American Statistical Association, vol. 62, pp. 399-402. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsGammaGofStatistic, -) - - -test_statistic = LillieforsGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/gamma/mathematical-validation.md b/docs/criteria/goodness-of-fit/gamma/mathematical-validation.md new file mode 100644 index 00000000..5d4e68d2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/mathematical-validation.md @@ -0,0 +1,200 @@ +# Mathematical verification of Gamma statistics + +Audit date: 2026-10-17. The scope is **all 28 concrete Gamma classes** exported +by `gamma/gamma_statistics.py`: 13 generated EDF, five generated frequency and 10 local classes. +The [catalog](index.md) links every criterion to a page with its exact formula, +constructor example and scientific source. Abstract infrastructure is excluded. + +## Null hypothesis and conventions + +Shape `alfa` and rate `beta` are fixed, finite and positive; origin is zero. +SciPy's scale is `1/beta`. No parameter estimation is performed. +Let $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. +For spacing statistics include $u_0=0$ and $u_{n+1}=1$. +The probability integral transform makes these $u_i$ uniform order statistics +under the specified continuous null. This argument supports applying general +uniform EDF/spacing formulas to Gamma; it does not transfer fitted-model tables. + +## Formula checks + +| Criteria (number of public classes) | Checked definition | Source and qualification | +|---|---|---| +| Kolmogorov–Smirnov D+, D−, D (3) | Positive/negative supremum discrepancies; D is their maximum, without scaling | [Zhang (2002), §2.1](https://doi.org/10.1111/1467-9868.00337) | +| Anderson–Darling (1) | Weighted logarithmic sum, factor 1/n and subtraction of n | [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437); [Zhang, §2.2](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf) | +| Cramér–von Mises (1) | Squared deviations from half-ranks plus 1/(12n) | [Zhang, §2.3](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf) | +| Watson (1) | Centered Cramér–von Mises, subtracting $n(\bar u-1/2)^2$ | [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109); [Lemeshko et al. (2014), eq. (6)](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf) | +| Kuiper, scaled, corrected (3) | $V=D^++D^-$; $\sqrt nV$; $(\sqrt n+0.155+0.24/\sqrt n)V$ | [Lemeshko et al., eqs. (1)–(3)](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf) | +| Zhang K, A, C (3) | Half-rank likelihood ratios and quarter-rank log odds | [Zhang, eqs. (3.1)–(3.3)](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf); Z_C implements the paper's stated approximate form | +| Liao–Shimokawa | Sum of local EDF maxima weighted by $[u_i(1-u_i)]^{-1/2}/\sqrt n$ | [Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965); formula also explicit in [Al-Zahrani (2012), eq. (13)](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf) | +| Pearson, Freeman–Tukey, modified log-likelihood, Neyman, Cressie–Read (5) | Power divergences at $\lambda=1,-1/2,-1,-2,2/3$ | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); explicit zero-count limits | +| Likelihood ratio (1) | $2\sum_{O_j>0}O_j\log(O_j/E_j)$, power-divergence limit at zero | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| Greenwood (1) | Sum of squares of all n+1 spacings | [Does, Helmers and Klaassen (1988), eqs. (1)–(2)](https://ir.cwi.nl/pub/1694/1694D.pdf) | +| Moran (1) | Negative sum of log spacings scaled by n | [Moran (1951)](https://doi.org/10.1111/j.2517-6161.1951.tb00079.x), bibliographic background; the retained normalization is qualified below | +| Probability plot correlation (1) | One minus correlation with Gamma quantiles at $(i-3/8)/(n+1/4)$ | [Filliben (1975)](https://doi.org/10.1080/00401706.1975.10489279), methodological background only; Gamma/Blom variant is a library adaptation | +| Graph edge count, maximum degree, average degree, components, clique number, independence number (6) | Exact graph with edges iff $|u_i-u_j|<(\max u-\min u)/10$ | Related methodology: [Ebner, Nestmann and Schulte (2020 preprint)](https://arxiv.org/abs/1812.08638); this range-based construction and two-tail convention are library definitions | + +## Findings and qualifications + +No mathematical formula change was required for the definitions checked. +This is a verification of statistic calculation, not certification of type-I +error, consistency, or power for all alternatives. + +- **Liao–Shimokawa uses the shared EDF kernel.** The original + Liao–Shimokawa paper studies fitted Weibull/extreme-value models. Its critical + values cannot be reused for the fixed Gamma hypothesis. +- **Moran has a normalization offset.** The code returns + $-\sum\log(nD_j)$, exceeding $-\sum\log((n+1)D_j)$ by + $(n+1)\log((n+1)/n)$. The identity was verified algebraically and on equal + spacings. This does not change rankings at fixed n, but changes critical values. + The primary paper's exact normalization was not verified from accessible full + text; the citation is not used to claim that it specifies the library's factor n. +- **PPCC is not an omnibus fixed-parameter Gamma test.** Correlation eliminates + positive scale and translation of observations. Such alternatives can therefore + leave the statistic unchanged. At n=2 it is zero in exact arithmetic. Its null + distribution depends on shape; normality PPCC tables are not applicable. +- **The six graph statistics are local adaptations.** Graph quantities were + verified against independent enumeration. The referenced paper does not validate + this exact threshold. Affine transformations of u scale both distances and h + identically; compressed uniform positions inside [0,1] give a concrete blind + spot. This is an inference from the implemented rule. Average degree is exactly + twice edge count divided by n, so the two contain the same information at fixed n. +- **Tail selection is part of the definition.** All nongraph statistics reject + large values; graph statistics use both tails. This includes D− and D+ despite + their CDF-direction names. Greenwood's chosen right tail does not test excessive + regularity of spacings. + +Bibliographic verification is distinguished from full-text formula verification. +Zhang, Lemeshko et al., and Does et al. were checked in accessible papers linked +above. For Liao–Shimokawa, the explicit expression was checked in Al-Zahrani's +published application, rather than claiming access to the original full text. +PPCC and graph citations provide background, not evidence for the exact local +Gamma constructions. Every criterion page states its applicable qualification. + +## API and documentation corrections + +Previously there were 18 criterion pages for 29 public classes. Eleven pages, +a complete index and this report have been added, and all pages are in MkDocs +navigation. All 28 examples are executed in the test suite. Broken links to the +absent `gamma-statistics-audit.md` have been replaced. + +Generated frequency constructors use `binning=EqualProbabilityBins(count=k)`, +not `bins=k`. Their default is `PowerCount()` (ceil(2*n**0.4), bounded to 2…1000), +not eight bins. Cressie–Read power is fixed at 2/3. Only the local likelihood-ratio +class retains `bins=k` and the default eight bins. Generated binning configurations +are included in storage keys, whereas likelihood-ratio storage remains blocked. +Watson and Kuiper use the generated short codes `WATSON` and `KUIPER`. +Old tests and documentation expecting the pre-generation interface were corrected. + +The companion `gamma/__init__.pyi` declares all 31 public classes (28 concrete and three +abstract), including dynamically generated criteria, frequency `binning`, legacy +KS options and the local likelihood-ratio `bins` constructor. Regenerate it with +`.venv/bin/python scripts/generate_gamma_stub.py`; use `--check` to detect stale +declarations without importing the package. Public class coverage and declared +constructor signatures were checked against the runtime implementation. + +The package follows the same layout as `continuous/uniform`: numerical +implementations live in `gamma/gamma_statistics.py`, explicit public re-exports +in `gamma/__init__.py`, and generated type declarations in `gamma/__init__.pyi`. +Imports from `continuous.gamma` and class module identities remain unchanged, +including pickle lookup paths for classes. Instance serialization is outside this +check: parameter values currently contain an unpicklable mapping proxy. Internal catalogs are in `gamma_statistics`. + +## Numerical verification + +The isolated focused run passed **960 tests**. Ruff passed for the changed Python +files. MkDocs built successfully; existing missing-link warnings belong to other +distribution sections. All local Gamma links resolve. The focused suite checks: + +- Independent closed-form EDF definitions at four shape/rate pairs, with a + prescribed probability sample, for all 13 generated classes. +- Numerical integration of the step EDF for Anderson–Darling, Cramér–von Mises + and Watson; SciPy one-sample KS in each direction. +- SciPy power-divergence comparisons with positive counts and analytic limits + with empty cells for all six frequency discrepancies, including likelihood ratio. +- Both endpoint spacings, Moran's offset, ties, zeros, and exact exponential + survival identities for the shape-one Gamma upper tail. +- Independent Pearson correlation for PPCC; its affine blind spot and n=2 case. +- NetworkX/brute-force clique and independent-set references for all graph + outputs, including ties, singleton/constant samples and ten random samples. +- Rate/unit invariance for every class, invalid inputs and parameters, unchanged + samples/state, class generation, hypothesis declarations and pickle identity. +- Page/catalog/navigation coverage, all 28 Markdown examples and module doctests. + +Logarithmic implementations avoid cancellation but remain limited by SciPy/float64 +Gamma probability evaluation. Extreme log probabilities can become infinite; +CDF saturation can merge graph positions. No claim of arbitrary-precision tail +accuracy is made. Fixed-bin chi-square approximations need adequate expected +counts; adaptive bins require calibration of their selection process. + +### Numba optimization + +All 28 concrete criteria now dispatch to numerical kernels compiled with +`@jit(nopython=True, cache=True)`. The 18 generated EDF/frequency classes already +used compiled shared kernels. The 10 local classes now have static compiled +`do_execute_statistic` methods. Validation, Gamma CDF/log-CDF/log-survival and +quantile calls remain outside JIT because they use SciPy. There are no module-level +functions in `gamma/gamma_statistics.py`; validation and sorting helpers belong to the base class. +`gamma/__init__.pyi` was regenerated, and its generator removes JIT decorators from stubs. + +Greenwood and Moran accumulate results without temporary spacing, +rank or weight arrays. PPCC uses scaled two-pass moments without modifying its +arguments. The likelihood ratio handles zero counts explicitly. Graph kernels +use the ordering of CDF positions: sliding windows count neighbors and cliques, +adjacent gaps determine components, and greedy selection determines the maximum +independent set. Each graph kernel takes O(n) time and O(1) auxiliary space; +validation, CDF computation and O(n log n) sample sorting precede it. No adjacency +lists are allocated. Strict distance comparisons and the h=0 convention are retained. + +New regressions compare compiled and Python kernel evaluations, check actual +nopython dispatch for every criterion, verify input immutability, and enumerate +graphs at exact threshold distances and their floating-point neighbors. Existing +independent mathematical references continue to pass. No fastmath approximation +is enabled; different summation orders can still change final rounding bits. + +A local warmed run on 2,000 Gamma observations (NumPy RNG seed 2026, shape 2.5, +rate 1.5) measured: + +| Operation | Previous implementation | Optimized | Ratio | +|---|---:|---:|---:| +| Graph edge count, full validation/CDF/statistic call | 82.805 ms | 0.223 ms | 372× | +| Greenwood kernel, precomputed sorted CDF | 7.673 µs | 1.969 µs | 3.9× | + +The graph baseline used the former generic adjacency-list path on the same +transformed sample; the Greenwood baseline used NumPy differences and squared +spacings. Results were checked for equality (graph) or numerical agreement +(Greenwood). Timings are minima of five repeats, with one old graph call, 100 new +graph calls and 1,000 Greenwood calls per repeat, divided by the call count. +JIT compilation was warmed before timing. These are local measurements, not +portable performance guarantees; the first invocation also pays compilation or +cache-loading cost. Greenwood's ratio excludes SciPy CDF computation. + +### Reproducing the focused run + +Ordinary collection is currently blocked by an unrelated obsolete +`AbstractChi2Statistic` import in `exponentiated_weibull.py`, reached through +`continuous/__init__.py`. The following explicit isolation bypasses **only that +package initializer**; it imports the actual Gamma implementation, factories and +kernels. It does not establish that normal package initialization works. +Run from the repository root: + +```bash +.venv/bin/python - <<'PY' +import sys +import types +from pathlib import Path +import pytest + +root = Path.cwd() +sys.path[:0] = [str(root), str(root / 'src')] +name = 'pysatl_criterion.statistics.goodness_of_fit.continuous' +package = types.ModuleType(name) +package.__path__ = [str(root / 'src/pysatl_criterion/statistics/goodness_of_fit/continuous')] +sys.modules[name] = package +raise SystemExit(pytest.main([ + '-q', 'tests/statistics/test_gamma_numba.py', + 'tests/statistics/test_gamma_dynamic.py', + 'tests/distributions/test_gamma.py', + 'tests/distributions/test_gamma_correctness.py', +])) +PY +``` diff --git a/docs/criteria/goodness-of-fit/gamma/min_toshiyuki_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/min_toshiyuki_gamma_criterion.md deleted file mode 100644 index bdc79b8e..00000000 --- a/docs/criteria/goodness-of-fit/gamma/min_toshiyuki_gamma_criterion.md +++ /dev/null @@ -1,48 +0,0 @@ -# Min-Toshiyuki test for gamma distribution - -## Description -Performs Min-Toshiyuki tail-sensitive goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic up-weights empirical distribution deviations near the tails. - -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MinToshiyukiGammaGofStatistic, -) - - -test_statistic = MinToshiyukiGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` - -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. - -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation transforms observations with the gamma cumulative distribution function and passes the resulting values to the common Min-Toshiyuki statistic implementation. - -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.gamma`. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MinToshiyukiGammaGofStatistic, -) - - -test_statistic = MinToshiyukiGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/gamma/modified_log_likelihood_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/modified_log_likelihood_gamma_criterion.md new file mode 100644 index 00000000..fdf53dd2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/modified_log_likelihood_gamma_criterion.md @@ -0,0 +1,44 @@ +# Modified log-likelihood for Gamma + +`ModifiedLogLikelihoodGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Here $O_j$ and $E_j=np_j$ are observed and expected cell counts. With k equal-probability cells, $E_j=n/k$. + +$$ +T=2\sum_j E_j\log(E_j/O_j) +$$ + +Any empty observed cell with positive expectation gives infinity. + +The constructor accepts `binning`, a `BinningStrategy`. The default is `EqualProbabilityBins()` with `PowerCount()`: k is ceil(2*n**0.4), bounded to 2…1000. To fix k, use `EqualProbabilityBins(count=k)`. Counts use the intervals of the transformed CDF; the last interval includes 1. Other strategies use their own null probabilities. Binning configuration is included in storage keys. + +For fixed null-probability bins, use multinomial/Monte Carlo calibration with the same n and bins. The chi-square(k−1) approximation needs sufficiently large expected counts and fixed k; sparse cells or sample-dependent rules require separate calibration. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( + ModifiedLogLikelihoodGammaGofStatistic, +) + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = ModifiedLogLikelihoodGammaGofStatistic( + parameters, binning=EqualProbabilityBins(count=3) +) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/moran_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/moran_gamma_criterion.md index 30a76858..5f95613a 100644 --- a/docs/criteria/goodness-of-fit/gamma/moran_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/moran_gamma_criterion.md @@ -1,52 +1,35 @@ -# Moran test for gamma distribution +# Moran for Gamma -## Description -Performs Moran log-spacing goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic is based on logarithms of spacings after the gamma probability integral transform. +`MoranGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MoranGammaGofStatistic, -) - - -test_statistic = MoranGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +## Definition -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +$$ +M=-\sum_{j=1}^{n+1}\log(nD_j),\quad D_j=u_j-u_{j-1},\ u_0=0,\ u_{n+1}=1 +$$ -`rvs` - array-like sample data passed to `execute_statistic`. +The historical factor n is retained. Relative to scaling every spacing by n+1, the returned value is larger by $(n+1)\log((n+1)/n)$. Calibrate this normalization. Ties and zero observations give infinity. Log-CDF/log-survival differences preserve small spacings until the underlying probabilities themselves become unrepresentable. -## Details -For spacings $D_i$ between consecutive gamma CDF values, the implementation returns +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -$$ M = -\sum_i \log(nD_i). $$ +## Source -Spacings must be strictly positive. +[Moran (1951), The Random Division of an Interval—Part II](https://doi.org/10.1111/j.2517-6161.1951.tb00079.x). -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Moran, P.A.P. (1951): The random division of an interval. - Journal of the Royal Statistical Society, Series B, vol. 13, pp. 147-150. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MoranGammaGofStatistic, -) +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import MoranGammaGofStatistic - -test_statistic = MoranGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = MoranGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/neyman_chi2_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/neyman_chi2_gamma_criterion.md new file mode 100644 index 00000000..9ec2e080 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/neyman_chi2_gamma_criterion.md @@ -0,0 +1,40 @@ +# Neyman modified chi-squared for Gamma + +`NeymanChi2GammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Here $O_j$ and $E_j=np_j$ are observed and expected cell counts. With k equal-probability cells, $E_j=n/k$. + +$$ +T=\sum_j(O_j-E_j)^2/O_j +$$ + +Any empty observed cell with positive expectation gives infinity. + +The constructor accepts `binning`, a `BinningStrategy`. The default is `EqualProbabilityBins()` with `PowerCount()`: k is ceil(2*n**0.4), bounded to 2…1000. To fix k, use `EqualProbabilityBins(count=k)`. Counts use the intervals of the transformed CDF; the last interval includes 1. Other strategies use their own null probabilities. Binning configuration is included in storage keys. + +For fixed null-probability bins, use multinomial/Monte Carlo calibration with the same n and bins. The chi-square(k−1) approximation needs sufficiently large expected counts and fixed k; sparse cells or sample-dependent rules require separate calibration. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import NeymanChi2GammaGofStatistic + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = NeymanChi2GammaGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/probability_plot_correlation_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/probability_plot_correlation_gamma_criterion.md index 1f3dc48d..9064ec2c 100644 --- a/docs/criteria/goodness-of-fit/gamma/probability_plot_correlation_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/probability_plot_correlation_gamma_criterion.md @@ -1,49 +1,37 @@ -# Probability plot correlation test for gamma distribution +# Probability plot correlation for Gamma -## Description -Performs probability plot correlation coefficient goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The statistic measures linear alignment between ordered sample values and theoretical gamma quantiles. +`ProbabilityPlotCorrelationGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ProbabilityPlotCorrelationGammaGofStatistic, -) +## Definition +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -test_statistic = ProbabilityPlotCorrelationGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` +$$ +T=1-\operatorname{corr}(x_{(i)},q_i),\quad q_i=F_{\alpha,1}^{-1}\left(\frac{i-3/8}{n+1/4}\right) +$$ -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +The citation supplies methodological background, not validation of this Gamma/Blom variant. The rate cancels from correlation. Positive affine transformations of the sample leave the statistic unchanged, so it cannot detect scale or location alternatives within the allowed support. Requires at least two nonconstant observations; at n=2 it is identically zero in exact arithmetic. Its null law depends on shape. Normality tables must not be reused. -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -`rvs` - array-like sample data passed to `execute_statistic`. +## Source -## Details -The implementation computes plotting positions, evaluates theoretical gamma quantiles, and returns one minus the correlation coefficient between the ordered sample and the expected quantiles. -Values near zero indicate stronger linear alignment with the gamma model. +[Filliben (1975), The Probability Plot Correlation Coefficient Test for Normality](https://doi.org/10.1080/00401706.1975.10489279). -## Author(s) -Sergey Golovachev, Alexey Mironov - -## References -Filliben, J.J. (1975): The probability plot correlation coefficient test for normality. - Technometrics, vol. 17, pp. 111-117. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ( ProbabilityPlotCorrelationGammaGofStatistic, ) - -test_statistic = ProbabilityPlotCorrelationGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = ProbabilityPlotCorrelationGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/watson_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/watson_gamma_criterion.md index 53cfff18..c7ae4eb3 100644 --- a/docs/criteria/goodness-of-fit/gamma/watson_gamma_criterion.md +++ b/docs/criteria/goodness-of-fit/gamma/watson_gamma_criterion.md @@ -1,49 +1,35 @@ -# Watson test for gamma distribution +# Watson for Gamma -## Description -Performs Watson goodness-of-fit test for the hypothesis that the sample comes from a gamma distribution. -The Watson statistic is a centered modification of the Cramer-von Mises statistic. +`WatsonGammaGofStatistic` -Hypothesis of Gamma Distribution -The null hypothesis is that the data comes from a gamma distribution with positive shape parameter `alpha` and positive rate parameter `beta`. +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WatsonGammaGofStatistic, -) +## Definition +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. -test_statistic = WatsonGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) -``` - -## Arguments -`alpha` - positive shape parameter of the gamma distribution. Default value is `1.0`. +$$ +U^2=W^2-n(\bar u-1/2)^2 +$$ -`beta` - positive rate parameter of the gamma distribution. Default value is `1.0`. +Computed as a centered sum of squares to avoid cancellation. The current short code is `WATSON`. -`rvs` - array-like sample data passed to `execute_statistic`. +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. -## Details -The implementation computes Cramer-von Mises terms from gamma CDF values and subtracts the Watson centering correction. -Large values indicate stronger deviation from the gamma model. +## Source -## Author(s) -Sergey Golovachev, Alexey Mironov +[Lemeshko et al. (2014), eqs. (1)–(6)](https://doi.org/10.3103/S875669901401004X); [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109).. -## References -Watson, G.S. (1961): Goodness-of-fit tests on a circle. - Biometrika, vol. 48, pp. 109-114. +## Usage -## Examples ```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WatsonGammaGofStatistic, -) - +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import WatsonGammaGofStatistic -test_statistic = WatsonGammaGofStatistic(alpha=2, beta=1) -statistic_result = test_statistic.execute_statistic([0.42, 0.77, 1.05, 1.48, 1.96, 2.34, 3.12]) -print(statistic_result) +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = WatsonGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) ``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/zhang_a_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/zhang_a_gamma_criterion.md new file mode 100644 index 00000000..9492147e --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/zhang_a_gamma_criterion.md @@ -0,0 +1,35 @@ +# Zhang A for Gamma + +`ZhangAGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +Z_A=-\sum_i\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right] +$$ + +Computed using logarithmic probabilities; zero observations give infinity. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ZhangAGammaGofStatistic + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = ZhangAGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/zhang_c_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/zhang_c_gamma_criterion.md new file mode 100644 index 00000000..a39e4993 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/zhang_c_gamma_criterion.md @@ -0,0 +1,35 @@ +# Zhang C for Gamma + +`ZhangCGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +Z_C=\sum_i\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2 +$$ + +Computed using logarithmic probabilities; zero observations give infinity. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ZhangCGammaGofStatistic + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = ZhangCGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/gamma/zhang_k_gamma_criterion.md b/docs/criteria/goodness-of-fit/gamma/zhang_k_gamma_criterion.md new file mode 100644 index 00000000..15826fa2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/gamma/zhang_k_gamma_criterion.md @@ -0,0 +1,35 @@ +# Zhang K for Gamma + +`ZhangKGammaGofStatistic` + +Use fixed positive shape `alfa` and **rate** `beta` (SciPy scale is `1/beta`), with origin zero. Both parameters must be supplied; no fitting occurs. Samples must be finite, real, nonempty, one-dimensional and nonnegative. Zero is accepted as a support boundary. Ties are allowed unless they make the statistic infinite or degenerate. + +## Definition + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$. Define $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +Z_K=\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right],\quad r_i=i-1/2 +$$ + +Computed using logarithmic probabilities; zero observations give infinity. + +Large values oppose the null (right tail). `execute_statistic` returns a scalar, not a p-value. The sample is not modified. + +## Source + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337). + +## Usage + +```python +from pysatl_criterion.distribution import GammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.gamma import ZhangKGammaGofStatistic + +parameters = GammaDistributionDescriptor.DEFAULT.parse({"alfa": 2.5, "beta": 1.5}) +statistic = ZhangKGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.7, 1.3, 2.1, 3.4]) +``` + +See the [Gamma catalog](index.md) and [mathematical verification](mathematical-validation.md) +for calibration, numerical limits and the scope of scientific attribution. diff --git a/docs/criteria/goodness-of-fit/hyperbolic/anderson_darling_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/anderson_darling_hyperbolic_criterion.md new file mode 100644 index 00000000..450936d5 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/anderson_darling_hyperbolic_criterion.md @@ -0,0 +1,47 @@ +# AndersonDarling: гиперболическое распределение + +`AndersonDarlingHyperbolicGofStatistic` проверяет iid-выборку из полностью заданного +гиперболического распределения на R. Параметры фиксированы: +все четыре значения `alpha`, `beta`, `delta`, `mu` необходимо задать явно; +`alpha > abs(beta)`, `delta > 0`, все параметры — конечные вещественные скаляры. +Подгонки параметров нет. + +Для отсортированных наблюдений `u_i=F(x_(i))`, `i=1,...,n`: + +`A²=−n−Σ(2i−1)/n·[log(u_i)+log(1−u_(n+1−i))]`. + +Дополнительных поправок нет. Критическая область — большие значения. +Минимум одно конечное вещественное наблюдение; повторы и константы допустимы. +Невалидные выборки вызывают `ValueError`, обнаруженные численные ошибки CDF — +`FloatingPointError`. Вызов возвращает `float`, вход не изменяется, +дополнительные kwargs игнорируются. + +Logcdf и logsf вычисляются отдельно. Численное обнуление хвоста +вызывает `FloatingPointError`: точная статистика конечна для конечных данных. + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + AndersonDarlingHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0.2, "delta": 1, "mu": 0} +) +statistic = AndersonDarlingHyperbolicGofStatistic(parameters) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) +assert isinstance(value, float) and value >= 0 +``` + +[Общий EDF-источник](https://doi.org/10.1214/aoms/1177729437) применяется через преобразование +известной непрерывной CDF; это не источник о подгонке гиперболической модели. +Нулевой закон зависит от размера выборки, но не от фиксированных параметров. +Встроенный Monte Carlo resolver не имеет гиперболического генератора. +Для внешнего моделирования используйте `genhyperbolic(p=1, a=alpha*delta, +b=beta*delta, loc=mu, scale=delta)` и вызывайте `execute_statistic` на каждой выборке. + +[Полный аудит, ограничения источников и требования к калибровке](mathematical-validation.md). + +[Каталог критериев](index.md). + +Проверенная вычислительная формула: [Zhang (2002), §2.2](https://doi.org/10.1111/1467-9868.00337), [полный текст](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/chi2_pearson_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/chi2_pearson_hyperbolic_criterion.md new file mode 100644 index 00000000..599ffdd5 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/chi2_pearson_hyperbolic_criterion.md @@ -0,0 +1,67 @@ +# Pearson χ²: гиперболическое распределение + +`Chi2PearsonHyperbolicGofStatistic` (`CHI2_PEARSON_HYPERBOLIC_GOODNESS_OF_FIT`) проверяет +полностью заданную гиперболическую iid-модель на вещественной оси. +Все параметры заданы заранее: конечные `alpha > abs(beta)`, `delta > 0`, `mu`. +Неизвестные параметры и их оценивание этим классом не поддерживаются. + +Пусть `O_j` — наблюдаемая частота, `E_j=n p_j>0` — ожидаемая частота в +j-й ячейке, `p_j` — её вероятность под нулевой гипотезой. +Обе суммы частот равны n. Статистика: + +`T = Σ(O_j−E_j)²/E_j`. + +Критическая область правая: большие T свидетельствуют против гипотезы. +Пустая ячейка вносит E_j. + +## Разбиение и калибровка + +Конструктор принимает `parameters` и необязательный `binning`. +По умолчанию используется `EqualProbabilityBins()`: наблюдения преобразуются +известной CDF, а `[0,1]` разбивается на равновероятные ячейки; `E_j=n/k`. +Количество ячеек выбирается общим правилом `PowerCount`, минимум две. +Пример ниже фиксирует две ячейки явно. + +Можно передать другие [стратегии разбиения](../binning/index.md), включая +`ExplicitBins` с границами, покрывающими весь носитель. Внутренняя граница +принадлежит ячейке справа; последняя включает правый конец. +Правила разбиения, числа ячеек и объединения входят в конфигурацию калибровки. + +Нужна непустая одномерная конечная вещественная выборка. Повторы и константы +допустимы; вход не изменяется. Это не гарантирует точности асимптотической +калибровки при малом числе наблюдений. Для заранее фиксированных k ячеек с +положительными вероятностями и известными параметрами применима асимптотика +χ² с k−1 степенями свободы. Для малых ожидаемых частот или адаптивных границ +нужно моделирование, воспроизводящее весь алгоритм разбиения. +Встроенный resolver не имеет гиперболического генератора: моделируйте внешне +через `scipy.stats.genhyperbolic(p=1, a=alpha*delta, b=beta*delta, loc=mu, scale=delta)`. +Класс возвращает статистику, а не p-value. Численные ошибки вероятностей +при построении таблицы приводят к исключению, не к скрытому clipping. + +## Пример + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + Chi2PearsonHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0, "delta": 1, "mu": 0} +) +criterion = Chi2PearsonHyperbolicGofStatistic(parameters, binning=EqualProbabilityBins(count=2)) +value = criterion.execute_statistic([-2.0, -1.0, -0.5, 1.0]) +assert isinstance(value, float) and value >= 0 +``` + +## Научный источник + +[Cressie N., Read T. R. C. (1984), Multinomial Goodness-of-Fit Tests, +JRSS B 46(3), 440–464](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x): +семейство power divergence при `λ=1`. +[Полный текст](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). +Применение к гиперболической модели использует вероятности её ячеек; +выбор конкретной стратегии разбиения является настройкой библиотеки. + +[Все критерии](index.md) · [Математическая проверка](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/cramer_von_mises_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/cramer_von_mises_hyperbolic_criterion.md new file mode 100644 index 00000000..87ed75bc --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/cramer_von_mises_hyperbolic_criterion.md @@ -0,0 +1,45 @@ +# CramerVonMises: гиперболическое распределение + +`CramerVonMisesHyperbolicGofStatistic` проверяет iid-выборку из полностью заданного +гиперболического распределения на R. Параметры фиксированы: +все четыре значения `alpha`, `beta`, `delta`, `mu` необходимо задать явно; +`alpha > abs(beta)`, `delta > 0`, все параметры — конечные вещественные скаляры. +Подгонки параметров нет. + +Для отсортированных наблюдений `u_i=F(x_(i))`, `i=1,...,n`: + +`W²=1/(12n)+Σ(u_i−(2i−1)/(2n))²`. + +Дополнительных поправок нет. Критическая область — большие значения. +Минимум одно конечное вещественное наблюдение; повторы и константы допустимы. +Невалидные выборки вызывают `ValueError`, обнаруженные численные ошибки CDF — +`FloatingPointError`. Вызов возвращает `float`, вход не изменяется, +дополнительные kwargs игнорируются. + + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + CramerVonMisesHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0.2, "delta": 1, "mu": 0} +) +statistic = CramerVonMisesHyperbolicGofStatistic(parameters) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) +assert isinstance(value, float) and value >= 0 +``` + +[Общий EDF-источник](https://doi.org/10.1214/aoms/1177729437) применяется через преобразование +известной непрерывной CDF; это не источник о подгонке гиперболической модели. +Нулевой закон зависит от размера выборки, но не от фиксированных параметров. +Встроенный Monte Carlo resolver не имеет гиперболического генератора. +Для внешнего моделирования используйте `genhyperbolic(p=1, a=alpha*delta, +b=beta*delta, loc=mu, scale=delta)` и вызывайте `execute_statistic` на каждой выборке. + +[Полный аудит, ограничения источников и требования к калибровке](mathematical-validation.md). + +[Каталог критериев](index.md). + +Проверенная вычислительная формула: [Zhang (2002), §2.3](https://doi.org/10.1111/1467-9868.00337), [полный текст](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/cressie_read_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/cressie_read_hyperbolic_criterion.md new file mode 100644 index 00000000..e70f6f02 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/cressie_read_hyperbolic_criterion.md @@ -0,0 +1,67 @@ +# Cressie–Read: гиперболическое распределение + +`CressieReadHyperbolicGofStatistic` (`CRESSIE_READ_HYPERBOLIC_GOODNESS_OF_FIT`) проверяет +полностью заданную гиперболическую iid-модель на вещественной оси. +Все параметры заданы заранее: конечные `alpha > abs(beta)`, `delta > 0`, `mu`. +Неизвестные параметры и их оценивание этим классом не поддерживаются. + +Пусть `O_j` — наблюдаемая частота, `E_j=n p_j>0` — ожидаемая частота в +j-й ячейке, `p_j` — её вероятность под нулевой гипотезой. +Обе суммы частот равны n. Статистика: + +`T = (9/5) Σ O_j [(O_j/E_j)^(2/3)−1]`. + +Критическая область правая: большие T свидетельствуют против гипотезы. +При O_j=0 соответствующее слагаемое равно нулю по непрерывности. + +## Разбиение и калибровка + +Конструктор принимает `parameters` и необязательный `binning`. +По умолчанию используется `EqualProbabilityBins()`: наблюдения преобразуются +известной CDF, а `[0,1]` разбивается на равновероятные ячейки; `E_j=n/k`. +Количество ячеек выбирается общим правилом `PowerCount`, минимум две. +Пример ниже фиксирует две ячейки явно. + +Можно передать другие [стратегии разбиения](../binning/index.md), включая +`ExplicitBins` с границами, покрывающими весь носитель. Внутренняя граница +принадлежит ячейке справа; последняя включает правый конец. +Правила разбиения, числа ячеек и объединения входят в конфигурацию калибровки. + +Нужна непустая одномерная конечная вещественная выборка. Повторы и константы +допустимы; вход не изменяется. Это не гарантирует точности асимптотической +калибровки при малом числе наблюдений. Для заранее фиксированных k ячеек с +положительными вероятностями и известными параметрами применима асимптотика +χ² с k−1 степенями свободы. Для малых ожидаемых частот или адаптивных границ +нужно моделирование, воспроизводящее весь алгоритм разбиения. +Встроенный resolver не имеет гиперболического генератора: моделируйте внешне +через `scipy.stats.genhyperbolic(p=1, a=alpha*delta, b=beta*delta, loc=mu, scale=delta)`. +Класс возвращает статистику, а не p-value. Численные ошибки вероятностей +при построении таблицы приводят к исключению, не к скрытому clipping. + +## Пример + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + CressieReadHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0, "delta": 1, "mu": 0} +) +criterion = CressieReadHyperbolicGofStatistic(parameters, binning=EqualProbabilityBins(count=2)) +value = criterion.execute_statistic([-2.0, -1.0, -0.5, 1.0]) +assert isinstance(value, float) and value >= 0 +``` + +## Научный источник + +[Cressie N., Read T. R. C. (1984), Multinomial Goodness-of-Fit Tests, +JRSS B 46(3), 440–464](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x): +семейство power divergence при `λ=2/3`. +[Полный текст](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). +Применение к гиперболической модели использует вероятности её ячеек; +выбор конкретной стратегии разбиения является настройкой библиотеки. + +[Все критерии](index.md) · [Математическая проверка](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/freeman_tukey_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/freeman_tukey_hyperbolic_criterion.md new file mode 100644 index 00000000..8fb671c2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/freeman_tukey_hyperbolic_criterion.md @@ -0,0 +1,67 @@ +# Freeman–Tukey: гиперболическое распределение + +`FreemanTukeyHyperbolicGofStatistic` (`FREEMAN_TUKEY_HYPERBOLIC_GOODNESS_OF_FIT`) проверяет +полностью заданную гиперболическую iid-модель на вещественной оси. +Все параметры заданы заранее: конечные `alpha > abs(beta)`, `delta > 0`, `mu`. +Неизвестные параметры и их оценивание этим классом не поддерживаются. + +Пусть `O_j` — наблюдаемая частота, `E_j=n p_j>0` — ожидаемая частота в +j-й ячейке, `p_j` — её вероятность под нулевой гипотезой. +Обе суммы частот равны n. Статистика: + +`T = 4 Σ(√O_j−√E_j)²`. + +Критическая область правая: большие T свидетельствуют против гипотезы. +Пустая ячейка вносит 4E_j. + +## Разбиение и калибровка + +Конструктор принимает `parameters` и необязательный `binning`. +По умолчанию используется `EqualProbabilityBins()`: наблюдения преобразуются +известной CDF, а `[0,1]` разбивается на равновероятные ячейки; `E_j=n/k`. +Количество ячеек выбирается общим правилом `PowerCount`, минимум две. +Пример ниже фиксирует две ячейки явно. + +Можно передать другие [стратегии разбиения](../binning/index.md), включая +`ExplicitBins` с границами, покрывающими весь носитель. Внутренняя граница +принадлежит ячейке справа; последняя включает правый конец. +Правила разбиения, числа ячеек и объединения входят в конфигурацию калибровки. + +Нужна непустая одномерная конечная вещественная выборка. Повторы и константы +допустимы; вход не изменяется. Это не гарантирует точности асимптотической +калибровки при малом числе наблюдений. Для заранее фиксированных k ячеек с +положительными вероятностями и известными параметрами применима асимптотика +χ² с k−1 степенями свободы. Для малых ожидаемых частот или адаптивных границ +нужно моделирование, воспроизводящее весь алгоритм разбиения. +Встроенный resolver не имеет гиперболического генератора: моделируйте внешне +через `scipy.stats.genhyperbolic(p=1, a=alpha*delta, b=beta*delta, loc=mu, scale=delta)`. +Класс возвращает статистику, а не p-value. Численные ошибки вероятностей +при построении таблицы приводят к исключению, не к скрытому clipping. + +## Пример + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + FreemanTukeyHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0, "delta": 1, "mu": 0} +) +criterion = FreemanTukeyHyperbolicGofStatistic(parameters, binning=EqualProbabilityBins(count=2)) +value = criterion.execute_statistic([-2.0, -1.0, -0.5, 1.0]) +assert isinstance(value, float) and value >= 0 +``` + +## Научный источник + +[Cressie N., Read T. R. C. (1984), Multinomial Goodness-of-Fit Tests, +JRSS B 46(3), 440–464](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x): +семейство power divergence при `λ=−1/2`. +[Полный текст](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). +Применение к гиперболической модели использует вероятности её ячеек; +выбор конкретной стратегии разбиения является настройкой библиотеки. + +[Все критерии](index.md) · [Математическая проверка](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/index.md b/docs/criteria/goodness-of-fit/hyperbolic/index.md new file mode 100644 index 00000000..775cd00a --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/index.md @@ -0,0 +1,27 @@ +# Критерии гиперболического распределения + +Пакет `pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic` +экспортирует базовый `AbstractHyperbolicGofStatistic` и одиннадцать конкретных критериев: шесть EDF и пять частотных. +Все проверяют полностью заданную непрерывную iid-модель на всей вещественной оси. +Задайте все четыре параметра явно: `alpha > abs(beta)`, `delta > 0`, конечный `mu`. +Неуказанные параметры считаются неизвестными; составная гипотеза не поддерживается. + +| Публичный класс и описание | Полный код | +| --- | --- | +| [AndersonDarlingHyperbolicGofStatistic](anderson_darling_hyperbolic_criterion.md) | `AD_HYPERBOLIC_GOODNESS_OF_FIT` | +| [CramerVonMisesHyperbolicGofStatistic](cramer_von_mises_hyperbolic_criterion.md) | `CVM_HYPERBOLIC_GOODNESS_OF_FIT` | +| [KolmogorovSmirnovHyperbolicGofStatistic](kolmogorov_smirnov_hyperbolic_criterion.md) | `KS_HYPERBOLIC_GOODNESS_OF_FIT` | +| [KuiperHyperbolicGofStatistic](kuiper_hyperbolic_criterion.md) | `KUI_HYPERBOLIC_GOODNESS_OF_FIT` | +| [LiaoShimokawaHyperbolicGofStatistic](liao_shimokawa_hyperbolic_criterion.md) | `LIAO_SHIMOKAWA_HYPERBOLIC_GOODNESS_OF_FIT` | +| [WatsonHyperbolicGofStatistic](watson_hyperbolic_criterion.md) | `WAT_HYPERBOLIC_GOODNESS_OF_FIT` | +| [Chi2PearsonHyperbolicGofStatistic](chi2_pearson_hyperbolic_criterion.md) | `CHI2_PEARSON_HYPERBOLIC_GOODNESS_OF_FIT` | +| [FreemanTukeyHyperbolicGofStatistic](freeman_tukey_hyperbolic_criterion.md) | `FREEMAN_TUKEY_HYPERBOLIC_GOODNESS_OF_FIT` | +| [ModifiedLogLikelihoodHyperbolicGofStatistic](modified_log_likelihood_hyperbolic_criterion.md) | `MODIFIED_LOG_LIKELIHOOD_HYPERBOLIC_GOODNESS_OF_FIT` | +| [NeymanChi2HyperbolicGofStatistic](neyman_chi2_hyperbolic_criterion.md) | `CHI2_NEYMAN_HYPERBOLIC_GOODNESS_OF_FIT` | +| [CressieReadHyperbolicGofStatistic](cressie_read_hyperbolic_criterion.md) | `CRESSIE_READ_HYPERBOLIC_GOODNESS_OF_FIT` | + +Все критерии отклоняют гипотезу при больших значениях статистики. +KS вычисляет двустороннее расстояние D; шесть EDF-классов генерируются EDF-фабрикой. +Частотные критерии генерируются общей frequency-фабрикой и принимают `binning`. + +[Математическая проверка, совместимость и измерения](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/kolmogorov_smirnov_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/kolmogorov_smirnov_hyperbolic_criterion.md new file mode 100644 index 00000000..9a20ba1c --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/kolmogorov_smirnov_hyperbolic_criterion.md @@ -0,0 +1,48 @@ +# KolmogorovSmirnov: гиперболическое распределение + +`KolmogorovSmirnovHyperbolicGofStatistic` проверяет iid-выборку из полностью заданного +гиперболического распределения на R. Параметры фиксированы: +все четыре значения `alpha`, `beta`, `delta`, `mu` необходимо задать явно; +`alpha > abs(beta)`, `delta > 0`, все параметры — конечные вещественные скаляры. +Подгонки параметров нет. + +Для отсортированных наблюдений `u_i=F(x_(i))`, `i=1,...,n`: + +`D=max(D+,D−), D+=max(i/n−u_i), D−=max(u_i−(i−1)/n)`. + +Дополнительных поправок нет. Критическая область — большие значения. +Минимум одно конечное вещественное наблюдение; повторы и константы допустимы. +Невалидные выборки вызывают `ValueError`, обнаруженные численные ошибки CDF — +`FloatingPointError`. Вызов возвращает `float`, вход не изменяется, +дополнительные kwargs игнорируются. + +Класс генерируется из `AbstractKSStatistic` и вычисляет двустороннее расстояние D. +Конструктор принимает только `parameters`; прежние `alternative_type` и `mode` +удалены при унификации с общей EDF-фабрикой. + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + KolmogorovSmirnovHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0.2, "delta": 1, "mu": 0} +) +statistic = KolmogorovSmirnovHyperbolicGofStatistic(parameters) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) +assert isinstance(value, float) and value >= 0 +``` + +[Общий EDF-источник](https://doi.org/10.1214/aoms/1177730256) применяется через преобразование +известной непрерывной CDF; это не источник о подгонке гиперболической модели. +Нулевой закон зависит от размера выборки, но не от фиксированных параметров. +Встроенный Monte Carlo resolver не имеет гиперболического генератора. +Для внешнего моделирования используйте `genhyperbolic(p=1, a=alpha*delta, +b=beta*delta, loc=mu, scale=delta)` и вызывайте `execute_statistic` на каждой выборке. + +[Полный аудит, ограничения источников и требования к калибровке](mathematical-validation.md). + +[Каталог критериев](index.md). + +Проверенная вычислительная формула: [Zhang (2002), §2.1](https://doi.org/10.1111/1467-9868.00337), [полный текст](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/kuiper_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/kuiper_hyperbolic_criterion.md new file mode 100644 index 00000000..1f790e7a --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/kuiper_hyperbolic_criterion.md @@ -0,0 +1,47 @@ +# Kuiper: гиперболическое распределение + +`KuiperHyperbolicGofStatistic` проверяет iid-выборку из полностью заданного +гиперболического распределения на R. Параметры фиксированы: +все четыре значения `alpha`, `beta`, `delta`, `mu` необходимо задать явно; +`alpha > abs(beta)`, `delta > 0`, все параметры — конечные вещественные скаляры. +Подгонки параметров нет. + +Для отсортированных наблюдений `u_i=F(x_(i))`, `i=1,...,n`: + +`V=D++D−, D+=max(i/n−u_i), D−=max(u_i−(i−1)/n)`. + +Дополнительных поправок нет. Критическая область — большие значения. +Минимум одно конечное вещественное наблюдение; повторы и константы допустимы. +Невалидные выборки вызывают `ValueError`, обнаруженные численные ошибки CDF — +`FloatingPointError`. Вызов возвращает `float`, вход не изменяется, +дополнительные kwargs игнорируются. + + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + KuiperHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0.2, "delta": 1, "mu": 0} +) +statistic = KuiperHyperbolicGofStatistic(parameters) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) +assert isinstance(value, float) and value >= 0 +``` + +[Общий EDF-источник](https://doi.org/10.1016/S1385-7258(60)50006-0) применяется через преобразование +известной непрерывной CDF; это не источник о подгонке гиперболической модели. +Нулевой закон зависит от размера выборки, но не от фиксированных параметров. +Встроенный Monte Carlo resolver не имеет гиперболического генератора. +Для внешнего моделирования используйте `genhyperbolic(p=1, a=alpha*delta, +b=beta*delta, loc=mu, scale=delta)` и вызывайте `execute_statistic` на каждой выборке. + +[Полный аудит, ограничения источников и требования к калибровке](mathematical-validation.md). + +[Каталог критериев](index.md). + +Проверенная вычислительная формула: [Lemeshko et al. (2014), формула (1)](https://doi.org/10.3103/S875669901401004X), [полный текст](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +При `n=1` статистика тождественно равна `1` и не различает альтернативы. diff --git a/docs/criteria/goodness-of-fit/hyperbolic/liao_shimokawa_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/liao_shimokawa_hyperbolic_criterion.md new file mode 100644 index 00000000..e79eca3e --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/liao_shimokawa_hyperbolic_criterion.md @@ -0,0 +1,31 @@ +# Liao–Shimokawa для гиперболического распределения + +`LiaoShimokawaHyperbolicGofStatistic` создаётся через `_edf_factory.py` +и использует общее ядро `AbstractLiaoShimokawaStatistic` из `edf.py`. +Код: `LIAO_SHIMOKAWA_HYPERBOLIC_GOODNESS_OF_FIT`. + +Все четыре параметра гиперболического распределения фиксированы заранее. +Для отсортированных наблюдений и значений CDF $u_i=F(x_{(i)})$: + +$$ +L_n=\frac1{\sqrt n}\sum_{i=1}^n +\frac{\max(i/n-u_i,\ u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}}. +$$ + +Большие значения статистики служат основанием для отклонения гипотезы. +Для вычисления весов используются логарифмы CDF и функции выживания. +Калибровка должна соответствовать полностью заданной гиперболической гипотезе. + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + LiaoShimokawaHyperbolicGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.5, "beta": 0.25, "delta": 2, "mu": 0}) +criterion = LiaoShimokawaHyperbolicGofStatistic(parameters) +value = criterion.execute_statistic([-2, -0.5, 0, 0.7, 2]) +``` + +Описание общего ядра: Liao and Shimokawa (1999), +[статья](https://doi.org/10.1080/00949659908811965). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/mathematical-validation.md b/docs/criteria/goodness-of-fit/hyperbolic/mathematical-validation.md new file mode 100644 index 00000000..ba81e171 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/mathematical-validation.md @@ -0,0 +1,265 @@ +# Проверка гиперболических критериев + +## Область проверки и источники + +Семейство содержит одиннадцать конкретных классов из [каталога](index.md): +шесть EDF-критериев и пять частотных, создаваемых соответствующими фабриками. + +При `gamma=sqrt(alpha²-beta²)` классическая плотность имеет вид + +`f(x)=gamma/(2*alpha*delta*K₁(delta*gamma)) * exp(-alpha*hypot(delta,x-mu)+beta*(x-mu))`. + +Соответствие `genhyperbolic(p=1, a=alpha*delta, b=beta*delta, loc=mu, scale=delta)` +проверено по [документации SciPy](https://docs.scipy.org/doc/scipy-1.16.1/reference/generated/scipy.stats.genhyperbolic.html) +и независимым интегрированием этой плотности. Носитель — вся вещественная ось. +Масштабированные параметры должны быть конечными и удовлетворять `a > abs(b)`. + +Научные ссылки: + +- [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256): KS. +- [Anderson–Darling (1952)](https://doi.org/10.1214/aoms/1177729437): интегральные EDF-критерии. +- [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0): круговая статистика. +- [Watson (1961)](https://academic.oup.com/biomet/article-abstract/48/1-2/109/225627): центрированная круговая статистика. + +Полные тексты ранних работ Smirnov, Anderson–Darling, Kuiper и Watson +не использовались для построчной проверки. Вычислительные формулы сверены +с доступными полными текстами научных статей: + +- [Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio, + JRSS B 64(2), 281–294](https://doi.org/10.1111/1467-9868.00337), + [PDF, страница 283, §§2.1–2.3](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + В §2.1 записан квадрат KS; реализация возвращает само расстояние D. + Формула AD эквивалентна после замены индекса в сумме log-SF; + CVM совпадает с §2.3, включая `1/(12n)`. +- [Lemeshko, Gorbunov, Lemeshko, Rogozhnikov (2014), Solving Problems of Using + Some Nonparametric Goodness-of-Fit Tests, 50, 21–35](https://doi.org/10.3103/S875669901401004X), + [PDF, страницы 22–23, формулы (1) и (6)](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + Kuiper совпадает с (1), без масштабирования из (2)–(4). + Watson совпадает с (6), без модификации (8). + +Это общие EDF-критерии, применённые к известной гиперболической CDF. +Статьи не подтверждают калибровку модели с оценёнными гиперболическими параметрами. +Аудит проверяет вычисление статистик, а не мощность против всех альтернатив +или точность конечновыборочных p-value. + +## Формулы и независимые проверки + +Пусть `u_i=F(x_(i))`, `i=1,...,n`, `d_i=u_i-(i-1/2)/n`. + +| Критерий | Реализованная статистика | Независимая проверка | +| --- | --- | --- | +| KS | `max(D+,D−)`; `D+=max(i/n-u_i)`, `D−=max(u_i-(i-1)/n)` | SciPy KS и CDF из интеграла плотности | +| CVM | `1/(12n)+Σd_i²` | Формула и интеграл квадрата отклонения EDF | +| AD | `−n−Σ(2i−1)/n [log(u_i)+log(1-u_(n+1−i))]` | Раздельные интегралы плотности в левом и правом хвостах; взвешенный EDF-интеграл | +| Kuiper | `D++D−` | Независимые односторонние KS-расстояния | +| Liao–Shimokawa | `Σ max(i/n−u_i, u_i−(i−1)/n) / sqrt(u_i(1−u_i)) / sqrt(n)` | Независимая ранговая формула и CDF SciPy | +| Watson | `1/(12n)+Σ(d_i−mean(d))²` | Центрированный EDF-интеграл и эквивалентность `W²−n(mean(u)−1/2)²` | + +Во всех случаях критическая область правая. Множители соответствуют формулам +в таблице; дополнительные поправки для конечной выборки не применяются. KS вычисляет двустороннее расстояние D. + +## Границы и калибровка + +Принимается непустая одномерная конечная вещественная выборка, включая один +элемент, повторы и константы. Вход не изменяется. NaN, бесконечности, комплексные +и маскированные наблюдения отвергаются. Некорректные вероятности вызывают +`FloatingPointError`. AD использует непосредственные log-CDF/log-SF: +вычитание округлённой CDF из единицы не используется. При `x=40` статистика +остаётся конечной; при потере представимости хвоста выдаётся явная ошибка. +Произвольно далёкие хвосты и почти вырожденные параметры ограничены точностью SciPy. +Скрытого clipping и точного Python-fallback нет. Вычисление CDF остаётся в SciPy, +поскольку это численное интегрирование, а не арифметическое EDF-ядро. + +Все четыре параметра необходимо задать явно. Частично заданные гипотезы +отвергаются; оценки параметров не вычисляются и не сохраняются. +При полностью заданной непрерывной iid-модели преобразование известной CDF +даёт равномерные `u_i`: калибровка EDF зависит от `n`, но не от параметров. +Для частотных критериев это верно при равновероятных ячейках и заданном правиле +их числа; для произвольных фиксированных границ закон зависит от вероятностей ячеек. +Для составной гипотезы нужна отдельная реализация оценивания и повторная подгонка +на каждой моделируемой выборке. Существующие таблицы нельзя переносить на неё. +Округлённые/дискретизированные данные требуют воспроизведения механизма наблюдения. +Встроенный Monte Carlo resolver не имеет гиперболического генератора; +используйте внешнее моделирование. + +## Независимая численная проверка + +Проверки из `tests/distributions/test_hyperbolic_correctness.py` используют +публичный `execute_statistic`, включая реальные CDF и логарифмические хвосты: + +- Нормировка классической плотности и интегрирование обоих хвостов проверены + при `(alpha,beta,delta,mu)` = `(2,0.3,1.5,-0.5)`, `(1,0,1,0)`, + `(1.8,-1.2,0.7,0.8)`, `(1,0.9,0.4,-1)`. Это симметричная модель, + обе стороны асимметрии и случай близких `alpha` и `abs(beta)`. +- Три вида выборки для каждого набора: один элемент, константа, разные значения. + Вероятности вычисляются квадратурой классической плотности независимо + от преобразования параметров `scipy.stats.genhyperbolic`. +- Публичные CVM, AD и Watson сопоставлены с численным интегрированием + соответствующих отклонений EDF по `[0,1]`, с разбиением в наблюдаемых вероятностях. + Для KS/Kuiper использованы односторонние статистики SciPy; CVM дополнительно + сопоставлен с `scipy.stats.cramervonmises` при `n >= 2` (ограничение SciPy). +- Все пять критериев сохраняют результат при согласованном изменении + масштаба и сдвига данных и параметров, а также при отражении со сменой знака beta. +- При одном наблюдении Kuiper равен 1, Watson равен 1/12 независимо от данных. + Эти два критерия при `n=1` не имеют различающей способности. + +Допуски для публичных значений: `rel=1e-9`, `abs=1e-11`. +Это численные проверки на выбранных случаях, а не гарантия точности SciPy +при любых экстремальных параметрах. + +## Полнота документации + +Для каждого из десяти классов существует ровно одна страница с гипотезой, +формулой, ограничениями, направлением критической области, примером и научными +ссылками. [Общий каталог](index.md) содержит все классы и полные коды; +каталог, десять страниц и этот отчёт включены в MkDocs. +Автотест сравнивает каталог с публичными экспортами, проверяет отдельную страницу +и DOI для каждого класса, исполняет все примеры и проверяет локальные ссылки. + +## Частотные критерии + +Добавлены Pearson, Freeman–Tukey, Modified Log Likelihood, Neyman и Cressie–Read +через `FrequencySpec` и `export_frequency_statistics`. Все четыре параметра +гиперболической модели фиксированы. Дополнительной подгонки нет. + +Пусть `O_j` и `E_j=n p_j` — частоты, `ΣO_j=ΣE_j=n`, `E_j>0`. + +| Критерий | Формула | Пустая наблюдаемая ячейка | +| --- | --- | --- | +| Pearson χ² | `Σ(O_j−E_j)²/E_j` | Пустая ячейка вносит E_j. | +| Freeman–Tukey | `4 Σ(√O_j−√E_j)²` | Пустая ячейка вносит 4E_j. | +| Modified Log Likelihood | `2 Σ E_j log(E_j/O_j)` | При O_j=0 результат +∞. Это математический предел. | +| Neyman χ² | `Σ(O_j−E_j)²/O_j` | При O_j=0 результат +∞. Это математический предел. | +| Cressie–Read | `(9/5) Σ O_j [(O_j/E_j)^(2/3)−1]` | При O_j=0 соответствующее слагаемое равно нулю по непрерывности. | + +Формулы соответствуют семейству power divergence при λ=1, −1/2, −1, −2, 2/3 +из [Cressie–Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). +Использованы опубликованная формула семейства и независимые проверки SciPy. +Критическая область правая. Бесконечности Neyman и Modified Log Likelihood +при пустых ячейках — математические значения, а не ошибки хвостового интегрирования AD. + +По умолчанию применяются равновероятные ячейки. Конструктор принимает +`binning`, конфигурация сохраняет стратегию и её параметры. При фиксированных +ячейках и положительных вероятностях стандартный асимптотический закон — +χ²(k−1); параметры распределения не оцениваются, поэтому число параметров +из степеней свободы не вычитается. Этот вывод не переносится автоматически +на адаптивные границы или растущее число ячеек. При малых частотах требуется +моделирование с тем же разбиением. Внешний генератор нужен и для частотных критериев. + +В `test_hyperbolic_frequency.py` проверены публичный путь, равновероятные +ячейки симметричного закона (медиана 0), повторы, пустые ячейки, крайние значения, +границы явных интервалов, независимое интегрирование классической плотности +для ожидаемых частот и сопоставление с `scipy.stats.power_divergence`. +Также проверены настройки разбиения, pickle, валидация и вызов Numba-ядер. + +## Архитектура и совместимость + +Модуль преобразован в пакет с `__init__.py`, `__init__.pyi` и +`hyperbolic_statistics.py`. Публичные имена, пути импорта и коды сохранены. +База больше не объявляет `supported_hypotheses`: все десять спецификаций фабрик +объявляют их самостоятельно. Ручной класс KS и адаптеры CVM/AD удалены. +Численные методы наследуются непосредственно из алгоритмов `edf.py`. + +Пять EDF-критериев создаются общей фабрикой с необязательным callback +проверенной CDF. При наличии log-ядра приоритет остаётся у логарифмических хвостов; +остальные алгоритмы избегают ненужного вычисления обоих хвостов. +Все десять публичных путей вызывают общие ядра `@jit(nopython=True, cache=True)`. +Отдельных вспомогательных функций в модуле семейства нет. + +Проверены уникальность кодов, экспорт классов и разрешение старых pickle-ссылок. +Добавлена сериализация экземпляров: параметры переводятся в обычные словари, +чтобы обойти непиклируемый `mappingproxy`, затем восстанавливаются в исходной схеме. +Изменения API при полной автогенерации: + +- KS принимает только `parameters`; `alternative_type` и `mode` удалены. +- `do_execute_statistic(cdf_vals)` принимает только отсортированные вероятности, + включая KS, CVM и AD. +- Для AD с готовыми логарифмическими хвостами используйте + `do_execute_log_statistic(log_cdf, log_sf)`. +- Публичный `execute_statistic(rvs, **kwargs)` сохраняет прежнее поведение + для двустороннего KS и остальных четырёх критериев. + +Генератор `scripts/generate_hyperbolic_stub.py --check` проверяет актуальность stub; +для форматирования используется Ruff из dev-зависимостей проекта. + +Исправлены неверное утверждение о параметрах по умолчанию и сломанные ссылки +в прежних страницах. Новых ошибок коэффициентов в существующих пяти формулах +не обнаружено. Устойчивая центрировка Watson и прямые логарифмические хвосты AD сохранены. + +## Производительность + +Исторический замер до удаления совместимых адаптеров, пустой `NUMBA_CACHE_DIR`. +Первый вызов включает компиляцию и инициализацию Numba; это не чистое время компилятора. +Прогретые ядра: `n=10000`, 1000 повторов; публичный путь: `n=100`, 10 повторов. + +| Код | Первый вызов, мс | Прогретое ядро, мкс | Публичный вызов, мс | +| --- | ---: | ---: | ---: | +| AD | 592.725 | 19.204 | 279.455 | +| CVM | 127.819 | 15.961 | 7.264 | +| KS | 368.179 | 33.127 | 7.297 | +| KUI | 195.830 | 31.891 | 7.278 | +| WAT | 152.739 | 29.814 | 7.245 | + +Сценарий: `benchmarks/benchmark_hyperbolic_pipeline.py`. +Это абсолютные времена, не заявление об ускорении относительно старого кода. +Основная стоимость публичного пути — SciPy CDF/хвосты; Numba ускоряет только +арифметическую часть. Аппаратная платформа, версии и состояние кеша меняют результат. + +## Проверки и ограничения запуска + +Обычная команда `pytest tests/distributions/test_hyperbolic.py + tests/distributions/test_hyperbolic_correctness.py` блокируется при сборе: +`exponentiated_weibull.py` импортирует удалённый `AbstractChi2Statistic` из `edf.py`. +Это существующая проблема соседнего семейства, не исправлявшаяся в данной задаче. + +Для изолированного запуска в `sys.modules` подставлен пустой пакет +`pysatl_criterion.statistics.goodness_of_fit.continuous` с настоящим `__path__`. +Тестируемые `hyperbolic`, EDF, фабрика, параметры и реестр загружаются из реальных +файлов; обходится только агрегирующий `continuous/__init__.py`. +Проверка глобального агрегирующего импорта остаётся заблокированной. +Результаты итогового запуска приведены ниже. + +Проверка после добавления частотных критериев: **336 passed**, без предупреждений. +Дополнительно изолированно прошли **70 тестов** `test_frequency.py`, +`test_binning.py`, `test_frequency_dynamic.py`. +Изолированно выполнены `tests/distributions/test_hyperbolic.py`, +`tests/distributions/test_hyperbolic_correctness.py`, +`tests/distributions/test_hyperbolic_frequency.py` и `tests/statistics/test_edf.py`. +Подключены общие частотные ядра без дублирования алгоритмов; расширены +независимые проверки и проверка полноты документации. +Проверены исполняемые примеры всех десяти страниц, полнота каталога/навигации, +локальные ссылки, старые pickle-ссылки и roundtrip экземпляров, +а также фактические вызовы скомпилированных ядер из публичного API. + +Ruff для изменённых Python-файлов и stub, `generate_hyperbolic_stub.py --check` +и `git diff --check` прошли. Обычная сборка MkDocs прошла; +`mkdocs build --strict` остановилась на 91 существующем предупреждении +других разделов (в частности, отсутствующие страницы аудита normality и Weibull). +Предупреждений для раздела hyperbolic нет. + +Воспроизведение изолированного запуска из корня репозитория: + +```text +.venv/bin/python - <<'PY' +import sys +import types +from pathlib import Path +import pytest +root = Path.cwd() +sys.path[:0] = [str(root), str(root / "src")] +name = "pysatl_criterion.statistics.goodness_of_fit.continuous" +package = types.ModuleType(name) +package.__path__ = [str(root / "src/pysatl_criterion/statistics/goodness_of_fit/continuous")] +sys.modules[name] = package +raise SystemExit(pytest.main([ + "tests/distributions/test_hyperbolic.py", + "tests/distributions/test_hyperbolic_correctness.py", + "tests/distributions/test_hyperbolic_frequency.py", + "tests/statistics/test_edf.py", "-q", +])) +PY +``` + +Для изолированного замера используйте тот же bootstrap пакета, затем +`runpy.run_path('benchmarks/benchmark_hyperbolic_pipeline.py', run_name='__main__')` +вместо вызова pytest. После исправления агрегирующего импорта изоляция не требуется. diff --git a/docs/criteria/goodness-of-fit/hyperbolic/modified_log_likelihood_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/modified_log_likelihood_hyperbolic_criterion.md new file mode 100644 index 00000000..32392794 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/modified_log_likelihood_hyperbolic_criterion.md @@ -0,0 +1,69 @@ +# Modified Log Likelihood: гиперболическое распределение + +`ModifiedLogLikelihoodHyperbolicGofStatistic` (`MODIFIED_LOG_LIKELIHOOD_HYPERBOLIC_GOODNESS_OF_FIT`) проверяет +полностью заданную гиперболическую iid-модель на вещественной оси. +Все параметры заданы заранее: конечные `alpha > abs(beta)`, `delta > 0`, `mu`. +Неизвестные параметры и их оценивание этим классом не поддерживаются. + +Пусть `O_j` — наблюдаемая частота, `E_j=n p_j>0` — ожидаемая частота в +j-й ячейке, `p_j` — её вероятность под нулевой гипотезой. +Обе суммы частот равны n. Статистика: + +`T = 2 Σ E_j log(E_j/O_j)`. + +Критическая область правая: большие T свидетельствуют против гипотезы. +При O_j=0 результат +∞. Это математический предел. + +## Разбиение и калибровка + +Конструктор принимает `parameters` и необязательный `binning`. +По умолчанию используется `EqualProbabilityBins()`: наблюдения преобразуются +известной CDF, а `[0,1]` разбивается на равновероятные ячейки; `E_j=n/k`. +Количество ячеек выбирается общим правилом `PowerCount`, минимум две. +Пример ниже фиксирует две ячейки явно. + +Можно передать другие [стратегии разбиения](../binning/index.md), включая +`ExplicitBins` с границами, покрывающими весь носитель. Внутренняя граница +принадлежит ячейке справа; последняя включает правый конец. +Правила разбиения, числа ячеек и объединения входят в конфигурацию калибровки. + +Нужна непустая одномерная конечная вещественная выборка. Повторы и константы +допустимы; вход не изменяется. Это не гарантирует точности асимптотической +калибровки при малом числе наблюдений. Для заранее фиксированных k ячеек с +положительными вероятностями и известными параметрами применима асимптотика +χ² с k−1 степенями свободы. Для малых ожидаемых частот или адаптивных границ +нужно моделирование, воспроизводящее весь алгоритм разбиения. +Встроенный resolver не имеет гиперболического генератора: моделируйте внешне +через `scipy.stats.genhyperbolic(p=1, a=alpha*delta, b=beta*delta, loc=mu, scale=delta)`. +Класс возвращает статистику, а не p-value. Численные ошибки вероятностей +при построении таблицы приводят к исключению, не к скрытому clipping. + +## Пример + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + ModifiedLogLikelihoodHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0, "delta": 1, "mu": 0} +) +criterion = ModifiedLogLikelihoodHyperbolicGofStatistic( + parameters, binning=EqualProbabilityBins(count=2) +) +value = criterion.execute_statistic([-2.0, -1.0, -0.5, 1.0]) +assert isinstance(value, float) and value >= 0 +``` + +## Научный источник + +[Cressie N., Read T. R. C. (1984), Multinomial Goodness-of-Fit Tests, +JRSS B 46(3), 440–464](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x): +семейство power divergence при `λ=−1`. +[Полный текст](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). +Применение к гиперболической модели использует вероятности её ячеек; +выбор конкретной стратегии разбиения является настройкой библиотеки. + +[Все критерии](index.md) · [Математическая проверка](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/neyman_chi2_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/neyman_chi2_hyperbolic_criterion.md new file mode 100644 index 00000000..3841d79b --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/neyman_chi2_hyperbolic_criterion.md @@ -0,0 +1,67 @@ +# Neyman χ²: гиперболическое распределение + +`NeymanChi2HyperbolicGofStatistic` (`CHI2_NEYMAN_HYPERBOLIC_GOODNESS_OF_FIT`) проверяет +полностью заданную гиперболическую iid-модель на вещественной оси. +Все параметры заданы заранее: конечные `alpha > abs(beta)`, `delta > 0`, `mu`. +Неизвестные параметры и их оценивание этим классом не поддерживаются. + +Пусть `O_j` — наблюдаемая частота, `E_j=n p_j>0` — ожидаемая частота в +j-й ячейке, `p_j` — её вероятность под нулевой гипотезой. +Обе суммы частот равны n. Статистика: + +`T = Σ(O_j−E_j)²/O_j`. + +Критическая область правая: большие T свидетельствуют против гипотезы. +При O_j=0 результат +∞. Это математический предел. + +## Разбиение и калибровка + +Конструктор принимает `parameters` и необязательный `binning`. +По умолчанию используется `EqualProbabilityBins()`: наблюдения преобразуются +известной CDF, а `[0,1]` разбивается на равновероятные ячейки; `E_j=n/k`. +Количество ячеек выбирается общим правилом `PowerCount`, минимум две. +Пример ниже фиксирует две ячейки явно. + +Можно передать другие [стратегии разбиения](../binning/index.md), включая +`ExplicitBins` с границами, покрывающими весь носитель. Внутренняя граница +принадлежит ячейке справа; последняя включает правый конец. +Правила разбиения, числа ячеек и объединения входят в конфигурацию калибровки. + +Нужна непустая одномерная конечная вещественная выборка. Повторы и константы +допустимы; вход не изменяется. Это не гарантирует точности асимптотической +калибровки при малом числе наблюдений. Для заранее фиксированных k ячеек с +положительными вероятностями и известными параметрами применима асимптотика +χ² с k−1 степенями свободы. Для малых ожидаемых частот или адаптивных границ +нужно моделирование, воспроизводящее весь алгоритм разбиения. +Встроенный resolver не имеет гиперболического генератора: моделируйте внешне +через `scipy.stats.genhyperbolic(p=1, a=alpha*delta, b=beta*delta, loc=mu, scale=delta)`. +Класс возвращает статистику, а не p-value. Численные ошибки вероятностей +при построении таблицы приводят к исключению, не к скрытому clipping. + +## Пример + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + NeymanChi2HyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0, "delta": 1, "mu": 0} +) +criterion = NeymanChi2HyperbolicGofStatistic(parameters, binning=EqualProbabilityBins(count=2)) +value = criterion.execute_statistic([-2.0, -1.0, -0.5, 1.0]) +assert isinstance(value, float) and value >= 0 +``` + +## Научный источник + +[Cressie N., Read T. R. C. (1984), Multinomial Goodness-of-Fit Tests, +JRSS B 46(3), 440–464](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x): +семейство power divergence при `λ=−2`. +[Полный текст](https://pages.stern.nyu.edu/~dbackus/Exotic/1Robustness/CressieRead%20JRSSB%2084.pdf). +Применение к гиперболической модели использует вероятности её ячеек; +выбор конкретной стратегии разбиения является настройкой библиотеки. + +[Все критерии](index.md) · [Математическая проверка](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/hyperbolic/watson_hyperbolic_criterion.md b/docs/criteria/goodness-of-fit/hyperbolic/watson_hyperbolic_criterion.md new file mode 100644 index 00000000..fe3fb0b5 --- /dev/null +++ b/docs/criteria/goodness-of-fit/hyperbolic/watson_hyperbolic_criterion.md @@ -0,0 +1,47 @@ +# Watson: гиперболическое распределение + +`WatsonHyperbolicGofStatistic` проверяет iid-выборку из полностью заданного +гиперболического распределения на R. Параметры фиксированы: +все четыре значения `alpha`, `beta`, `delta`, `mu` необходимо задать явно; +`alpha > abs(beta)`, `delta > 0`, все параметры — конечные вещественные скаляры. +Подгонки параметров нет. + +Для отсортированных наблюдений `u_i=F(x_(i))`, `i=1,...,n`: + +`U²=1/(12n)+Σ(d_i−mean(d))², d_i=u_i−(2i−1)/(2n)`. + +Дополнительных поправок нет. Критическая область — большие значения. +Минимум одно конечное вещественное наблюдение; повторы и константы допустимы. +Невалидные выборки вызывают `ValueError`, обнаруженные численные ошибки CDF — +`FloatingPointError`. Вызов возвращает `float`, вход не изменяется, +дополнительные kwargs игнорируются. + + +```python +from pysatl_criterion.distribution import HyperbolicDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.hyperbolic import ( + WatsonHyperbolicGofStatistic, +) + +parameters = HyperbolicDistributionDescriptor.DEFAULT.parse( + {"alpha": 1.5, "beta": 0.2, "delta": 1, "mu": 0} +) +statistic = WatsonHyperbolicGofStatistic(parameters) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) +assert isinstance(value, float) and value >= 0 +``` + +[Общий EDF-источник](https://doi.org/10.1093/biomet/48.1-2.109) применяется через преобразование +известной непрерывной CDF; это не источник о подгонке гиперболической модели. +Нулевой закон зависит от размера выборки, но не от фиксированных параметров. +Встроенный Monte Carlo resolver не имеет гиперболического генератора. +Для внешнего моделирования используйте `genhyperbolic(p=1, a=alpha*delta, +b=beta*delta, loc=mu, scale=delta)` и вызывайте `execute_statistic` на каждой выборке. + +[Полный аудит, ограничения источников и требования к калибровке](mathematical-validation.md). + +[Каталог критериев](index.md). + +Проверенная вычислительная формула: [Lemeshko et al. (2014), формула (6)](https://doi.org/10.3103/S875669901401004X), [полный текст](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +При `n=1` статистика тождественно равна `1/12` и не различает альтернативы. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/anderson_darling_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/anderson_darling_inverse_gamma_criterion.md new file mode 100644 index 00000000..48aa13eb --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/anderson_darling_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Anderson–Darling for inverse gamma + +## API and hypothesis + +`AndersonDarlingInverseGammaGofStatistic` has code `AD_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. The implementation uses log-CDF and log-survival directly, without epsilon clipping. Unrepresentable log tails raise `FloatingPointError`; arithmetic overflow in the final formula can still produce infinity. + +## Formula + +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1)[\log u_i+\log(1-u_{n+1-i})]. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + AndersonDarlingInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = AndersonDarlingInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Anderson and Darling (1952), Asymptotic Theory of Certain Goodness of Fit Criteria Based on Stochastic Processes](https://doi.org/10.1214/aoms/1177729437). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/chi2_pearson_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/chi2_pearson_inverse_gamma_criterion.md new file mode 100644 index 00000000..0161730e --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/chi2_pearson_inverse_gamma_criterion.md @@ -0,0 +1,42 @@ +# Pearson chi-squared for inverse gamma + +## API and hypothesis + +`Chi2PearsonInverseGammaGofStatistic` has code `CHI2_PEARSON_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Set `binning=EqualProbabilityBins(k)` to use a fixed number of cells. The default `EqualProbabilityBins()` uses the shared sample-size count rule, not a fixed eight cells. Here $O_j$ are observed counts and $E_j=n p_j>0$; for equal-probability cells $p_j=1/k$. The binning configuration is part of the storage identity. See [binning](../binning/index.md). + +For fixed cells and sufficiently large expected counts, the usual asymptotic reference has $k-1$ degrees of freedom. Sparse counts, adaptive edges or a growing cell count need calibration for the actual binning procedure. + +## Formula + +$$ +X^2=\sum_{j=1}^k\frac{(O_j-E_j)^2}{E_j}. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + Chi2PearsonInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = Chi2PearsonInverseGammaGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence family. + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/cramer_von_mises_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/cramer_von_mises_inverse_gamma_criterion.md new file mode 100644 index 00000000..95e8294c --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/cramer_von_mises_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Cramér–von Mises for inverse gamma + +## API and hypothesis + +`CramerVonMisesInverseGammaGofStatistic` has code `CVM_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +## Formula + +$$ +W^2=\frac1{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + CramerVonMisesInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = CramerVonMisesInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/cressie_read_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/cressie_read_inverse_gamma_criterion.md new file mode 100644 index 00000000..467466d2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/cressie_read_inverse_gamma_criterion.md @@ -0,0 +1,44 @@ +# Cressie–Read for inverse gamma + +## API and hypothesis + +`CressieReadInverseGammaGofStatistic` has code `CRESSIE_READ_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Set `binning=EqualProbabilityBins(k)` to use a fixed number of cells. The default `EqualProbabilityBins()` uses the shared sample-size count rule, not a fixed eight cells. Here $O_j$ are observed counts and $E_j=n p_j>0$; for equal-probability cells $p_j=1/k$. The binning configuration is part of the storage identity. See [binning](../binning/index.md). + +An empty observed cell contributes zero by continuity. + +For fixed cells and sufficiently large expected counts, the usual asymptotic reference has $k-1$ degrees of freedom. Sparse counts, adaptive edges or a growing cell count need calibration for the actual binning procedure. + +## Formula + +$$ +T=\frac95\sum_{j=1}^k O_j[(O_j/E_j)^{2/3}-1]. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + CressieReadInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = CressieReadInverseGammaGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence family. + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/freeman_tukey_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/freeman_tukey_inverse_gamma_criterion.md new file mode 100644 index 00000000..ca638801 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/freeman_tukey_inverse_gamma_criterion.md @@ -0,0 +1,44 @@ +# Freeman–Tukey for inverse gamma + +## API and hypothesis + +`FreemanTukeyInverseGammaGofStatistic` has code `FREEMAN_TUKEY_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Set `binning=EqualProbabilityBins(k)` to use a fixed number of cells. The default `EqualProbabilityBins()` uses the shared sample-size count rule, not a fixed eight cells. Here $O_j$ are observed counts and $E_j=n p_j>0$; for equal-probability cells $p_j=1/k$. The binning configuration is part of the storage identity. See [binning](../binning/index.md). + +An empty observed cell contributes $4E_j$. The factor four is intentional. + +For fixed cells and sufficiently large expected counts, the usual asymptotic reference has $k-1$ degrees of freedom. Sparse counts, adaptive edges or a growing cell count need calibration for the actual binning procedure. + +## Formula + +$$ +T=4\sum_{j=1}^k(\sqrt{O_j}-\sqrt{E_j})^2. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + FreemanTukeyInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = FreemanTukeyInverseGammaGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence family. + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/greenwood_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/greenwood_inverse_gamma_criterion.md new file mode 100644 index 00000000..2a025a41 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/greenwood_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Greenwood for inverse gamma + +## API and hypothesis + +`GreenwoodInverseGammaGofStatistic` has code `GRW_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +All $n+1$ spacings, including both endpoints, enter the sum. The null mean is $2/(n+2)$ and $1/(n+1)\le G\le1$. This is the raw spacing sum without standardization. + +## Formula + +$$ +G=\sum_{i=0}^n(u_{i+1}-u_i)^2,\qquad u_0=0,\ u_{n+1}=1. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + GreenwoodInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = GreenwoodInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Does, Helmers and Klaassen (1988), Approximating the distribution of Greenwood’s statistic](https://ir.cwi.nl/pub/1694/1694D.pdf), eqs. (1)–(2). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/index.md b/docs/criteria/goodness-of-fit/inverse-gamma/index.md new file mode 100644 index 00000000..053760ad --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/index.md @@ -0,0 +1,83 @@ +# Inverse-gamma goodness-of-fit criteria + +All 19 public classes below test a **fully specified** inverse-gamma distribution. + +For $x>0$ and $\alpha,\beta>0$, + +$$ +f(x)=\frac{\beta^\alpha}{\Gamma(\alpha)}x^{-\alpha-1}e^{-\beta/x}, +\qquad F(x)=Q(\alpha,\beta/x). +$$ + +Here $Q$ is the regularized upper incomplete gamma function; equivalently, +$\beta/X$ is Gamma(shape $\alpha$, scale 1). Location is fixed at zero. +Fix both parameters with +`InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0})`. +Omitting either parameter does not request estimation: these criteria reject +unsupported composite hypotheses. + +All classes return a scalar and use a right-tail rejection region. +Input observations must be finite, positive and nonempty. Singletons, ties and +constant samples are accepted. See [mathematical verification](mathematical-validation.md). + +## Criteria + +| Criterion | Public class | Short code | +|---|---|---| +| [Kolmogorov–Smirnov](kolmogorov_smirnov_inverse_gamma_criterion.md) | `KolmogorovSmirnovInverseGammaGofStatistic` | `KS` | +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_inverse_gamma_criterion.md) | `KolmogorovSmirnovDPlusInverseGammaGofStatistic` | `KS_PLUS` | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_inverse_gamma_criterion.md) | `KolmogorovSmirnovDMinusInverseGammaGofStatistic` | `KS_MINUS` | +| [Anderson–Darling](anderson_darling_inverse_gamma_criterion.md) | `AndersonDarlingInverseGammaGofStatistic` | `AD` | +| [Cramér–von Mises](cramer_von_mises_inverse_gamma_criterion.md) | `CramerVonMisesInverseGammaGofStatistic` | `CVM` | +| [Watson](watson_inverse_gamma_criterion.md) | `WatsonInverseGammaGofStatistic` | `WAT` | +| [Kuiper](kuiper_inverse_gamma_criterion.md) | `KuiperInverseGammaGofStatistic` | `KUI_INVGAMMA` | +| [Scaled Kuiper](kuiper_scaled_inverse_gamma_criterion.md) | `KuiperScaledInverseGammaGofStatistic` | `KUIPER_SCALED` | +| [Corrected Kuiper](kuiper_corrected_inverse_gamma_criterion.md) | `KuiperCorrectedInverseGammaGofStatistic` | `KUIPER_CORRECTED` | +| [Liao–Shimokawa](liao_shimokawa_inverse_gamma_criterion.md) | `LiaoShimokawaInverseGammaGofStatistic` | `LIAO_SHIMOKAWA` | +| [Zhang A](zhang_a_inverse_gamma_criterion.md) | `ZhangAInverseGammaGofStatistic` | `ZAA` | +| [Zhang C](zhang_c_inverse_gamma_criterion.md) | `ZhangCInverseGammaGofStatistic` | `ZAC` | +| [Zhang K](zhang_k_inverse_gamma_criterion.md) | `ZhangKInverseGammaGofStatistic` | `ZAK` | +| [Greenwood](greenwood_inverse_gamma_criterion.md) | `GreenwoodInverseGammaGofStatistic` | `GRW` | +| [Pearson chi-squared](chi2_pearson_inverse_gamma_criterion.md) | `Chi2PearsonInverseGammaGofStatistic` | `CHI2_PEARSON` | +| [Freeman–Tukey](freeman_tukey_inverse_gamma_criterion.md) | `FreemanTukeyInverseGammaGofStatistic` | `FREEMAN_TUKEY` | +| [Modified log-likelihood](modified_log_likelihood_inverse_gamma_criterion.md) | `ModifiedLogLikelihoodInverseGammaGofStatistic` | `MODIFIED_LOG_LIKELIHOOD` | +| [Neyman modified chi-squared](neyman_chi2_inverse_gamma_criterion.md) | `NeymanChi2InverseGammaGofStatistic` | `CHI2_NEYMAN` | +| [Cressie–Read](cressie_read_inverse_gamma_criterion.md) | `CressieReadInverseGammaGofStatistic` | `CRESSIE_READ` | + +The full code appends `_INV_GAMMA_GOODNESS_OF_FIT` to each short code. + +## Calibration and binning + +For fixed parameters, the probability integral transform gives iid Uniform(0,1) +observations under the null. Thus EDF and spacing null laws depend on sample size +and the chosen statistic, but not on alpha or beta. This conclusion requires +continuous iid data and parameters specified independently of the sample. +It does not justify using fitted-model tables or treating rounded data as continuous. + +The five frequency classes accept keyword-only `binning`. The default is +`EqualProbabilityBins()` with `PowerCount(2.0, 0.4)`, no minimum expected count, +and at most 1000 bins. For a fixed count use `EqualProbabilityBins(8)`; +the former `bins=8` argument is no longer supported. +Equal-probability bin counts are multinomial under the specified null. +Other strategies can have parameter-dependent or data-dependent calibration; +see [binning](../binning/index.md) and [storage identity](../binning/calibration.md). + +The built-in Monte Carlo resolver currently has no inverse-gamma generator. +External simulation can use `scipy.stats.invgamma.rvs(a=alpha, scale=beta, size=n)`; +repeat the same statistic and binning procedure for each replicate. +This audit validates calculations, not Monte Carlo p-values or nominal test size. + +## Numerical behavior + +Logarithmic EDF criteria use log-CDF/log-survival without clipping. A log-tail +underflow raises `FloatingPointError`; subsequent arithmetic can still overflow. +Probability-only formulas may see CDF rounding at zero and one. Frequency +validation converts numeric strings to floats; EDF/Greenwood reject such input. +Modified log-likelihood and Neyman return infinity for empty observed cells; +other frequency statistics implement their finite zero-count limits. + +## Sources + +The [SciPy inverse-gamma reference](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.invgamma.html) +fixes the shape/scale convention. Scientific sources for every statistic appear +on its individual page and in the [verification report](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_d_minus_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_d_minus_inverse_gamma_criterion.md new file mode 100644 index 00000000..61737a19 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_d_minus_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Kolmogorov–Smirnov D− for inverse gamma + +## API and hypothesis + +`KolmogorovSmirnovDMinusInverseGammaGofStatistic` has code `KS_MINUS_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +## Formula + +$$ +D^-=\max_{1\le i\le n}(u_i-(i-1)/n). +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + KolmogorovSmirnovDMinusInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = KolmogorovSmirnovDMinusInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Smirnov (1948), Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_d_plus_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_d_plus_inverse_gamma_criterion.md new file mode 100644 index 00000000..0dfa9ae7 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_d_plus_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Kolmogorov–Smirnov D+ for inverse gamma + +## API and hypothesis + +`KolmogorovSmirnovDPlusInverseGammaGofStatistic` has code `KS_PLUS_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +## Formula + +$$ +D^+=\max_{1\le i\le n}(i/n-u_i). +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + KolmogorovSmirnovDPlusInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = KolmogorovSmirnovDPlusInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Smirnov (1948), Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_inverse_gamma_criterion.md new file mode 100644 index 00000000..a680e8f0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/kolmogorov_smirnov_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Kolmogorov–Smirnov for inverse gamma + +## API and hypothesis + +`KolmogorovSmirnovInverseGammaGofStatistic` has code `KS_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +Optional `alternative_type=AlternativeType.RIGHT` returns $D^+$, `LEFT` returns $D^-$, and `TWO_TAILED` returns $D$. All three reject in the right tail of their statistic. `mode` is a compatibility option and does not change the scalar. Legacy directional storage calibration is blocked; prefer the dedicated D+ and D− classes. + +## Formula + +$$ +D=\max(D^+,D^-). +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + KolmogorovSmirnovInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = KolmogorovSmirnovInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Smirnov (1948), Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_corrected_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_corrected_inverse_gamma_criterion.md new file mode 100644 index 00000000..7b818c6d --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_corrected_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Corrected Kuiper for inverse gamma + +## API and hypothesis + +`KuiperCorrectedInverseGammaGofStatistic` has code `KUIPER_CORRECTED_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +Use calibration for this normalization; unscaled, scaled and corrected Kuiper values are different. The correction does not provide an exact finite-sample p-value. + +## Formula + +$$ +V_n^*=(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-). +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + KuiperCorrectedInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = KuiperCorrectedInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [author-hosted paper](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_inverse_gamma_criterion.md new file mode 100644 index 00000000..c6ecba75 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Kuiper for inverse gamma + +## API and hypothesis + +`KuiperInverseGammaGofStatistic` has code `KUI_INVGAMMA_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +Use calibration for this normalization; unscaled, scaled and corrected Kuiper values are different. The correction does not provide an exact finite-sample p-value. + +## Formula + +$$ +V=D^++D^-. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + KuiperInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = KuiperInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [author-hosted paper](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_scaled_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_scaled_inverse_gamma_criterion.md new file mode 100644 index 00000000..6c11f20a --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/kuiper_scaled_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Scaled Kuiper for inverse gamma + +## API and hypothesis + +`KuiperScaledInverseGammaGofStatistic` has code `KUIPER_SCALED_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +Use calibration for this normalization; unscaled, scaled and corrected Kuiper values are different. The correction does not provide an exact finite-sample p-value. + +## Formula + +$$ +V_n=\sqrt n(D^++D^-). +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + KuiperScaledInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = KuiperScaledInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [author-hosted paper](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/liao_shimokawa_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/liao_shimokawa_inverse_gamma_criterion.md new file mode 100644 index 00000000..7ed3356e --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/liao_shimokawa_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Liao–Shimokawa for inverse gamma + +## API and hypothesis + +`LiaoShimokawaInverseGammaGofStatistic` has code `LIAO_SHIMOKAWA_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. The implementation uses log-CDF and log-survival directly, without epsilon clipping. Unrepresentable log tails raise `FloatingPointError`; arithmetic overflow in the final formula can still produce infinity. + +The original paper concerns fitted Weibull/extreme-value hypotheses; its critical values do not apply here. + +## Formula + +$$ +L_n=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}}. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + LiaoShimokawaInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = LiaoShimokawaInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Liao and Shimokawa (1999), A new goodness-of-fit test for type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). The expression is also reproduced in [Al-Zahrani (2012), eq. (13)](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/mathematical-validation.md b/docs/criteria/goodness-of-fit/inverse-gamma/mathematical-validation.md new file mode 100644 index 00000000..5461959d --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/mathematical-validation.md @@ -0,0 +1,165 @@ +# Mathematical verification of inverse-gamma statistics + +## Scope and conclusion + +All **19 concrete public classes** in `continuous/inverse_gamma/inverse_gamma_statistics.py` were audited. +They implement 19 distinct scalar definitions. +No mathematical formula changes were needed for the definitions checked. +The complete class-to-page inventory is in the [overview](index.md). + +This report follows the [uniformity verification report](../uniformity/mathematical-validation.md). +It verifies the implemented statistics and documented conventions, not the power +of each test against every alternative or exact finite-sample rejection rates. + +## Null model and probability transform + +The hypothesis is iid inverse gamma with fixed shape $\alpha>0$, scale $\beta>0$ +and zero location: + +$$ +f(x)=\frac{\beta^\alpha}{\Gamma(\alpha)}x^{-\alpha-1}e^{-\beta/x},\quad x>0. +$$ + +Setting $Y=\beta/X$ and applying the Jacobian gives +$f_Y(y)=y^{\alpha-1}e^{-y}/\Gamma(\alpha)$, hence +$F_X(x)=P(Y\ge\beta/x)=Q(\alpha,\beta/x)$. +This verifies that the CDF uses the **upper** gamma tail, and that beta is a scale, +not a rate applied directly to X. See the [SciPy parameter convention](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.invgamma.html). + +For sorted observations write $u_i=F_X(x_{(i)})$. Under this fixed continuous null, +the unordered transformed observations are iid Uniform(0,1). Therefore EDF and +spacing null laws are independent of alpha and beta. With fixed equiprobable +cells the frequency vector is multinomial with probabilities $1/k$. +This conclusion does not extend automatically to arbitrary adaptive binning. +All 19 classes explicitly require both parameters; no fitting is performed. + +## Formula checks + +Every individual page gives the explicit implemented formula and a runnable example. + +| Classes / criteria | Verified convention | Scientific source | +|---|---|---| +| KS, KS D+, KS D− | Rank discrepancies $i/n-u_i$ and $u_i-(i-1)/n$; maximum without squaring | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256); [Zhang (2002), §2.1](https://doi.org/10.1111/1467-9868.00337) | +| Anderson–Darling | Weight $(2i-1)/n$, reversed survival tail, subtraction of n | [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437); Zhang §2.2 | +| Cramér–von Mises | Half-rank target and $1/(12n)$ constant | Zhang §2.3 | +| Watson | Centered EDF integral; equivalently $W^2-n(\bar u-1/2)^2$ | [Lemeshko et al. (2014), eq. (6)](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf) | +| Kuiper, scaled Kuiper, corrected Kuiper | $V=D^++D^-$; $\sqrt n V$; $(\sqrt n+0.155+0.24/\sqrt n)V$ | Lemeshko et al., eqs. (1)–(3) | +| Liao–Shimokawa | Local maximum discrepancy divided by $\sqrt{u_i(1-u_i)}$, summed and divided by $\sqrt n$ | [Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965); [Al-Zahrani (2012), eq. (13)](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf) | +| Zhang K, A, C | Half-rank likelihood terms and quarter-rank log-odds adjustment; no additional factor two | [Zhang (2002), eqs. (3.1)–(3.3), full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf) | +| Greenwood | Raw sum of all n+1 squared spacings, including endpoints | [Does, Helmers and Klaassen (1988), eqs. (1)–(2)](https://ir.cwi.nl/pub/1694/1694D.pdf) | +| Pearson | Power divergence at $\lambda=1$ | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| Freeman–Tukey | $\lambda=-1/2$, including factor four | Cressie and Read (1984) | +| Modified log-likelihood | $\lambda=-1$, expected-count weighting | Cressie and Read (1984) | +| Neyman modified chi-squared | $\lambda=-2$, observed-count denominator | Cressie and Read (1984) | +| Cressie–Read | $\lambda=2/3$, multiplier $9/5$ | Cressie and Read (1984) | + +The frequency formulas follow by substitution or taking the limit in +$2\sum_j O_j[(O_j/E_j)^\lambda-1]/[\lambda(\lambda+1)]$, using +$\sum O_j=\sum E_j$. The implementation's special handling of zero counts +matches these limits: Freeman–Tukey contributes $4E_j$, Pearson contributes +$E_j$, and Cressie–Read contributes zero. Modified log-likelihood and Neyman +return positive infinity if any $O_j=0$ with $E_j>0$. + +For Greenwood, the n+1 uniform spacings have a Dirichlet(1,…,1) law. +Each squared spacing has mean $2/[(n+1)(n+2)]$, yielding $E[G]=2/(n+2)$. +Cauchy–Schwarz and nonnegative spacings give $1/(n+1)\le G\le1$. + +## Source qualifications and interpretation + +The Zhang, Greenwood and Lemeshko full texts were available for formula checks. +Lemeshko's DOI resolves to **Solving Problems of Using Some Nonparametric +Goodness-of-Fit Tests**; the page references use that title. +For Liao–Shimokawa, the original bibliographic record was checked and its formula +was inspected in Al-Zahrani's published application, eq. (13); the original +publisher full text was unavailable. Cressie–Read's accessible publisher summary +and indexed paper give the divergence definition and parameter mapping; the +zero-count limits were also derived directly and checked numerically. + +These are general discrepancies applied to the fixed inverse-gamma CDF, not +claims of specialized fitted inverse-gamma tests. In particular, the Weibull or +extreme-value calibration in the original Liao–Shimokawa work is inapplicable. +Kuiper corrections change normalization; they do not +produce exact finite-sample p-values. All current classes reject for large values, +including directional KS and Greenwood; this does not imply equal power against +all alternatives. Singletons and ties have well-defined values, but rounded-data +calibration differs from the continuous null. + +## Numerical verification + +The regression suites are: + +- `tests/distributions/test_inverse_gamma.py`; +- `tests/distributions/test_inverse_gamma_correctness.py`; +- `tests/distributions/test_inverse_gamma_mathematical_validation.py`. + +Independent checks cover: + +- All 14 EDF/spacing classes against scalar formulas evaluated with 70-digit + Decimal arithmetic, with four shape/scale pairs, singletons, ties and asymmetric + probability grids. Data are constructed through reciprocal Gamma quantiles, + independently of the production inverse-gamma CDF. +- AD, CvM and Watson against piecewise numerical integration of the empirical + distribution discrepancy, including tied observations. +- All five frequency classes against explicit counts, varying parameters and + empty cells, plus SciPy power-divergence comparisons with nonzero counts. +- Exact shape-one CDF $F(x)=e^{-\beta/x}$ for all five logarithmic EDF classes at + $x=10^{20}$, where the ordinary CDF rounds to one. +- The Greenwood mean for n=1 by integration, KS directions against SciPy, + scale equivariance, hypothesis declarations, missing parameters, positive + support, invalid samples, input immutability and repeatability. +- A one-to-one mapping from every concrete class to a documentation page, + scientific links, overview and navigation entries, and execution of every + page's Python example. + +Log-tail underflow is explicitly rejected without epsilon replacement. Ordinary +CDF values can still round at endpoints; finite logarithms do not guarantee a +finite final statistic if subsequent arithmetic overflows. No claim of arbitrary +precision or accuracy throughout the entire float64 input domain is made. +The frequency factory accepts numeric strings through conversion, while the +EDF/spacing sample validator rejects them. + +## Reproduction and current limitations + +The focused isolated run passed **707 tests**. Ruff checks passed for the new +mathematical validation suite. MkDocs built successfully; its warnings concern +other documentation families, with no inverse-gamma link warnings. The normal invocation is: + +```bash +.venv/bin/python -m pytest tests/distributions/test_inverse_gamma*.py -q +``` + +In the current working tree, normal collection is blocked by an existing import +in `continuous/log_logistic.py` of the removed `edf.AbstractChi2Statistic`. +The isolated run bypassed only the eager `continuous/__init__.py` module; it +loaded the actual inverse-gamma implementation, factories, kernels and binning. +It does not establish that ordinary package initialization works. Reproduce it +from the repository root with: + +```python +import sys +import types +from pathlib import Path +import pytest + +root = Path.cwd() +name = "pysatl_criterion.statistics.goodness_of_fit.continuous" +package = types.ModuleType(name) +package.__path__ = [str(root / "src/pysatl_criterion/statistics/goodness_of_fit/continuous")] +sys.modules[name] = package +raise SystemExit( + pytest.main( + [ + "tests/distributions/test_inverse_gamma.py", + "tests/distributions/test_inverse_gamma_correctness.py", + "tests/distributions/test_inverse_gamma_mathematical_validation.py", + "-q", + ] + ) +) +``` + +The built-in Monte Carlo resolver lacks an inverse-gamma generator; external +simulation is required. Frequency configuration is included in storage identity. +Legacy directional KS storage calibration is guarded; dedicated D+ and D− +classes have distinct statistic codes. No simulated significance-level or power +study was performed in this audit. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/modified_log_likelihood_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/modified_log_likelihood_inverse_gamma_criterion.md new file mode 100644 index 00000000..68e3ef8a --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/modified_log_likelihood_inverse_gamma_criterion.md @@ -0,0 +1,46 @@ +# Modified log-likelihood for inverse gamma + +## API and hypothesis + +`ModifiedLogLikelihoodInverseGammaGofStatistic` has code `MODIFIED_LOG_LIKELIHOOD_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Set `binning=EqualProbabilityBins(k)` to use a fixed number of cells. The default `EqualProbabilityBins()` uses the shared sample-size count rule, not a fixed eight cells. Here $O_j$ are observed counts and $E_j=n p_j>0$; for equal-probability cells $p_j=1/k$. The binning configuration is part of the storage identity. See [binning](../binning/index.md). + +An empty observed cell returns **positive infinity**. This is the mathematical zero-count limit, not numerical failure. + +For fixed cells and sufficiently large expected counts, the usual asymptotic reference has $k-1$ degrees of freedom. Sparse counts, adaptive edges or a growing cell count need calibration for the actual binning procedure. + +## Formula + +$$ +T=2\sum_{j=1}^k E_j\log(E_j/O_j). +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + ModifiedLogLikelihoodInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = ModifiedLogLikelihoodInverseGammaGofStatistic( + parameters, binning=EqualProbabilityBins(4) +) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence family. + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/neyman_chi2_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/neyman_chi2_inverse_gamma_criterion.md new file mode 100644 index 00000000..5e41d888 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/neyman_chi2_inverse_gamma_criterion.md @@ -0,0 +1,44 @@ +# Neyman modified chi-squared for inverse gamma + +## API and hypothesis + +`NeymanChi2InverseGammaGofStatistic` has code `CHI2_NEYMAN_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Set `binning=EqualProbabilityBins(k)` to use a fixed number of cells. The default `EqualProbabilityBins()` uses the shared sample-size count rule, not a fixed eight cells. Here $O_j$ are observed counts and $E_j=n p_j>0$; for equal-probability cells $p_j=1/k$. The binning configuration is part of the storage identity. See [binning](../binning/index.md). + +An empty observed cell returns **positive infinity**. This is the mathematical zero-count limit, not numerical failure. + +For fixed cells and sufficiently large expected counts, the usual asymptotic reference has $k-1$ degrees of freedom. Sparse counts, adaptive edges or a growing cell count need calibration for the actual binning procedure. + +## Formula + +$$ +T=\sum_{j=1}^k\frac{(O_j-E_j)^2}{O_j}. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + NeymanChi2InverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = NeymanChi2InverseGammaGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), power-divergence family. + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/watson_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/watson_inverse_gamma_criterion.md new file mode 100644 index 00000000..817b26a6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/watson_inverse_gamma_criterion.md @@ -0,0 +1,41 @@ +# Watson for inverse gamma + +## API and hypothesis + +`WatsonInverseGammaGofStatistic` has code `WAT_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. Ordinary CDF values can round to zero or one in extreme tails. + +Here $W^2$ is the [Cramér–von Mises statistic](cramer_von_mises_inverse_gamma_criterion.md) and $\bar u=n^{-1}\sum_i u_i$. The implementation evaluates centered squared deviations plus $1/(12n)$ to avoid cancellation. + +## Formula + +$$ +U^2=W^2-n(\bar u-1/2)^2. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + WatsonInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = WatsonInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests](https://doi.org/10.3103/S875669901401004X), eqs. (1)–(6); [author-hosted paper](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/zhang_a_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/zhang_a_inverse_gamma_criterion.md new file mode 100644 index 00000000..a6e10aec --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/zhang_a_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Zhang A for inverse gamma + +## API and hypothesis + +`ZhangAInverseGammaGofStatistic` has code `ZAA_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. The implementation uses log-CDF and log-survival directly, without epsilon clipping. Unrepresentable log tails raise `FloatingPointError`; arithmetic overflow in the final formula can still produce infinity. + +## Formula + +$$ +Z_A=-\sum_{i=1}^n\left[\frac{\log u_i}{n-i+1/2}+\frac{\log(1-u_i)}{i-1/2}\right]. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + ZhangAInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = ZhangAInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/zhang_c_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/zhang_c_inverse_gamma_criterion.md new file mode 100644 index 00000000..e0ca6531 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/zhang_c_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Zhang C for inverse gamma + +## API and hypothesis + +`ZhangCInverseGammaGofStatistic` has code `ZAC_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. The implementation uses log-CDF and log-survival directly, without epsilon clipping. Unrepresentable log tails raise `FloatingPointError`; arithmetic overflow in the final formula can still produce infinity. + +## Formula + +$$ +Z_C=\sum_{i=1}^n\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + ZhangCInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = ZhangCInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/inverse-gamma/zhang_k_inverse_gamma_criterion.md b/docs/criteria/goodness-of-fit/inverse-gamma/zhang_k_inverse_gamma_criterion.md new file mode 100644 index 00000000..5207df17 --- /dev/null +++ b/docs/criteria/goodness-of-fit/inverse-gamma/zhang_k_inverse_gamma_criterion.md @@ -0,0 +1,39 @@ +# Zhang K for inverse gamma + +## API and hypothesis + +`ZhangKInverseGammaGofStatistic` has code `ZAK_INV_GAMMA_GOODNESS_OF_FIT`. + +Both positive parameters must be fixed before observing the sample; location is zero. No parameter fitting is performed. The input must be a nonempty one-dimensional sample of finite, strictly positive observations. Ties and constant samples are accepted; rounded observations require appropriate calibration. The result is one scalar statistic, not a p-value. Large values reject the null. + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$, $i=1,\ldots,n$, with sorted observations; $D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. The implementation uses log-CDF and log-survival directly, without epsilon clipping. Unrepresentable log tails raise `FloatingPointError`; arithmetic overflow in the final formula can still produce infinity. + +## Formula + +$$ +Z_K=\max_i\left[(i-1/2)\log\frac{i-1/2}{nu_i}+(n-i+1/2)\log\frac{n-i+1/2}{n(1-u_i)}\right]. +$$ + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import InverseGammaDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.inverse_gamma import ( + ZhangKInverseGammaGofStatistic, +) + +parameters = InverseGammaDistributionDescriptor.DEFAULT.parse({"alpha": 3.0, "beta": 2.0}) +statistic = ZhangKInverseGammaGofStatistic(parameters) +value = statistic.execute_statistic([0.35, 0.5, 0.7, 1.0, 1.5, 3.0]) +assert not np.isnan(value) +``` + +## Scientific references + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337), §§2–3; [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +These references support the statistic or its general construction, not a test +with estimated inverse-gamma parameters. See the [family overview](index.md) +and [mathematical verification](mathematical-validation.md) for calibration +and numerical qualifications. diff --git a/docs/criteria/goodness-of-fit/laplace/a_rat_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/a_rat_laplace_criterion.md new file mode 100644 index 00000000..88a44c57 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/a_rat_laplace_criterion.md @@ -0,0 +1,56 @@ +# A_RAT: fitted Laplace statistic + +Public class: `AlizadehNoughabiLikelihoodLaplaceGofStatistic`. Registry code: `A_RAT_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +Density-based empirical likelihood ratio A_rat (Noughabi, 2016). + +Minimum over integer 1 <= m < min(n**delta, n/2) of the product +2m/[n*(x_(i+m)-x_(i-m))*f_hat(x_i)]. Endpoint ranks are clamped. +Products are evaluated in log space. ``log_scale=True`` returns log(A_rat) +and requires its own calibration. Zero spacings give +infinity. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +`delta=0.5`, with `0 < delta < 1`. The window bound includes n/2 as in the comparison paper. `log_scale=False` returns the original product; overflow produces positive infinity. `log_scale=True` returns its logarithm and avoids product overflow. These settings are part of the calibration configuration. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiLikelihoodLaplaceGofStatistic, +) + +criterion = AlizadehNoughabiLikelihoodLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1007/s40304-016-0095-0) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/aj_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/aj_laplace_criterion.md new file mode 100644 index 00000000..6fe34c16 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/aj_laplace_criterion.md @@ -0,0 +1,55 @@ +# AJ: fitted Laplace statistic + +Public class: `AlizadehNoughabiJarrahiferizLaplaceGofStatistic`. Registry code: `AJ_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +Informational energy AJ: mean 2m/[n*(F_hat(x_hi)-F_hat(x_lo))]. + +Large values reject. Window m=1 by default; 1 <= m < n/2. +Zero CDF spacings yield +infinity. Same-tail differences are evaluated +with expm1 rather than subtracting rounded CDF values. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). Zero relevant spacings produce positive infinity. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiJarrahiferizLaplaceGofStatistic, +) + +criterion = AlizadehNoughabiJarrahiferizLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://www.inderscience.com/info/inarticle.php?artid=102022) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/anderson_darling_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/anderson_darling_laplace_criterion.md index 0277f156..ec511a42 100644 --- a/docs/criteria/goodness-of-fit/laplace/anderson_darling_laplace_criterion.md +++ b/docs/criteria/goodness-of-fit/laplace/anderson_darling_laplace_criterion.md @@ -1,52 +1,70 @@ -# Anderson-Darling test for Laplace distribution +# Anderson--Darling statistic for the Laplace distribution -## Description -Performs Anderson-Darling goodness-of-fit test for the hypothesis that the sample comes from a Laplace distribution. -The test gives additional weight to discrepancies in the distribution tails. +`AndersonDarlingLaplaceGofStatistic` tests independent observations from **Laplace(t, s) with +both parameters fixed in advance**. Its support is the real line. No parameters +are fitted by `execute_statistic`. -Hypothesis of Laplace Distribution -The null hypothesis is that the data comes from a Laplace distribution with location parameter `t` and positive scale parameter `s`. +## Parameters and usage -Test Statistic -The statistic is computed from the log cumulative distribution function and log survival function of the reference Laplace distribution. +`t=0.0` is a finite real scalar location; `s=1.0` is a finite positive real +scalar scale. `rvs` must be a nonempty, one-dimensional sample of finite real +numbers. A single observation, ties, and constant samples are accepted. +Invalid inputs raise `ValueError`. The sample and model are not modified. +`execute_statistic(rvs, **kwargs)` returns a scalar; extra keywords are ignored. -## Usage ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import LaplaceDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( AndersonDarlingLaplaceGofStatistic, ) - -test_statistic = AndersonDarlingLaplaceGofStatistic(t=0, s=1) -statistic_result = test_statistic.execute_statistic([-1.7, -0.9, -0.35, 0.0, 0.42, 0.88, 1.64]) -print(statistic_result) +statistic = AndersonDarlingLaplaceGofStatistic( + LaplaceDistributionDescriptor.DEFAULT.parse({"t": 0.0, "s": 1.0}) +) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) ``` -## Arguments -`t` - location parameter of the Laplace distribution. Default value is `0.0`. +## Formula and calibration -`s` - positive scale parameter of the Laplace distribution. Default value is `1.0`. +Let `u_i = F_(t,s)(x_(i))`, for sorted observations, `i=1,...,n`. +The Laplace CDF is `exp((x-t)/s)/2` for `x 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +AP_a = log(2*theta_a) + 1 - H_a; m=1 by default. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). `scale_estimator="corrected"` is the default; `"mle"` implements the corresponding maximum-likelihood-scale variant. Zero relevant spacings produce positive infinity. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiParkALaplaceGofStatistic, +) + +criterion = AlizadehNoughabiParkALaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/00949655.2015.1104685) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/ap_e_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ap_e_laplace_criterion.md new file mode 100644 index 00000000..e553455a --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ap_e_laplace_criterion.md @@ -0,0 +1,55 @@ +# AP_E: fitted Laplace statistic + +Public class: `AlizadehNoughabiParkELaplaceGofStatistic`. Registry code: `AP_E_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +AP_e = log(2*theta_e) + 1 - H_e; m=1 by default. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). `scale_estimator="corrected"` is the default; `"mle"` implements the corresponding maximum-likelihood-scale variant. Zero relevant spacings produce positive infinity. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiParkELaplaceGofStatistic, +) + +criterion = AlizadehNoughabiParkELaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/00949655.2015.1104685) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/ap_v_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ap_v_laplace_criterion.md new file mode 100644 index 00000000..df605df0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ap_v_laplace_criterion.md @@ -0,0 +1,55 @@ +# AP_V: fitted Laplace statistic + +Public class: `AlizadehNoughabiParkVLaplaceGofStatistic`. Registry code: `AP_V_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +AP_v = log(2*theta_v) + 1 - H_v; m=1 by default. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). `scale_estimator="corrected"` is the default; `"mle"` implements the corresponding maximum-likelihood-scale variant. Zero relevant spacings produce positive infinity. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiParkVLaplaceGofStatistic, +) + +criterion = AlizadehNoughabiParkVLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/00949655.2015.1104685) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/ap_y_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ap_y_laplace_criterion.md new file mode 100644 index 00000000..abeaa930 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ap_y_laplace_criterion.md @@ -0,0 +1,55 @@ +# AP_Y: fitted Laplace statistic + +Public class: `AlizadehNoughabiParkYLaplaceGofStatistic`. Registry code: `AP_Y_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +AP_y = log(2*theta_y) + 1 - H_y; m=1 by default. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). `scale_estimator="corrected"` is the default; `"mle"` implements the corresponding maximum-likelihood-scale variant. This implementation requires distinct observations; ties raise `ValueError`. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiParkYLaplaceGofStatistic, +) + +criterion = AlizadehNoughabiParkYLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/00949655.2015.1104685) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/ap_z_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ap_z_laplace_criterion.md new file mode 100644 index 00000000..8691639e --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ap_z_laplace_criterion.md @@ -0,0 +1,55 @@ +# AP_Z: fitted Laplace statistic + +Public class: `AlizadehNoughabiParkZLaplaceGofStatistic`. Registry code: `AP_Z_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +AP_z = log(2*theta_z) + 1 - H_z; m=1 by default. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). `scale_estimator="corrected"` is the default; `"mle"` implements the corresponding maximum-likelihood-scale variant. Zero relevant spacings produce positive infinity. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + AlizadehNoughabiParkZLaplaceGofStatistic, +) + +criterion = AlizadehNoughabiParkZLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/00949655.2015.1104685) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/brt_v3_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/brt_v3_laplace_criterion.md new file mode 100644 index 00000000..4d7e861d --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/brt_v3_laplace_criterion.md @@ -0,0 +1,55 @@ +# BRT_V3: fitted Laplace statistic + +Public class: `BestRaynerThasV3LaplaceGofStatistic`. Registry code: `BRT_V3_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +Rescaled smooth component V3: sqrt(n/63) times sample skewness. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: two-sided. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +The signed, rescaled components use sample central moments with divisor n. The constants 63 and 1188 normalize the limiting variances to one. They differ from the unrescaled moment components with denominators 54 and 1072.8 and from the MLE-polynomial V3/V4 in PoweR. Calibration must match this normalization. Formula reconstruction and the independent moment check are described in [fitted definitions](fitted-definitions.md). + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + BestRaynerThasV3LaplaceGofStatistic, +) + +criterion = BestRaynerThasV3LaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1016/j.csda.2008.05.023) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/brt_v4_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/brt_v4_laplace_criterion.md new file mode 100644 index 00000000..ef89f5c9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/brt_v4_laplace_criterion.md @@ -0,0 +1,55 @@ +# BRT_V4: fitted Laplace statistic + +Public class: `BestRaynerThasV4LaplaceGofStatistic`. Registry code: `BRT_V4_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +Rescaled smooth component V4: sqrt(n/1188) times (sample kurtosis - 6). + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: two-sided. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +The signed, rescaled components use sample central moments with divisor n. The constants 63 and 1188 normalize the limiting variances to one. They differ from the unrescaled moment components with denominators 54 and 1072.8 and from the MLE-polynomial V3/V4 in PoweR. Calibration must match this normalization. Formula reconstruction and the independent moment check are described in [fitted definitions](fitted-definitions.md). + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + BestRaynerThasV4LaplaceGofStatistic, +) + +criterion = BestRaynerThasV4LaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1016/j.csda.2008.05.023) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/chi2_pearson_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/chi2_pearson_laplace_criterion.md new file mode 100644 index 00000000..bcde48a7 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/chi2_pearson_laplace_criterion.md @@ -0,0 +1,71 @@ +# Pearson chi-squared test for the Laplace distribution + +## Description + +`Chi2PearsonLaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `CHI2_PEARSON_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + Chi2PearsonLaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = Chi2PearsonLaplaceGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +`binning` — keyword-only strategy, default `EqualProbabilityBins()`: +`PowerCount(coefficient=2.0, exponent=0.4)`, `min_expected=None`, `max_bins=1000`. +The support is the entire real line. Ties and constant samples are accepted. +Bins must cover the full support; expected counts are obtained from the fixed +Laplace null. No minimum expected count is imposed by default. + +## Details + +The default equal-probability bins are built in Laplace probability space, +not as equal-width intervals on the real line. With $m$ such bins, +$p_j=1/m$. Other strategies use their actual null bin probabilities. +Unknown or sample-fitted parameters are not supported. A fitted extension would +need refitting and rebuilding bins in every Monte Carlo replicate. + + +For observed bin counts $O_j$ and positive expected counts $E_j=np_j$, +where $p_j$ is the bin probability under the specified Laplace null: + +$$ +X^2=\sum_{j=1}^{m}\frac{(O_j-E_j)^2}{E_j}. +$$ + +The power-divergence parameter is $\lambda=1$. An empty observed bin contributes +$E_j$, so zero observed counts do not make this statistic infinite. + +Large values form the right-tail rejection region. Binning is reapplied for every sample. Calibrate with the same rule and sample +size; a statistic value alone is not a p-value. The default has no minimum +expected-count constraint, so a chi-squared approximation is not automatically +justified. See [binning strategies](../binning/index.md) and +[calibration storage](../binning/calibration.md). `configuration()` includes the +binning policy, while `code()` identifies the algorithm. + +## References + +Pearson, K. (1900). [On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling](https://doi.org/10.1080/14786440009463897). *Philosophical Magazine*, 50, 157–175. + +Cressie, N., and Read, T. R. C. (1984). [Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). *Journal of the Royal Statistical Society: Series B*, 46(3), 440–464. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/ck_c_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ck_c_laplace_criterion.md new file mode 100644 index 00000000..de83f8ea --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ck_c_laplace_criterion.md @@ -0,0 +1,55 @@ +# CK_C: fitted Laplace statistic + +Public class: `ChoiKimCLaplaceGofStatistic`. Registry code: `CK_C_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +CK_c = exp(H_correa) / MAD; m=1 by default, 1 <= m < n/2. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: left. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). Zero relevant spacings produce zero, a limiting left-tail statistic. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + ChoiKimCLaplaceGofStatistic, +) + +criterion = ChoiKimCLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/02331880600822473) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/ck_e_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ck_e_laplace_criterion.md new file mode 100644 index 00000000..c9745947 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ck_e_laplace_criterion.md @@ -0,0 +1,55 @@ +# CK_E: fitted Laplace statistic + +Public class: `ChoiKimELaplaceGofStatistic`. Registry code: `CK_E_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +CK_e = exp(H_van_es) / MAD; m=1 by default, 1 <= m < n/2. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: left. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). Zero relevant spacings produce zero, a limiting left-tail statistic. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + ChoiKimELaplaceGofStatistic, +) + +criterion = ChoiKimELaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/02331880600822473) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/ck_v_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ck_v_laplace_criterion.md new file mode 100644 index 00000000..807bed2d --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ck_v_laplace_criterion.md @@ -0,0 +1,55 @@ +# CK_V: fitted Laplace statistic + +Public class: `ChoiKimVLaplaceGofStatistic`. Registry code: `CK_V_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +CK_v = exp(H_v) / MAD; m=1 by default, 1 <= m < n/2. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: left. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +Window `m` is an integer, defaults to **1**, and must satisfy `1 <= m < n/2`. This default is an explicit implementation setting, not the optimized size-dependent window table in the comparison paper. Choose a window before calibration. See the exact entropy estimates and corrected scales in [fitted definitions](fitted-definitions.md). Zero relevant spacings produce zero, a limiting left-tail statistic. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + ChoiKimVLaplaceGofStatistic, +) + +criterion = ChoiKimVLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/02331880600822473) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/cressie_read_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/cressie_read_laplace_criterion.md new file mode 100644 index 00000000..9e215f98 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/cressie_read_laplace_criterion.md @@ -0,0 +1,68 @@ +# Cressie–Read test for the Laplace distribution + +## Description + +`CressieReadLaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `CRESSIE_READ_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + CressieReadLaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = CressieReadLaplaceGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +`binning` — keyword-only strategy, default `EqualProbabilityBins()`: +`PowerCount(coefficient=2.0, exponent=0.4)`, `min_expected=None`, `max_bins=1000`. +The support is the entire real line. Ties and constant samples are accepted. +Bins must cover the full support; expected counts are obtained from the fixed +Laplace null. No minimum expected count is imposed by default. + +## Details + +The default equal-probability bins are built in Laplace probability space, +not as equal-width intervals on the real line. With $m$ such bins, +$p_j=1/m$. Other strategies use their actual null bin probabilities. +Unknown or sample-fitted parameters are not supported. A fitted extension would +need refitting and rebuilding bins in every Monte Carlo replicate. + + +For observed bin counts $O_j$ and positive expected counts $E_j=np_j$, +where $p_j$ is the bin probability under the specified Laplace null: + +$$ +T_{CR}=\frac95\sum_{j=1}^{m}O_j\left[\left(\frac{O_j}{E_j}\right)^{2/3}-1\right]. +$$ + +This class fixes the power-divergence parameter at $\lambda=2/3$; there is no `lambda_` constructor argument. Terms with zero observed counts contribute zero by continuity. + +Large values form the right-tail rejection region. Binning is reapplied for every sample. Calibrate with the same rule and sample +size; a statistic value alone is not a p-value. The default has no minimum +expected-count constraint, so a chi-squared approximation is not automatically +justified. See [binning strategies](../binning/index.md) and +[calibration storage](../binning/calibration.md). `configuration()` includes the +binning policy, while `code()` identifies the algorithm. + +## References + +Cressie, N., and Read, T. R. C. (1984). [Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). *Journal of the Royal Statistical Society: Series B*, 46(3), 440–464. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/cvm_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/cvm_laplace_criterion.md index 1b6e478b..6200b8e9 100644 --- a/docs/criteria/goodness-of-fit/laplace/cvm_laplace_criterion.md +++ b/docs/criteria/goodness-of-fit/laplace/cvm_laplace_criterion.md @@ -1,57 +1,66 @@ -# Cramer-von Mises test for Laplace distribution +# Cramer--von Mises statistic for the Laplace distribution -## Description -Performs Cramer-von Mises goodness-of-fit test for the hypothesis that the sample comes from a Laplace distribution. -The statistic accumulates squared differences between empirical plotting positions and Laplace cumulative distribution function values. +`CramerVonMisesLaplaceGofStatistic` tests independent observations from **Laplace(t, s) with +both parameters fixed in advance**. Its support is the real line. No parameters +are fitted by `execute_statistic`. -Hypothesis of Laplace Distribution -The null hypothesis is that the data comes from a Laplace distribution with location parameter `t` and positive scale parameter `s`. +## Parameters and usage -Test Statistic -The observations are sorted, transformed by the reference Laplace cumulative distribution function, and compared with expected uniform plotting positions. +`t=0.0` is a finite real scalar location; `s=1.0` is a finite positive real +scalar scale. `rvs` must be a nonempty, one-dimensional sample of finite real +numbers. A single observation, ties, and constant samples are accepted. +Invalid inputs raise `ValueError`. The sample and model are not modified. +`execute_statistic(rvs, **kwargs)` returns a scalar; extra keywords are ignored. -## Usage ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import LaplaceDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( CramerVonMisesLaplaceGofStatistic, ) - -test_statistic = CramerVonMisesLaplaceGofStatistic(t=0, s=1) -statistic_result = test_statistic.execute_statistic([-1.7, -0.9, -0.35, 0.0, 0.42, 0.88, 1.64]) -print(statistic_result) +statistic = CramerVonMisesLaplaceGofStatistic( + LaplaceDistributionDescriptor.DEFAULT.parse({"t": 0.0, "s": 1.0}) +) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) ``` -## Arguments -`t` - location parameter of the Laplace distribution. Default value is `0.0`. +## Formula and calibration -`s` - positive scale parameter of the Laplace distribution. Default value is `1.0`. +Let `u_i = F_(t,s)(x_(i))`, for sorted observations, `i=1,...,n`. +The Laplace CDF is `exp((x-t)/s)/2` for `x 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +Data-driven efficient Legendre score test for fitted Laplace data. + +W_k=n*v_k'*(I-A_k*A_k')^(-1)*v_k, v=mean(phi)-A*mean(score). +Select the smallest k maximizing W_k-k*log(n), 1 <= k <= max_components. +This is an explicit Laplace specialization of the general score selection +construction, not a reproduction of the DD implementation compared in +Best et al. (2008). Calibrate by refitting simulated Laplace(0,1) samples. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +`max_components=4` by default, with integer values from 1 to 10. Numerical population integrals form the nuisance-score projection once during construction; the sample calculation uses a Numba kernel. This is a documented Laplace specialization of Janic–Ledwina, **not a verified reproduction of the DD procedure compared by Best–Rayner–Thas**. No omnibus-consistency claim is made for a fixed maximum dimension. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + DataDrivenSmoothLaplaceGofStatistic, +) + +criterion = DataDrivenSmoothLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://www.impan.pl/~ledwina/Janic-Ledwina-24-09-08.pdf) +- [Scientific source 2](https://doi.org/10.1016/j.csda.2008.05.023) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/dlo_x_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/dlo_x_laplace_criterion.md new file mode 100644 index 00000000..006416d6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/dlo_x_laplace_criterion.md @@ -0,0 +1,56 @@ +# DLO_X: fitted Laplace statistic + +Public class: `DesgagneLafayeDeMicheauxOuimetXLaplaceGofStatistic`. Registry code: `DLO_X_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +DLO_X = Z(S)^2 + Z(Knet)^2. Requires n >= 4. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +The implementation uses the parity-dependent finite-sample corrections in equations (7)–(9) of the comparison paper. It requires n >= 4, since the odd-n kurtosis variance correction is negative at n=3. Asymptotic normal/chi-square approximations are discussed for n >= 20; use simulated calibration for small samples. The full formula is in [fitted definitions](fitted-definitions.md). + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + DesgagneLafayeDeMicheauxOuimetXLaplaceGofStatistic, +) + +criterion = DesgagneLafayeDeMicheauxOuimetXLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/02331888.2022.2144859) +- [Scientific source 2](https://arxiv.org/abs/1809.02852) +- [Scientific source 3](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/dlo_z_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/dlo_z_laplace_criterion.md new file mode 100644 index 00000000..35080b97 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/dlo_z_laplace_criterion.md @@ -0,0 +1,56 @@ +# DLO_Z: fitted Laplace statistic + +Public class: `DesgagneLafayeDeMicheauxOuimetZLaplaceGofStatistic`. Registry code: `DLO_Z_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +DLO_Z = Z(Knet), signed kurtosis component. Requires n >= 4. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: two-sided. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +The implementation uses the parity-dependent finite-sample corrections in equations (7)–(9) of the comparison paper. It requires n >= 4, since the odd-n kurtosis variance correction is negative at n=3. Asymptotic normal/chi-square approximations are discussed for n >= 20; use simulated calibration for small samples. The full formula is in [fitted definitions](fitted-definitions.md). + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + DesgagneLafayeDeMicheauxOuimetZLaplaceGofStatistic, +) + +criterion = DesgagneLafayeDeMicheauxOuimetZLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1080/02331888.2022.2144859) +- [Scientific source 2](https://arxiv.org/abs/1809.02852) +- [Scientific source 3](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/fitted-definitions.md b/docs/criteria/goodness-of-fit/laplace/fitted-definitions.md new file mode 100644 index 00000000..ca794c09 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/fitted-definitions.md @@ -0,0 +1,227 @@ +# Fitted Laplace: definitions and conventions + +All statistics on this page test the composite family Laplace(t, s), s > 0. +Write n for sample size, μ̂ for the sample median (average of the two middle +observations for even n), b̂ = mean|x−μ̂|, and z_i=(x_i−μ̂)/b̂. +Let x̄ be the sample mean and s_n²=mean(x−x̄)², with divisor n throughout. +Order-statistic subscripts outside 1,…,n are clamped to the nearest endpoint. +The implementation works on standardized observations to avoid scale overflow. +Constant samples have no admissible fitted scale. + +## Characteristic-function tests + +For j=1,2, + +\[ +T_{n,a}^{(j)}=n\int_{-\infty}^{\infty} +\left|(1+t^2)n^{-1}\sum_i e^{it z_i}-1\right|^2w_j(t,a)\,dt, +\quad w_1=e^{-a|t|},\quad w_2=e^{-at^2}. +\] + +The default is MLE standardization. With `estimator="mom"`, replace z by +(x−x̄)/(s_n/√2). Both statistics reject for large values. The closed forms in +[Meintanis (2004)](https://doi.org/10.1081/STA-120028735) are evaluated without +allocating an n×n matrix. Default a values are 2 and 0.5, respectively. +The defining integral provides both an independent test and a cancellation fallback. + +## Choi–Kim entropy tests + +Choose integer 1 ≤ m < n/2 and define Δ_i=z_(i+m)−z_(i−m). + +\[ +H_v=\frac1n\sum_{i=1}^n\log\frac{n\Delta_i}{2m},\qquad +H_{\mathrm{vanEs}}=\frac1{n-m}\sum_{i=1}^{n-m}\log(z_{i+m}-z_i) ++\sum_{k=m}^{n}\frac1k. +\] + +For Correa, let z̄_i be the average of the 2m+1 clamped observations indexed +j=i−m,…,i+m. The rank j itself is not clamped: + +\[ +H_c=-\frac1n\sum_i\log +\frac{\sum_{j=i-m}^{i+m}(j-i)(z_j-\bar z_i)/n} +{\sum_{j=i-m}^{i+m}(z_j-\bar z_i)^2}. +\] + +CK_v=exp(H_v), CK_c=exp(H_c), CK_e=exp(H_vanEs) on standardized data; +in original units these are exp(H)/b̂. No extra 2e divisor is applied. +Small values reject. See [Choi–Kim (2006)](https://doi.org/10.1080/02331880600822473). + +## AP entropy tests and corrected scales + +[Alizadeh Noughabi–Park (2016)](https://doi.org/10.1080/00949655.2015.1104685) +use AP_r=log(2θ_r)+1−H_r. Their H_e is the Ebrahimi estimate, **not** van Es. +For r=v,e,a,z, + +\[ +H_r=\frac1n\sum_i\log\frac{n\Delta_i}{m c_{r,i}}, +\] + +where c_v,i=2; c_e,i=1+min(i−1,m,n−i)/m; +c_a,i=1 at i≤m or i≥n−m+1 and 2 otherwise; +c_z,i=i/m for i≤m, (n−i+1)/m for i≥n−m+1, and 2 otherwise. + +For AP_y, define B=(n−1)/(n(n+1)) and the smoothed empirical CDF values + +\[ +F_1=B\left(\frac n{n-1}+\frac n{2n-1}\right),\quad +F_n=B\left(\frac{(n-1)^2+1}{n-1}+1+\frac{n-1}{2n-1}\right), +\] + +\[ +F_i=B\left(\frac{i(n-1)+1}{n-1}+ +\frac{z_i-z_{i-1}}{z_{i+1}-z_{i-1}}\right),\quad 2\le i\le n-1. +\] + +Set d_i=F_(i+m)−F_(i−m), C=Σd_i and +H_y=Σ(d_i/C)log(Δ_i/d_i). The implementation uses the strictly increasing +sample branch of this definition: AP_y rejects tied observations explicitly. + +The corrected scale is the integral of absolute deviation of a piecewise-linear +quantile Q with knots β_i at (i−1)/n, i=1,…,n+1: + +\[ +\theta(\beta)=\int_0^1|Q(u)-Q(1/2)|\,du. +\] + +Define ξ_i=(2m)⁻¹Σ_{k=i−m}^{i+m−1}z_k. For v use β=ξ, and for y use +β_i=2mξ_i/C. For e,a,z, interior knots m+1≤i≤n−m+1 equal ξ_i; replace tails by + +\[ +\beta_i=\xi_{m+1}-\sum_{k=i}^{m}\frac{z_{m+k}-z_1}{d_{L,k}} +\quad(i\le m),\qquad +\beta_i=\xi_{n-m+1}+\sum_{k=n-m+2}^{i}\frac{z_n-z_{k-m-1}}{d_{R,k}} +\quad(i\ge n-m+2). +\] + +| Variant | d_L,k | d_R,k | +|---|---|---| +| e | m+k−1 | n+m−k+1 | +| a | m | m | +| z | k | n−k+2 | + +The integral uses trapezoids on each side of 1/2, splitting the central interval +for odd n. `scale_estimator="mle"` substitutes θ=1 on standardized data, +providing the corresponding MLE-scale variants. Large values reject. + +## Moment and smooth components + +Let g_1=mean((x−x̄)/s_n)³ and g_2=mean((x−x̄)/s_n)⁴. The signed rescaled +components are + +\[ +\widetilde V_3=\sqrt{n/63}\,g_1,\qquad +\widetilde V_4=\sqrt{n/1188}\,(g_2-6). +\] + +The moment components reported in [Batsidis et al., Section 3.3](https://www.ajs.or.at/index.php/ajs/article/download/1251/754) +use denominators 54 and 1072.8 and have asymptotic variances 7/6 and 165/149. +Rescaling gives 54·7/6=63 and 1072.8·165/149=1188. This is a reconstruction +of the unit-variance versions motivated by [Best–Rayner–Thas (2008)](https://doi.org/10.1016/j.csda.2008.05.023). +It can also be checked directly from Laplace moments: for standardized variance-one +Y, E(Y^(2k))=(2k)!/2^k. The influence functions are Y³−3Y and Y⁴−12Y²+6, +with variances 63 and 1188. Both components have two-sided rejection. + +For [Gel (2010)](https://doi.org/10.1016/j.csda.2009.10.008), put +q_j=mean((x−x̄)/(√2 b̂))^j, j=3,4: + +\[ +Ge=nq_3^2/60+n(q_4-6)^2/1200. +\] + +Large values reject. The constants are the recommended small/moderate-sample +choice, not a fitted estimate of asymptotic variances. + +The signed [González-Estrada–Villaseñor (2016)](https://doi.org/10.1016/j.spl.2016.07.003) +statistic is + +\[ +GV=2\sqrt n\left\{\frac{s_n}{\sqrt2\,\mathrm{mean}|x-\bar x|}-1\right\}. +\] + +The absolute deviations here are about the sample **mean**. Rejection is two-sided. + +## Density likelihood and informational energy + +For [Alizadeh Noughabi (2016)](https://doi.org/10.1007/s40304-016-0095-0), + +\[ +A_{rat}=\min_{1\le m<\min(n^\delta,n/2)} +\prod_{i=1}^n\frac{2m}{n\Delta_i f_{0,1}(z_i)},\qquad \delta=0.5. +\] + +Only integer windows are considered. The extra n/2 bound follows the +[comparison paper, Section 3.3](https://arxiv.org/abs/2007.06154). +The calculation sums log factors and minimizes before exponentiating. +`log_scale=True` returns the log of the minimum. Large values reject. + +For [Alizadeh Noughabi–Jarrahiferiz (2019)](https://www.inderscience.com/info/inarticle.php?artid=102022), + +\[ +AJ=\frac1n\sum_i\frac{2m}{n\{F_{0,1}(z_{i+m})-F_{0,1}(z_{i-m})\}}. +\] + +Large values reject. Tail differences use exponential identities with `expm1`. + +## DLO finite-sample scores + +The λ=1 specialization of [Desgagné–Lafaye de Micheaux–Ouimet](https://doi.org/10.1080/02331888.2022.2144859) +is implemented with the finite-sample corrections in equations (7)–(9) of the +[comparison paper](https://arxiv.org/abs/2007.06154). Define + +\[ +S=\mathrm{mean}(z),\quad K=\mathrm{mean}(|z|\log|z|),\quad +K_{net}=\max(0,K-S^2/2),\quad c=1-\gamma. +\] + +Use 0·log0=0 and Euler's constant γ. Then + +\[ +Z_S=\frac{\sqrt n S}{\sqrt{v_S}},\qquad +Z_K=\frac{\sqrt n(K_{net}^{1/4}-c^{1/4}b_K)} +{\sqrt{c^{-3/2}(\pi^2/3-3)v_K/16}}. +\] + +| n | v_S | b_K | v_K | +|---|---|---|---| +| even | 1−1.856/n^1.06 | 1−0.422/n^1.01 | 1−1.950/n^0.92+39.349/n^2.3 | +| odd | 1−0.281/n^1.03 | 1−0.198/n^0.86 | 1−3.827/n^1.04 | + +DLO_X=Z_S²+Z_K² rejects on the right; DLO_Z=Z_K is signed and two-sided. +Require n≥4. Normal/chi-square asymptotic approximations are not substituted for +finite-sample calibration. + +## Data-driven smooth adaptation + +This class specializes the general efficient-score construction and Schwarz +selection rule of [Janic–Ledwina, Sections 2–2.1](https://www.impan.pl/~ledwina/Janic-Ledwina-24-09-08.pdf) +to the Laplace MLE. It is **not** a verified implementation of the DD comparator +in Best–Rayner–Thas. + +Let φ_j(u)=√(2j+1)P_j(2u−1) for Legendre polynomials P_j. The standardized +Laplace nuisance score is s(z)=(sign z, |z|−1)', with E(ss')=I₂. +Let A_j=E[φ_j(F(Z))s(Z)'] under Z∼Laplace(0,1), and +v=mean φ(F(z))−A mean s(z). For each k=1,…,d, + +\[ +W_k=n v_{1:k}'(I_k-A_{1:k}A_{1:k}')^{-1}v_{1:k},\qquad +\hat k=\min\arg\max_k\{W_k-k\log n\}. +\] + +The statistic is W_k̂ and rejects on the right. Default d=4; integer 1≤d≤10. +Population integrals are computed at construction, not estimated from the sample. +A fixed d does not give an omnibus-consistency guarantee. + +## Shared calibration and implementation settings + +Constructor settings enter `configuration()`. Use identical sample size, window, +weight, estimation mode, score dimension and log/product convention when calibrating. +The built-in generator uses Laplace(0,1) for these invariant composite tests. +Every execution fits anew and leaves the hypothesis parameters unknown. + +All spacing windows default to m=1. This explicit choice does not reproduce the +size-dependent power-optimized tables in the comparison paper. Ties are permitted +except in AP_y; zero required spacings yield limiting zero CK or infinite AP/AJ/A_rat. +Neither known-parameter EDF tables nor critical values for a different window apply. + +[Catalog](index.md) · [Validation report](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/freeman_tukey_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/freeman_tukey_laplace_criterion.md new file mode 100644 index 00000000..6ae70a55 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/freeman_tukey_laplace_criterion.md @@ -0,0 +1,68 @@ +# Freeman–Tukey test for the Laplace distribution + +## Description + +`FreemanTukeyLaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `FREEMAN_TUKEY_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + FreemanTukeyLaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = FreemanTukeyLaplaceGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +`binning` — keyword-only strategy, default `EqualProbabilityBins()`: +`PowerCount(coefficient=2.0, exponent=0.4)`, `min_expected=None`, `max_bins=1000`. +The support is the entire real line. Ties and constant samples are accepted. +Bins must cover the full support; expected counts are obtained from the fixed +Laplace null. No minimum expected count is imposed by default. + +## Details + +The default equal-probability bins are built in Laplace probability space, +not as equal-width intervals on the real line. With $m$ such bins, +$p_j=1/m$. Other strategies use their actual null bin probabilities. +Unknown or sample-fitted parameters are not supported. A fitted extension would +need refitting and rebuilding bins in every Monte Carlo replicate. + + +For observed bin counts $O_j$ and positive expected counts $E_j=np_j$, +where $p_j$ is the bin probability under the specified Laplace null: + +$$ +T_{FT}=4\sum_{j=1}^{m}\left(\sqrt{O_j}-\sqrt{E_j}\right)^2. +$$ + +The power-divergence parameter is $\lambda=-1/2$. An empty observed bin contributes $4E_j$, so zero observed counts do not make this statistic infinite. + +Large values form the right-tail rejection region. Binning is reapplied for every sample. Calibrate with the same rule and sample +size; a statistic value alone is not a p-value. The default has no minimum +expected-count constraint, so a chi-squared approximation is not automatically +justified. See [binning strategies](../binning/index.md) and +[calibration storage](../binning/calibration.md). `configuration()` includes the +binning policy, while `code()` identifies the algorithm. + +## References + +Cressie, N., and Read, T. R. C. (1984). [Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). *Journal of the Royal Statistical Society: Series B*, 46(3), 440–464. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/ge_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/ge_laplace_criterion.md new file mode 100644 index 00000000..c2ef6290 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/ge_laplace_criterion.md @@ -0,0 +1,55 @@ +# GE: fitted Laplace statistic + +Public class: `GelLaplaceGofStatistic`. Registry code: `GE_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +Ge = n*q3^2/60 + n*(q4-6)^2/1200; qj use sqrt(2)*MAD scale. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +The constants 60 and 1200 are the small/moderate-sample choice recommended by Gel. A sample-specific/asymptotic variance estimator is not substituted. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + GelLaplaceGofStatistic, +) + +criterion = GelLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1016/j.csda.2009.10.008) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/greenwood_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/greenwood_laplace_criterion.md index f3ee4894..79b81b02 100644 --- a/docs/criteria/goodness-of-fit/laplace/greenwood_laplace_criterion.md +++ b/docs/criteria/goodness-of-fit/laplace/greenwood_laplace_criterion.md @@ -1,55 +1,68 @@ -# Greenwood test for Laplace distribution +# Greenwood statistic for the Laplace distribution -## Description -Performs Greenwood spacing goodness-of-fit test for the hypothesis that the sample comes from a Laplace distribution. -The statistic measures squared spacings after transforming observations by the Laplace cumulative distribution function. +`GreenwoodLaplaceGofStatistic` tests independent observations from **Laplace(t, s) with +both parameters fixed in advance**. Its support is the real line. No parameters +are fitted by `execute_statistic`. -Hypothesis of Laplace Distribution -The null hypothesis is that the data comes from a Laplace distribution with location parameter `t` and positive scale parameter `s`. +## Parameters and usage -Test Statistic -The statistic is based on the sum of squared spacings between consecutive probability-transformed observations. +`t=0.0` is a finite real scalar location; `s=1.0` is a finite positive real +scalar scale. `rvs` must be a nonempty, one-dimensional sample of finite real +numbers. A single observation, ties, and constant samples are accepted. +Invalid inputs raise `ValueError`. The sample and model are not modified. +`execute_statistic(rvs, **kwargs)` returns a scalar; extra keywords are ignored. -## Usage ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import LaplaceDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( GreenwoodLaplaceGofStatistic, ) - -test_statistic = GreenwoodLaplaceGofStatistic(t=0, s=1) -statistic_result = test_statistic.execute_statistic([-1.7, -0.9, -0.35, 0.0, 0.42, 0.88, 1.64]) -print(statistic_result) +statistic = GreenwoodLaplaceGofStatistic( + LaplaceDistributionDescriptor.DEFAULT.parse({"t": 0.0, "s": 1.0}) +) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) ``` -## Arguments -`t` - location parameter of the Laplace distribution. Default value is `0.0`. +## Formula and calibration -`s` - positive scale parameter of the Laplace distribution. Default value is `1.0`. +Let `u_i = F_(t,s)(x_(i))`, for sorted observations, `i=1,...,n`. +The Laplace CDF is `exp((x-t)/s)/2` for `x 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +GV = 2*sqrt(n)*(s_n/(sqrt(2)*mean|x-mean(x)|)-1). + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: two-sided. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +The mean absolute deviation in GV is centered at the **sample mean**, while the MLE scale used by most other Laplace tests is centered at the median. Standard deviation uses divisor n. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + GonzalezEstradaVillasenorLaplaceGofStatistic, +) + +criterion = GonzalezEstradaVillasenorLaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1016/j.spl.2016.07.003) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/index.md b/docs/criteria/goodness-of-fit/laplace/index.md new file mode 100644 index 00000000..aa34683f --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/index.md @@ -0,0 +1,94 @@ +# Laplace goodness-of-fit statistics + +The 19 fixed-parameter criteria below test independent observations from Laplace(t, s), with finite +location t and positive finite scale s **fixed before observing the sample**. +Construct parameters with `LaplaceDistributionDescriptor.DEFAULT.parse({'t': 0, 's': 1})`. +Missing parameters are rejected; none of these criteria estimates them. + +Import classes from `pysatl_criterion.statistics.goodness_of_fit.continuous.laplace`. + +| Criterion | Public class | Code | +|---|---|---| +| [Kolmogorov–Smirnov](kolmogorov_smirnov_laplace_criterion.md) | `KolmogorovSmirnovLaplaceGofStatistic` | `KS_LAPLACE_GOODNESS_OF_FIT` | +| [Cramér–von Mises](cvm_laplace_criterion.md) | `CramerVonMisesLaplaceGofStatistic` | `CVM_LAPLACE_GOODNESS_OF_FIT` | +| [Anderson–Darling](anderson_darling_laplace_criterion.md) | `AndersonDarlingLaplaceGofStatistic` | `AD_LAPLACE_GOODNESS_OF_FIT` | +| [Kuiper](kuiper_laplace_criterion.md) | `KuiperLaplaceGofStatistic` | `KUI_LAPLACE_GOODNESS_OF_FIT` | +| [Watson](watson_laplace_criterion.md) | `WatsonLaplaceGofStatistic` | `WAT_LAPLACE_GOODNESS_OF_FIT` | +| [Greenwood](greenwood_laplace_criterion.md) | `GreenwoodLaplaceGofStatistic` | `GRW_LAPLACE_GOODNESS_OF_FIT` | +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_laplace_criterion.md) | `KolmogorovSmirnovDPlusLaplaceGofStatistic` | `KS_PLUS_LAPLACE_GOODNESS_OF_FIT` | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_laplace_criterion.md) | `KolmogorovSmirnovDMinusLaplaceGofStatistic` | `KS_MINUS_LAPLACE_GOODNESS_OF_FIT` | +| [Liao–Shimokawa](liao_shimokawa_laplace_criterion.md) | `LiaoShimokawaLaplaceGofStatistic` | `LIAO_SHIMOKAWA_LAPLACE_GOODNESS_OF_FIT` | +| [Scaled Kuiper](kuiper_scaled_laplace_criterion.md) | `KuiperScaledLaplaceGofStatistic` | `KUIPER_SCALED_LAPLACE_GOODNESS_OF_FIT` | +| [Corrected Kuiper](kuiper_corrected_laplace_criterion.md) | `KuiperCorrectedLaplaceGofStatistic` | `KUIPER_CORRECTED_LAPLACE_GOODNESS_OF_FIT` | +| [Zhang Z_A](zhang_a_laplace_criterion.md) | `ZhangALaplaceGofStatistic` | `ZHANG_ZA_LAPLACE_GOODNESS_OF_FIT` | +| [Zhang Z_K](zhang_k_laplace_criterion.md) | `ZhangKLaplaceGofStatistic` | `ZHANG_ZK_LAPLACE_GOODNESS_OF_FIT` | +| [Zhang Z_C](zhang_c_laplace_criterion.md) | `ZhangCLaplaceGofStatistic` | `ZHANG_ZC_LAPLACE_GOODNESS_OF_FIT` | +| [Freeman–Tukey](freeman_tukey_laplace_criterion.md) | `FreemanTukeyLaplaceGofStatistic` | `FREEMAN_TUKEY_LAPLACE_GOODNESS_OF_FIT` | +| [Modified log-likelihood](modified_log_likelihood_laplace_criterion.md) | `ModifiedLogLikelihoodLaplaceGofStatistic` | `MODIFIED_LOG_LIKELIHOOD_LAPLACE_GOODNESS_OF_FIT` | +| [Neyman modified chi-squared](neyman_chi2_laplace_criterion.md) | `NeymanChi2LaplaceGofStatistic` | `CHI2_NEYMAN_LAPLACE_GOODNESS_OF_FIT` | +| [Cressie–Read](cressie_read_laplace_criterion.md) | `CressieReadLaplaceGofStatistic` | `CRESSIE_READ_LAPLACE_GOODNESS_OF_FIT` | +| [Pearson chi-squared](chi2_pearson_laplace_criterion.md) | `Chi2PearsonLaplaceGofStatistic` | `CHI2_PEARSON_LAPLACE_GOODNESS_OF_FIT` | + +`AbstractLaplaceGofStatistic` is an abstract public base, not a registered criterion. +All fixed-parameter criteria reject for large statistic values. KS additionally accepts a CDF +comparison direction; LEFT and RIGHT still use right-tail rejection. +The catalog includes 13 EDF criteria, five frequency criteria and Greenwood. +Frequency criteria accept `binning=`; calibration must use the same binning policy. + +See [mathematical validation](mathematical-validation.md) for independent checks, +implementation changes, numerical limitations and calibration requirements. + +The EDF extensions are D+, D−, Liao–Shimokawa, scaled/corrected Kuiper and +Zhang K/A/C. They use the existing shared definitions and analytic Laplace log +probabilities for tail-sensitive algorithms. The frequency extensions are Pearson, +Freeman–Tukey, modified log likelihood, Neyman and Cressie–Read. Their definitions +and binning rules are described in the [universal criteria](../universal.md). + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + Chi2PearsonLaplaceGofStatistic, + KolmogorovSmirnovDPlusLaplaceGofStatistic, +) + +parameters = LaplaceDistributionDescriptor.DEFAULT.parse({"t": 0, "s": 1}) +sample = [-2.0, -1.0, -0.5, 0.0, 0.2, 0.5, 1.0, 2.0] +d_plus = KolmogorovSmirnovDPlusLaplaceGofStatistic(parameters).execute_statistic(sample) +pearson = Chi2PearsonLaplaceGofStatistic( + parameters, binning=EqualProbabilityBins(count=4) +).execute_statistic(sample) +``` + +The legacy KS constructor still accepts `alternative_type` and `mode`. +Dedicated D+ and D− classes have distinct registry codes; all reject in the right tail. + +## Fitted location-scale family + +The package also contains 19 specialist criteria (38 concrete criteria in total). +Both parameters are unknown: pass `Distribution.DEFAULT.parse({})`. +Choi–Kim rejects for small values; V3, V4, GV and DLO_Z are signed two-sided +statistics; the other added criteria reject for large values. +Each replicate must be fitted anew. See [definitions and calibration](fitted-definitions.md). + +| Criterion | Public class | Code | +|---|---|---| +| [A_RAT](a_rat_laplace_criterion.md) | `AlizadehNoughabiLikelihoodLaplaceGofStatistic` | `A_RAT_LAPLACE_GOODNESS_OF_FIT` | +| [AJ](aj_laplace_criterion.md) | `AlizadehNoughabiJarrahiferizLaplaceGofStatistic` | `AJ_LAPLACE_GOODNESS_OF_FIT` | +| [ME1](me1_laplace_criterion.md) | `Meintanis1LaplaceGofStatistic` | `ME1_LAPLACE_GOODNESS_OF_FIT` | +| [ME2](me2_laplace_criterion.md) | `Meintanis2LaplaceGofStatistic` | `ME2_LAPLACE_GOODNESS_OF_FIT` | +| [CK_V](ck_v_laplace_criterion.md) | `ChoiKimVLaplaceGofStatistic` | `CK_V_LAPLACE_GOODNESS_OF_FIT` | +| [CK_C](ck_c_laplace_criterion.md) | `ChoiKimCLaplaceGofStatistic` | `CK_C_LAPLACE_GOODNESS_OF_FIT` | +| [CK_E](ck_e_laplace_criterion.md) | `ChoiKimELaplaceGofStatistic` | `CK_E_LAPLACE_GOODNESS_OF_FIT` | +| [AP_V](ap_v_laplace_criterion.md) | `AlizadehNoughabiParkVLaplaceGofStatistic` | `AP_V_LAPLACE_GOODNESS_OF_FIT` | +| [AP_E](ap_e_laplace_criterion.md) | `AlizadehNoughabiParkELaplaceGofStatistic` | `AP_E_LAPLACE_GOODNESS_OF_FIT` | +| [AP_Y](ap_y_laplace_criterion.md) | `AlizadehNoughabiParkYLaplaceGofStatistic` | `AP_Y_LAPLACE_GOODNESS_OF_FIT` | +| [AP_A](ap_a_laplace_criterion.md) | `AlizadehNoughabiParkALaplaceGofStatistic` | `AP_A_LAPLACE_GOODNESS_OF_FIT` | +| [AP_Z](ap_z_laplace_criterion.md) | `AlizadehNoughabiParkZLaplaceGofStatistic` | `AP_Z_LAPLACE_GOODNESS_OF_FIT` | +| [BRT_V3](brt_v3_laplace_criterion.md) | `BestRaynerThasV3LaplaceGofStatistic` | `BRT_V3_LAPLACE_GOODNESS_OF_FIT` | +| [BRT_V4](brt_v4_laplace_criterion.md) | `BestRaynerThasV4LaplaceGofStatistic` | `BRT_V4_LAPLACE_GOODNESS_OF_FIT` | +| [GE](ge_laplace_criterion.md) | `GelLaplaceGofStatistic` | `GE_LAPLACE_GOODNESS_OF_FIT` | +| [GV](gv_laplace_criterion.md) | `GonzalezEstradaVillasenorLaplaceGofStatistic` | `GV_LAPLACE_GOODNESS_OF_FIT` | +| [DLO_X](dlo_x_laplace_criterion.md) | `DesgagneLafayeDeMicheauxOuimetXLaplaceGofStatistic` | `DLO_X_LAPLACE_GOODNESS_OF_FIT` | +| [DLO_Z](dlo_z_laplace_criterion.md) | `DesgagneLafayeDeMicheauxOuimetZLaplaceGofStatistic` | `DLO_Z_LAPLACE_GOODNESS_OF_FIT` | +| [DD_SMOOTH](dd_smooth_laplace_criterion.md) | `DataDrivenSmoothLaplaceGofStatistic` | `DD_SMOOTH_LAPLACE_GOODNESS_OF_FIT` | diff --git a/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_d_minus_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_d_minus_laplace_criterion.md new file mode 100644 index 00000000..3c3b0ceb --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_d_minus_laplace_criterion.md @@ -0,0 +1,62 @@ +# Kolmogorov–Smirnov D− test for the Laplace distribution + +## Description + +`KolmogorovSmirnovDMinusLaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `KS_MINUS_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + KolmogorovSmirnovDMinusLaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = KolmogorovSmirnovDMinusLaplaceGofStatistic(parameters) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +The support is the entire real line. Singletons, ties and constant samples are +accepted. Empty, nonfinite, complex and multidimensional samples are rejected. + +## Details + +Writing $z=(x-t)/s$, the Laplace CDF is $F_{t,s}(x)=e^z/2$ for $z<0$ +and $F_{t,s}(x)=1-e^{-z}/2$ otherwise. For a fixed continuous null the +probability integral transform gives independent uniforms. Its null law depends +on sample size, not the known location or scale. Parameters estimated from the +sample require a different test and calibration with refitting in every replicate. +Rounding-induced ties require a matching observation model during calibration. + + +Let $u_i=F_{t,s}(X_{(i)})$ for the sorted sample, with $n$ observations. + +$$ +D_n^- = \max_{1\le i\le n}\left(u_i-\frac{i-1}{n}\right). +$$ + +This is the unscaled negative EDF deviation. Large values indicate an empirical CDF below the null CDF, corresponding to observations tending toward larger values. The statistic uses a right-tail rejection region even though the EDF deviation is one-sided. + +Large statistic values form the rejection region. `execute_statistic` returns +the statistic only. Use a null distribution calibrated for this class and sample +size, for example with `MonteCarloLimitDistributionResolver`. Parameters remain +fixed throughout calibration. + +## References + +Smirnov, N. (1948). [Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). *Annals of Mathematical Statistics*, 19(2), 279–281. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_d_plus_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_d_plus_laplace_criterion.md new file mode 100644 index 00000000..14b964fb --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_d_plus_laplace_criterion.md @@ -0,0 +1,62 @@ +# Kolmogorov–Smirnov D+ test for the Laplace distribution + +## Description + +`KolmogorovSmirnovDPlusLaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `KS_PLUS_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + KolmogorovSmirnovDPlusLaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = KolmogorovSmirnovDPlusLaplaceGofStatistic(parameters) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +The support is the entire real line. Singletons, ties and constant samples are +accepted. Empty, nonfinite, complex and multidimensional samples are rejected. + +## Details + +Writing $z=(x-t)/s$, the Laplace CDF is $F_{t,s}(x)=e^z/2$ for $z<0$ +and $F_{t,s}(x)=1-e^{-z}/2$ otherwise. For a fixed continuous null the +probability integral transform gives independent uniforms. Its null law depends +on sample size, not the known location or scale. Parameters estimated from the +sample require a different test and calibration with refitting in every replicate. +Rounding-induced ties require a matching observation model during calibration. + + +Let $u_i=F_{t,s}(X_{(i)})$ for the sorted sample, with $n$ observations. + +$$ +D_n^+ = \max_{1\le i\le n}\left(\frac{i}{n}-u_i\right). +$$ + +This is the unscaled positive EDF deviation. Large values indicate an empirical CDF above the null CDF, corresponding to observations tending toward smaller values. The statistic uses a right-tail rejection region even though the EDF deviation is one-sided. + +Large statistic values form the rejection region. `execute_statistic` returns +the statistic only. Use a null distribution calibrated for this class and sample +size, for example with `MonteCarloLimitDistributionResolver`. Parameters remain +fixed throughout calibration. + +## References + +Smirnov, N. (1948). [Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). *Annals of Mathematical Statistics*, 19(2), 279–281. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_laplace_criterion.md index 963009d7..f191dacc 100644 --- a/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_laplace_criterion.md +++ b/docs/criteria/goodness-of-fit/laplace/kolmogorov_smirnov_laplace_criterion.md @@ -1,61 +1,74 @@ -# Kolmogorov-Smirnov test for Laplace distribution +# Kolmogorov--Smirnov statistic for the Laplace distribution -## Description -Performs Kolmogorov-Smirnov goodness-of-fit test for the hypothesis that the sample comes from a Laplace distribution. -The statistic compares the empirical distribution function with the theoretical Laplace cumulative distribution function. +`KolmogorovSmirnovLaplaceGofStatistic` tests independent observations from **Laplace(t, s) with +both parameters fixed in advance**. Its support is the real line. No parameters +are fitted by `execute_statistic`. -Hypothesis of Laplace Distribution -The null hypothesis is that the data comes from a Laplace distribution with location parameter `t` and positive scale parameter `s`. +## Parameters and usage -Test Statistic -The statistic is based on the maximum distance between the empirical distribution function and the reference Laplace cumulative distribution function. +`t=0.0` is a finite real scalar location; `s=1.0` is a finite positive real +scalar scale. `rvs` must be a nonempty, one-dimensional sample of finite real +numbers. A single observation, ties, and constant samples are accepted. +Invalid inputs raise `ValueError`. The sample and model are not modified. +`execute_statistic(rvs, **kwargs)` returns a scalar; extra keywords are ignored. -## Usage ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import LaplaceDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( KolmogorovSmirnovLaplaceGofStatistic, ) - -test_statistic = KolmogorovSmirnovLaplaceGofStatistic(t=0, s=1) -statistic_result = test_statistic.execute_statistic([-1.7, -0.9, -0.35, 0.0, 0.42, 0.88, 1.64]) -print(statistic_result) +statistic = KolmogorovSmirnovLaplaceGofStatistic( + LaplaceDistributionDescriptor.DEFAULT.parse({"t": 0.0, "s": 1.0}) +) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) ``` -## Arguments -`t` - location parameter of the Laplace distribution. Default value is `0.0`. - -`s` - positive scale parameter of the Laplace distribution. Default value is `1.0`. - -`alternative_type` - alternative hypothesis type used by the Kolmogorov-Smirnov statistic. - -`mode` - calculation mode passed to the Kolmogorov-Smirnov statistic. Default value is `auto`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Laplace cumulative distribution function - -$$ F_0(x) = F_{\mathrm{Laplace}(t, s)}(x) $$ - -for the ordered observations and passes these values to the common Kolmogorov-Smirnov statistic implementation. +## Formula and calibration -## Author(s) -Kirill Tahmazidi, Alexey Mironov +Let `u_i = F_(t,s)(x_(i))`, for sorted observations, `i=1,...,n`. +The Laplace CDF is `exp((x-t)/s)/2` for `x0 expected counts for exhaustive bins. +With equal-probability bins E_j=n/m. Explicit or adaptive strategies can have +unequal expected counts. For each of the five classes, independent counts +(2,3,4,5) and equal expected counts are compared with SciPy `power_divergence`. + +| Code and page | Formula | SciPy λ | Empty observed bin | +|---|---|---:|---| +| [CHI2_PEARSON](chi2_pearson_laplace_criterion.md) | Σ(O_j−E_j)²/E_j | 1 | contributes E_j | +| [FREEMAN_TUKEY](freeman_tukey_laplace_criterion.md) | 4Σ(√O_j−√E_j)² | −1/2 | contributes 4E_j | +| [MODIFIED_LOG_LIKELIHOOD](modified_log_likelihood_laplace_criterion.md) | 2Σ E_j log(E_j/O_j) | −1 | +infinity | +| [CHI2_NEYMAN](neyman_chi2_laplace_criterion.md) | Σ(O_j−E_j)²/O_j | −2 | +infinity | +| [CRESSIE_READ](cressie_read_laplace_criterion.md) | (9/5)Σ O_j[(O_j/E_j)^(2/3)−1] | 2/3 | zero contribution in this expression | + +These are the shared power-divergence definitions documented with the Pearson +and Cressie–Read references on the criterion pages. Cressie–Read fixes λ=2/3; +there is no `lambda_` constructor option. Modified log likelihood uses E_j in +the weight and differs from the ordinary G statistic (λ=0). + +### Extreme-value checks for the original six criteria + +For (-a,0,a), A² approaches 2a/3+8log(2)/3−3 as a grows. +At a=10^308 the result remains representable. This detects premature overflow +when tail logs are added before normalization. Watson at n=1 equals 1/12 +for every observation; equally spaced midpoint probabilities give 1/(12n). +Location-scale transformations are checked independently for all six criteria. + +## Changes and compatibility + +- Converted `continuous/laplace.py` into a package with explicit exports and a + generated `__init__.pyi`; generator supports `--check` without importing the package. +- Preserved all six public class names, short codes and the `continuous.laplace` + module identity used by pickle. The abstract family no longer declares hypotheses; + concrete classes and factory specifications declare both parameters fixed. +- All 13 EDF and five frequency criteria use shared factories and kernels. + Greenwood is the only manually declared concrete class. Generated KS retains + its existing constructor through the factory compatibility option; its former + call to the removed multi-argument KS interface is corrected. +- `do_execute_statistic(sample)` remains an observation-based compatibility entry + point. Private `_calculate_statistic` helpers were removed; benchmark scripts now + use the public `execute_statistic` API. `mode` remains a compatibility setting. +- Analytic CDF and log probabilities and Greenwood spacings are static cached + Numba methods. No numerical helpers remain outside classes. +- Shared AD log evaluation now weights each tail before adding, avoiding intermediate + overflow. The mathematical definition and calibration scale are unchanged. +- A factory validation callback retains Laplace's rejection of strings and other + nonnumeric inputs. Masked observations are now rejected instead of silently used. + +## Input and calibration limits + +Nonempty one-dimensional finite real samples are required. Singletons, ties, +constant samples and gaps of any width are allowed. The support is the entire +real line. EDF and Greenwood require no binning; ties give zero spacings. +Frequency criteria use a configurable binning strategy and positive expected +counts. Empty observed bins are handled as specified in the table above. The exact continuous null calibration assumes continuous observations; +rounding-induced ties require a matching observation model in simulation. + +For EDF and Greenwood, the PIT gives a parameter-free null law at fixed n when +both parameters are known. Frequency calibration must also match `binning`, +including adaptive bin selection; arbitrary binning is not parameter-free. The +default has no minimum expected-count constraint, so a chi-squared approximation +is not automatically justified. See [binning calibration](../binning/calibration.md). +Monte Carlo must call the same statistic, including the KS direction. Stored KS +calibration is rejected for LEFT/RIGHT because its key does not encode direction. +Fitting t or s outside this API does not justify using the known-parameter null law; +a fitted test would need a separately supported hypothesis and refitting in every +simulation. All 19 criteria use the right rejection tail. Greenwood's right-tail +form detects clustering; universal consistency is not asserted. + +CDF rounding can erase tiny tail spacings. AD, Liao–Shimokawa and Zhang K/A/C +use analytic log tails instead of reconstructing rounded tail probabilities. Standardization avoids overflow in x−t when the quotient +is representable; a result beyond float64 range is still +infinity. No clipping +or Python high-precision fallback is used. Warm timing includes validation, +sorting, CDF evaluation and the shared kernel. + +## Reproducible checks + +```text +.venv/bin/python -m pytest tests/distributions/test_laplace.py tests/distributions/test_laplace_correctness.py tests/statistics/test_laplace_architecture.py tests/statistics/test_edf.py -q +.venv/bin/python scripts/generate_laplace_stub.py --check +.venv/bin/python -m mkdocs build --strict +PYTHONPATH=src .venv/bin/python benchmarks/benchmark_laplace_pipeline.py +``` + +The ordinary pytest run is blocked during collection by an existing unrelated +import of `AbstractChi2Statistic` from `edf` in `exponentiated_weibull.py`. +An isolated run bypasses only `continuous/__init__.py` using a package placeholder; +it loads real Laplace, factory, EDF, distribution and resolver implementations. +Registry assertions in that run verify the Laplace subtree, not successful loading +of the entire project's registry. This distinction also applies to benchmarks. + +### Results (2026-10-16) + +- **478 tests passed in an isolated run** covering Laplace, shared EDF kernels + and Uniform/Pareto factory regressions. Checks include independent formulas, + integrals, SciPy power divergences, extreme tails, input validation, KS options, + pickle, registry uniqueness, nopython dispatch, stub and catalog coverage. +- Ruff on changed Python files and generated stub: passed. Stub `--check`: passed. +- MkDocs normal build: passed. Strict build: blocked by 85 pre-existing warnings + elsewhere (including missing normality and Weibull audit links); no Laplace warning. +- Instance pickle now serializes plain parameter values and reconstructs the + supported Laplace schema, avoiding the shared immutable mapping's pickle error. + +The following measurements cover the original six criteria only. No timing claim +is made for the 13 additional variants. Measured on the local Python 3.11 environment, n=10,000, seed 42, best of three +batches of 200 calls. Both paths include sorting; the reference uses SciPy CDFs +and independent NumPy formulas. These are local measurements, not guarantees. + +| Code | First call, ms | Warm public call, µs | SciPy reference, µs | Speed ratio | +|---|---:|---:|---:|---:| +| AD | 83.422 | 370.70 | 498.09 | 1.34× | +| CVM | 4.595 | 301.00 | 415.27 | 1.38× | +| GRW | 1.955 | 294.14 | 414.08 | 1.41× | +| KS | 3.229 | 320.25 | 424.47 | 1.33× | +| KUI | 3.636 | 319.63 | 423.42 | 1.32× | +| WAT | 3.032 | 317.74 | 418.28 | 1.32× | + +First-call time includes Numba initialization/cache loading and is excluded from +warm measurements; it is not a measurement of compiler time alone. All numerical +kernels use `nopython=True, cache=True`. Avoiding duplicate validation and sorting +in the factory callback improved the full generated-criterion path. + + +## Documentation coverage + +All 19 concrete classes have individual pages linked from the catalog and MkDocs +navigation. Each page states the fixed null, formula, input limits, rejection +direction, calibration requirements, an executable example and scientific sources. +`mathematical-validation.md` summarizes verification; it does not replace those pages. + +## Fitted-test audit + +The added formulas follow the original article citations in each class and +[Desgagné–Lafaye de Micheaux–Ouimet, comparison, Section 3](https://arxiv.org/abs/2007.06154). +[Exact definitions](fitted-definitions.md) record all estimator and normalization choices. + +Independent checks in `tests/statistics/test_laplace_published.py` cover: + +- Meintanis: numerical integration of the squared empirical-characteristic-function discrepancy, both weights and both parameter estimators. +- Choi–Kim: direct spacings, van Es harmonic correction and independent regression slopes for Correa. +- AP: entropy spacings and numerical integration of the absolute deviation of the reconstructed piecewise-linear quantile; corrected and MLE variants. +- Gel, GV and rescaled V3/V4: direct sample central moments and the correct centering of absolute deviations. +- A_rat: direct products over every admissible integer window; optional log transform checked separately. +- AJ: independent SciPy fitted CDF differences. +- DLO: even/odd corrections checked at n=4, 5, 20, 21, including the zero-log-zero convention. +- Data-driven smooth: independent population integrals in observation coordinates, covariance solve and Schwarz selection. +- All added classes: hypothesis capabilities, registry/pickle, affine invariance, permutation invariance, finite-real input validation, no sample mutation and calibration sampler resolution. + +### Explicit adaptations and limits + +Entropy windows default to m=1 rather than silently extrapolating power-optimal tables. +AP_y rejects ties; other spacing tests use their limiting zero/infinite statistic when +a required spacing vanishes. A_rat uses the additional n/2 upper window bound from +the comparison, and offers an explicit log-scale option. DLO starts at n=4 because +its finite-sample odd-n variance correction is invalid at n=3. + +The smooth moment components are rescaled to asymptotic unit variance (63 and 1188). +Their reconstruction uses the moment components and variances reported in +[Batsidis, Economou and Bar-Lev (2022), Section 3.3](https://www.ajs.or.at/index.php/ajs/article/download/1251/754), +and is independently checked using Laplace moments. The original Best et al. full +text was unavailable; no unverified DD formula is attributed to it. +The data-driven class is explicitly a Laplace specialization of the general +[Janic–Ledwina score construction](https://www.impan.pl/~ledwina/Janic-Ledwina-24-09-08.pdf), +not a replication of the DD comparator in Best et al. + +Most arithmetic runs in cached nopython kernels. Meintanis has a quadrature fallback +for cancellation/extreme weights. Data-driven population matrices are computed once +per instance with SciPy, outside the sample kernel. Fitting/validation remains NumPy. diff --git a/docs/criteria/goodness-of-fit/laplace/me1_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/me1_laplace_criterion.md new file mode 100644 index 00000000..3eafa216 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/me1_laplace_criterion.md @@ -0,0 +1,55 @@ +# ME1: fitted Laplace statistic + +Public class: `Meintanis1LaplaceGofStatistic`. Registry code: `ME1_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +T_(n,a)^(1): n integral |(1+t^2) mean exp(it*z)-1|^2 w_a(t) dt. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +`a > 0` selects the weight; defaults are 2 for ME1 and 0.5 for ME2. `estimator="mle"` uses median/MAD, while `"mom"` uses mean and sqrt(variance/2). Closed-form kernels use O(n²) time and O(n) memory. For cancellation or weights outside [0.01, 10], adaptive quadrature evaluates the defining integral; failure to converge raises `ArithmeticError`. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + Meintanis1LaplaceGofStatistic, +) + +criterion = Meintanis1LaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1081/STA-120028735) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/me2_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/me2_laplace_criterion.md new file mode 100644 index 00000000..5aa35264 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/me2_laplace_criterion.md @@ -0,0 +1,55 @@ +# ME2: fitted Laplace statistic + +Public class: `Meintanis2LaplaceGofStatistic`. Registry code: `ME2_LAPLACE_GOODNESS_OF_FIT`. + +## Hypothesis and definition + +H0: independent observations follow Laplace(t, s) for some unknown t and s > 0. +Pass `Distribution.DEFAULT.parse({})`. Fixed or partially fixed parameters are rejected. + +T_(n,a)^(2): n integral |(1+t^2) mean exp(it*z)-1|^2 w_a(t) dt. + +Composite Laplace null: both location and scale are unknown. +Use Distribution.DEFAULT.parse({}); refit on every simulated sample. +Rejection direction: right. Constant samples are invalid. + +The exact mathematical definitions and notation are in [fitted definitions](fitted-definitions.md). + +## Options and limitations + +`a > 0` selects the weight; defaults are 2 for ME1 and 0.5 for ME2. `estimator="mle"` uses median/MAD, while `"mom"` uses mean and sqrt(variance/2). Closed-form kernels use O(n²) time and O(n) memory. For cancellation or weights outside [0.01, 10], adaptive quadrature evaluates the defining integral; failure to converge raises `ArithmeticError`. + +Input must be a finite, real, one-dimensional nonconstant sample with n >= 3 +(n >= 4 for DLO). Sorting does not modify the caller's sample. Extreme floating +point shifts can erase differences before execution; no implementation can recover +those differences. These methods return a statistic, not a p-value. + +## Calibration + +Use the statistic's declared rejection direction. Simulate independent Laplace(0,1) +samples of the same size and call `execute_statistic` on every replicate, preserving +all constructor settings. Location and scale are re-estimated on each call. +`get_hypothesis_generator` selects the standard representative while the public +hypothesis retains both parameters as unknown. Fixed-parameter EDF critical values +are not applicable. + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + Meintanis2LaplaceGofStatistic, +) + +criterion = Meintanis2LaplaceGofStatistic(Distribution.DEFAULT.parse({})) +value = criterion.execute_statistic([-3.2, -1.4, -0.8, -0.1, 0.05, 0.5, 0.9, 1.7, 4.1]) +assert np.isfinite(value) +``` + +## Scientific references + +- [Scientific source 1](https://doi.org/10.1081/STA-120028735) +- [Scientific source 2](https://arxiv.org/abs/2007.06154) + +[Catalog](index.md) · [Mathematical validation](mathematical-validation.md) diff --git a/docs/criteria/goodness-of-fit/laplace/modified_log_likelihood_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/modified_log_likelihood_laplace_criterion.md new file mode 100644 index 00000000..9cc4ba19 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/modified_log_likelihood_laplace_criterion.md @@ -0,0 +1,70 @@ +# Modified log-likelihood test for the Laplace distribution + +## Description + +`ModifiedLogLikelihoodLaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `MODIFIED_LOG_LIKELIHOOD_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + ModifiedLogLikelihoodLaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = ModifiedLogLikelihoodLaplaceGofStatistic( + parameters, binning=EqualProbabilityBins(count=3) +) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +`binning` — keyword-only strategy, default `EqualProbabilityBins()`: +`PowerCount(coefficient=2.0, exponent=0.4)`, `min_expected=None`, `max_bins=1000`. +The support is the entire real line. Ties and constant samples are accepted. +Bins must cover the full support; expected counts are obtained from the fixed +Laplace null. No minimum expected count is imposed by default. + +## Details + +The default equal-probability bins are built in Laplace probability space, +not as equal-width intervals on the real line. With $m$ such bins, +$p_j=1/m$. Other strategies use their actual null bin probabilities. +Unknown or sample-fitted parameters are not supported. A fitted extension would +need refitting and rebuilding bins in every Monte Carlo replicate. + + +For observed bin counts $O_j$ and positive expected counts $E_j=np_j$, +where $p_j$ is the bin probability under the specified Laplace null: + +$$ +T_{ML}=2\sum_{j=1}^{m}E_j\log\frac{E_j}{O_j}. +$$ + +This is the $\lambda=-1$ power divergence, with expected counts multiplying the log ratio. It differs from the ordinary likelihood-ratio G statistic ($\lambda=0$). Any zero observed count produces positive infinity. + +Large values form the right-tail rejection region. Binning is reapplied for every sample. Calibrate with the same rule and sample +size; a statistic value alone is not a p-value. The default has no minimum +expected-count constraint, so a chi-squared approximation is not automatically +justified. See [binning strategies](../binning/index.md) and +[calibration storage](../binning/calibration.md). `configuration()` includes the +binning policy, while `code()` identifies the algorithm. + +## References + +Cressie, N., and Read, T. R. C. (1984). [Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). *Journal of the Royal Statistical Society: Series B*, 46(3), 440–464. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/neyman_chi2_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/neyman_chi2_laplace_criterion.md new file mode 100644 index 00000000..e5a032e7 --- /dev/null +++ b/docs/criteria/goodness-of-fit/laplace/neyman_chi2_laplace_criterion.md @@ -0,0 +1,68 @@ +# Neyman modified chi-squared test for the Laplace distribution + +## Description + +`NeymanChi2LaplaceGofStatistic` tests the fully specified null $H_0: X \sim \operatorname{Laplace}(t,s)$. +Its algorithm code is `CHI2_NEYMAN_LAPLACE_GOODNESS_OF_FIT`. + +## Usage + +```python +from pysatl_criterion.distribution import LaplaceDistributionDescriptor as Laplace +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import ( + NeymanChi2LaplaceGofStatistic, +) + +parameters = Laplace.DEFAULT.parse({"t": 0, "s": 1}) +criterion = NeymanChi2LaplaceGofStatistic(parameters, binning=EqualProbabilityBins(count=3)) +statistic = criterion.execute_statistic([-2.0, -1.0, -0.2, 0.2, 1.0, 2.0]) +print(statistic) +``` + +## Arguments + +`parameters` — `ParameterValues` with finite location `t` and positive finite +scale `s`, both fixed before observing the sample. Missing parameters are +unsupported. No parameters are estimated by this criterion. + +`rvs` — a nonempty, one-dimensional sample of finite real observations. + +`binning` — keyword-only strategy, default `EqualProbabilityBins()`: +`PowerCount(coefficient=2.0, exponent=0.4)`, `min_expected=None`, `max_bins=1000`. +The support is the entire real line. Ties and constant samples are accepted. +Bins must cover the full support; expected counts are obtained from the fixed +Laplace null. No minimum expected count is imposed by default. + +## Details + +The default equal-probability bins are built in Laplace probability space, +not as equal-width intervals on the real line. With $m$ such bins, +$p_j=1/m$. Other strategies use their actual null bin probabilities. +Unknown or sample-fitted parameters are not supported. A fitted extension would +need refitting and rebuilding bins in every Monte Carlo replicate. + + +For observed bin counts $O_j$ and positive expected counts $E_j=np_j$, +where $p_j$ is the bin probability under the specified Laplace null: + +$$ +T_N=\sum_{j=1}^{m}\frac{(O_j-E_j)^2}{O_j}. +$$ + +The power-divergence parameter is $\lambda=-2$. The denominator contains observed counts, so any empty observed bin produces positive infinity. This is the frequency-based Neyman statistic; it is not a Neyman smooth test. + +Large values form the right-tail rejection region. Binning is reapplied for every sample. Calibrate with the same rule and sample +size; a statistic value alone is not a p-value. The default has no minimum +expected-count constraint, so a chi-squared approximation is not automatically +justified. See [binning strategies](../binning/index.md) and +[calibration storage](../binning/calibration.md). `configuration()` includes the +binning policy, while `code()` identifies the algorithm. + +## References + +Cressie, N., and Read, T. R. C. (1984). [Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). *Journal of the Royal Statistical Society: Series B*, 46(3), 440–464. + +See the [Laplace criterion catalog](index.md) for the other implementations. + +See [mathematical validation](mathematical-validation.md) for implementation checks and limits. diff --git a/docs/criteria/goodness-of-fit/laplace/watson_laplace_criterion.md b/docs/criteria/goodness-of-fit/laplace/watson_laplace_criterion.md index a2aef9a9..86ecf682 100644 --- a/docs/criteria/goodness-of-fit/laplace/watson_laplace_criterion.md +++ b/docs/criteria/goodness-of-fit/laplace/watson_laplace_criterion.md @@ -1,52 +1,68 @@ -# Watson test for Laplace distribution +# Watson statistic for the Laplace distribution -## Description -Performs Watson goodness-of-fit test for the hypothesis that the sample comes from a Laplace distribution. -The Watson statistic is a centered modification of the Cramer-von Mises statistic. +`WatsonLaplaceGofStatistic` tests independent observations from **Laplace(t, s) with +both parameters fixed in advance**. Its support is the real line. No parameters +are fitted by `execute_statistic`. -Hypothesis of Laplace Distribution -The null hypothesis is that the data comes from a Laplace distribution with location parameter `t` and positive scale parameter `s`. +## Parameters and usage -Test Statistic -The statistic removes the squared mean deviation of the probability-transformed observations from the Cramer-von Mises statistic. +`t=0.0` is a finite real scalar location; `s=1.0` is a finite positive real +scalar scale. `rvs` must be a nonempty, one-dimensional sample of finite real +numbers. A single observation, ties, and constant samples are accepted. +Invalid inputs raise `ValueError`. The sample and model are not modified. +`execute_statistic(rvs, **kwargs)` returns a scalar; extra keywords are ignored. -## Usage ```python -from pysatl_criterion.statistics.goodness_of_fit import ( - WatsonLaplaceGofStatistic, -) - +from pysatl_criterion.distribution import LaplaceDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.laplace import WatsonLaplaceGofStatistic -test_statistic = WatsonLaplaceGofStatistic(t=0, s=1) -statistic_result = test_statistic.execute_statistic([-1.7, -0.9, -0.35, 0.0, 0.42, 0.88, 1.64]) -print(statistic_result) +statistic = WatsonLaplaceGofStatistic( + LaplaceDistributionDescriptor.DEFAULT.parse({"t": 0.0, "s": 1.0}) +) +value = statistic.execute_statistic([-1.0, 0.0, 0.5, 2.0]) ``` -## Arguments -`t` - location parameter of the Laplace distribution. Default value is `0.0`. +## Formula and calibration + +Let `u_i = F_(t,s)(x_(i))`, for sorted observations, `i=1,...,n`. +The Laplace CDF is `exp((x-t)/s)/2` for `x0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1)[\log u_i+\log(1-u_{n+1-i})] +$$ + +Logarithmic tails are evaluated directly from $z=\beta(\log x-\log\alpha)$, without clipping probabilities. A result beyond float64 range can be positive infinity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + AndersonDarlingLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = AndersonDarlingLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)); [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437) diff --git a/docs/criteria/goodness-of-fit/log-logistic/cressie-read.md b/docs/criteria/goodness-of-fit/log-logistic/cressie-read.md new file mode 100644 index 00000000..a32ae4ae --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/cressie-read.md @@ -0,0 +1,69 @@ +# CressieReadLogLogisticGofStatistic + +Cressie–Read for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +T=\frac95\sum_j O_j[(O_j/E_j)^{2/3}-1] +$$ + +Here $O_j$ are observed cell counts and $E_j=np_j>0$ are null expected +counts, with equal totals. The keyword `binning` accepts a `BinningStrategy`. +The default `EqualProbabilityBins()` uses `PowerCount()` (at least two cells, +approximately $2n^{0.4}$, rounded up, subject to `max_bins`). To fix the number, +use `EqualProbabilityBins(5)`. Internal boundaries belong to the cell on the +right. The default does not merge small expected counts. +See [binning strategies](../binning/index.md). + +The summand for $O_j=0$ is zero by continuity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + CressieReadLogLogisticGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = CressieReadLogLogisticGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) diff --git a/docs/criteria/goodness-of-fit/log-logistic/cvm.md b/docs/criteria/goodness-of-fit/log-logistic/cvm.md new file mode 100644 index 00000000..d4ee8e5f --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/cvm.md @@ -0,0 +1,58 @@ +# CramerVonMisesLogLogisticGofStatistic + +Cramér–von Mises for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +W^2=\frac1{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2 +$$ + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + CramerVonMisesLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = CramerVonMisesLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/freeman-tukey.md b/docs/criteria/goodness-of-fit/log-logistic/freeman-tukey.md new file mode 100644 index 00000000..15739b89 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/freeman-tukey.md @@ -0,0 +1,69 @@ +# FreemanTukeyLogLogisticGofStatistic + +Freeman–Tukey for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +T=4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2 +$$ + +Here $O_j$ are observed cell counts and $E_j=np_j>0$ are null expected +counts, with equal totals. The keyword `binning` accepts a `BinningStrategy`. +The default `EqualProbabilityBins()` uses `PowerCount()` (at least two cells, +approximately $2n^{0.4}$, rounded up, subject to `max_bins`). To fix the number, +use `EqualProbabilityBins(5)`. Internal boundaries belong to the cell on the +right. The default does not merge small expected counts. +See [binning strategies](../binning/index.md). + +An empty observed cell contributes $4E_j$. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + FreemanTukeyLogLogisticGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = FreemanTukeyLogLogisticGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) diff --git a/docs/criteria/goodness-of-fit/log-logistic/index.md b/docs/criteria/goodness-of-fit/log-logistic/index.md new file mode 100644 index 00000000..1cd3feb8 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/index.md @@ -0,0 +1,81 @@ +# Log-logistic goodness-of-fit statistics + +The family has **20 concrete criteria**: 13 EDF, 5 frequency and 2 fitted-model +statistics. [Mathematical verification](mathematical-validation.md) records the +formula audit, numerical checks, corrections and calibration limitations. + +For $x>0$ the distribution is + +$$ +F_{\alpha,\beta}(x)=\frac1{1+(\alpha/x)^\beta},\qquad +\alpha>0,\quad\beta>0. +$$ + +Equivalently, $\log X$ is logistic with location $\log\alpha$ and scale $1/\beta$. +CDF and logarithmic tails are evaluated through logarithms to avoid overflow of +$x/\alpha$. All criteria reject for large values. Their output is a statistic, +not a calibrated p-value. + +## Catalog + +Each class name below has the suffix `LogLogisticGofStatistic`. + +| Criterion | Class prefix | Hypothesis | Input | +|---|---|---|---| +| [Kolmogorov–Smirnov D+](ks-plus.md) | `KolmogorovSmirnovDPlus` | Both parameters fixed | Complete positive sample | +| [Kolmogorov–Smirnov D−](ks-minus.md) | `KolmogorovSmirnovDMinus` | Both parameters fixed | Complete positive sample | +| [Kolmogorov–Smirnov](ks.md) | `KolmogorovSmirnov` | Both parameters fixed | Complete positive sample | +| [Anderson–Darling](ad.md) | `AndersonDarling` | Both parameters fixed | Complete positive sample | +| [Cramér–von Mises](cvm.md) | `CramerVonMises` | Both parameters fixed | Complete positive sample | +| [Liao–Shimokawa](liao-shimokawa.md) | `LiaoShimokawa` | Both parameters fixed | Complete positive sample | +| [Watson](watson.md) | `Watson` | Both parameters fixed | Complete positive sample | +| [Kuiper](kuiper.md) | `Kuiper` | Both parameters fixed | Complete positive sample | +| [Scaled Kuiper](kuiper-scaled.md) | `KuiperScaled` | Both parameters fixed | Complete positive sample | +| [Corrected Kuiper](kuiper-corrected.md) | `KuiperCorrected` | Both parameters fixed | Complete positive sample | +| [Zhang K](zhang-k.md) | `ZhangK` | Both parameters fixed | Complete positive sample | +| [Zhang A](zhang-a.md) | `ZhangA` | Both parameters fixed | Complete positive sample | +| [Zhang C](zhang-c.md) | `ZhangC` | Both parameters fixed | Complete positive sample | +| [Pearson chi-squared](pearson.md) | `Chi2Pearson` | Both parameters fixed | Complete positive sample | +| [Freeman–Tukey](freeman-tukey.md) | `FreemanTukey` | Both parameters fixed | Complete positive sample | +| [Modified log-likelihood](modified-log-likelihood.md) | `ModifiedLogLikelihood` | Both parameters fixed | Complete positive sample | +| [Neyman chi-squared](neyman-chi2.md) | `NeymanChi2` | Both parameters fixed | Complete positive sample | +| [Cressie–Read](cressie-read.md) | `CressieRead` | Both parameters fixed | Complete positive sample | +| [Bagdonavicius–Nikulin](nikulin.md) | `Nikulin` | Both parameters unknown | Positive times; optional event flags | +| [Mirvaliev](mirvaliev.md) | `Mirvaliev` | Both parameters unknown | Complete positive sample | + +## Parameters and examples + +There are no implicit unit-scale/unit-shape defaults in the criterion constructor. +The 18 generated criteria require both parameters; Nikulin and Mirvaliev require +an empty parameter set. Each individual page contains a runnable example and +scientific references. For example: + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + AndersonDarlingLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 2.0}) +statistic = AndersonDarlingLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.2, 0.5, 0.8, 1.4, 2.5]) +assert value >= 0 +``` + +## Calibration + +For fixed parameters, the probability integral transform gives a uniform null +for EDF statistics. Equal-probability frequency cells give multinomial counts +with equal probabilities. Preserve sample size, the exact statistic normalization +and the binning configuration in simulation. General binning strategies need +calibration under the actual distribution. The default frequency interface is +`binning=EqualProbabilityBins()`; the former `bins` keyword is not supported. + +For Mirvaliev, refit log-moments in every replicate. For Nikulin, reproduce the +censoring and observation scheme, refit the likelihood and recompute exposure +intervals. Event flag 1 means failure. No built-in log-logistic generator is +registered, so simulation is external. Critical values for fitted Weibull tests +or fixed-parameter KS tests cannot be reused for these fitted criteria. + +See [binning](../binning/index.md) and the [verification report](mathematical-validation.md) +for sources and limitations. diff --git a/docs/criteria/goodness-of-fit/log-logistic/ks-minus.md b/docs/criteria/goodness-of-fit/log-logistic/ks-minus.md new file mode 100644 index 00000000..4020be7a --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/ks-minus.md @@ -0,0 +1,58 @@ +# KolmogorovSmirnovDMinusLogLogisticGofStatistic + +Kolmogorov–Smirnov D− for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D^-=\max_i(u_i-(i-1)/n) +$$ + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + KolmogorovSmirnovDMinusLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = KolmogorovSmirnovDMinusLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/ks-plus.md b/docs/criteria/goodness-of-fit/log-logistic/ks-plus.md new file mode 100644 index 00000000..5c10f9ec --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/ks-plus.md @@ -0,0 +1,58 @@ +# KolmogorovSmirnovDPlusLogLogisticGofStatistic + +Kolmogorov–Smirnov D+ for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D^+=\max_i(i/n-u_i) +$$ + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + KolmogorovSmirnovDPlusLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = KolmogorovSmirnovDPlusLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/ks.md b/docs/criteria/goodness-of-fit/log-logistic/ks.md new file mode 100644 index 00000000..5ff7a8cd --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/ks.md @@ -0,0 +1,60 @@ +# KolmogorovSmirnovLogLogisticGofStatistic + +Kolmogorov–Smirnov for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D=\max(D^+,D^-) +$$ + +The default returns unscaled $D$. The legacy keyword `alternative_type` can select `AlternativeType.RIGHT` ($D^+$) or `LEFT` ($D^-$); rejection is still in the right tail. Prefer the separate D+ and D− classes for distinct criterion identifiers. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + KolmogorovSmirnovLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = KolmogorovSmirnovLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/kuiper-corrected.md b/docs/criteria/goodness-of-fit/log-logistic/kuiper-corrected.md new file mode 100644 index 00000000..02bb6175 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/kuiper-corrected.md @@ -0,0 +1,60 @@ +# KuiperCorrectedLogLogisticGofStatistic + +Corrected Kuiper for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V_c=(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-) +$$ + +The correction defines the returned statistic; it does not make asymptotic critical values exact for every sample size. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + KuiperCorrectedLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = KuiperCorrectedLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Lemeshko et al. (2014), equations (1)–(6)](https://doi.org/10.3103/S875669901401004X) ([full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/kuiper-scaled.md b/docs/criteria/goodness-of-fit/log-logistic/kuiper-scaled.md new file mode 100644 index 00000000..2746b675 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/kuiper-scaled.md @@ -0,0 +1,58 @@ +# KuiperScaledLogLogisticGofStatistic + +Scaled Kuiper for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V_s=\sqrt n(D^++D^-) +$$ + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + KuiperScaledLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = KuiperScaledLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Lemeshko et al. (2014), equations (1)–(6)](https://doi.org/10.3103/S875669901401004X) ([full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/kuiper.md b/docs/criteria/goodness-of-fit/log-logistic/kuiper.md new file mode 100644 index 00000000..d54c2c4b --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/kuiper.md @@ -0,0 +1,58 @@ +# KuiperLogLogisticGofStatistic + +Kuiper for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V=D^++D^- +$$ + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + KuiperLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = KuiperLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Lemeshko et al. (2014), equations (1)–(6)](https://doi.org/10.3103/S875669901401004X) ([full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/liao-shimokawa.md b/docs/criteria/goodness-of-fit/log-logistic/liao-shimokawa.md new file mode 100644 index 00000000..af5bafc1 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/liao-shimokawa.md @@ -0,0 +1,62 @@ +# LiaoShimokawaLogLogisticGofStatistic + +Liao–Shimokawa for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +L_n=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}} +$$ + +Logarithmic tails are evaluated directly from $z=\beta(\log x-\log\alpha)$, without clipping probabilities. A result beyond float64 range can be positive infinity. + +This is the Liao–Shimokawa discrepancy applied to a fixed log-logistic CDF. The original paper studies fitted Weibull/extreme-value models; its critical values do not apply here. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + LiaoShimokawaLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = LiaoShimokawaLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965). The displayed expression is also given in [Al-Zahrani (2012), §3](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf). diff --git a/docs/criteria/goodness-of-fit/log-logistic/mathematical-validation.md b/docs/criteria/goodness-of-fit/log-logistic/mathematical-validation.md new file mode 100644 index 00000000..be7972ce --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/mathematical-validation.md @@ -0,0 +1,226 @@ +# Mathematical verification of log-logistic statistics + +Audit date: 2026-10-17. All **20 concrete criteria** in `log_logistic/log_logistic_statistics.py` were +reviewed: 13 generated EDF statistics, 5 generated frequency statistics and the +2 fitted-model statistics Nikulin and Mirvaliev. The report follows the +[uniformity verification report](../uniformity/mathematical-validation.md). +The [catalog](index.md) links to an individual page for every criterion. + +## Formula checks + +Write $u_i=F_{\alpha,\beta}(x_{(i)})$ and $r_i=i-1/2$. +For positive observations, + +$$ +z_i=\beta(\log x_i-\log\alpha),\qquad +F(x_i)=\operatorname{expit}(z_i),\quad +\log F(x_i)=-\log(1+e^{-z_i}),\quad +\log S(x_i)=-\log(1+e^{z_i}). +$$ + +The implementation uses `logaddexp` for the last two expressions. The generated +criteria require both parameters fixed. The two bespoke criteria require both +unknown; hypothesis support is declared separately by each concrete criterion. + +| Criteria (number) | Checked definition | Scientific source | +|---|---|---| +| KS D+, D−, D (3) | $D^+=\max(i/n-u_i)$, $D^-=\max(u_i-(i-1)/n)$, $D=\max(D^+,D^-)$; no square or scaling | [Zhang (2002), §2.1](https://doi.org/10.1111/1467-9868.00337) | +| Anderson–Darling (1) | Weighted logarithmic sum, factor $1/n$, subtraction of $n$ | [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437); [Zhang (2002), §2.2](https://doi.org/10.1111/1467-9868.00337) | +| Cramér–von Mises (1) | $1/(12n)+\sum(u_i-r_i/n)^2$ | [Zhang (2002), §2.3](https://doi.org/10.1111/1467-9868.00337) | +| Watson (1) | $W^2-n(\bar u-1/2)^2$, evaluated with centered deviations | [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109); [Lemeshko et al. (2014), eq. (6)](https://doi.org/10.3103/S875669901401004X) | +| Kuiper, scaled, corrected (3) | $V=D^++D^-$, $\sqrt nV$, $(\sqrt n+0.155+0.24/\sqrt n)V$ | [Lemeshko et al. (2014), eqs. (1)–(3)](https://doi.org/10.3103/S875669901401004X) | +| Zhang K, A, C (3) | Half-rank likelihood ratios and quarter-rank log-odds correction | [Zhang (2002), eqs. (3.1)–(3.3)](https://doi.org/10.1111/1467-9868.00337) | +| Liao–Shimokawa (1) | $n^{-1/2}\sum_i\max(i/n-u_i,u_i-(i-1)/n)/\sqrt{u_i(1-u_i)}$ | [Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965); [Al-Zahrani (2012), eq. (13)](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf) | +| Pearson, Freeman–Tukey, modified log-likelihood, Neyman, Cressie–Read (5) | Power-divergence family at $\lambda=1,-1/2,-1,-2,2/3$; zero-count limits checked explicitly | [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| Bagdonavicius–Nikulin (1) | Exposure residuals and information correction with an observed-count denominator | [Bagdonavicius and Nikulin (2011), §§3–5](https://www.numdam.org/item/10.1016/j.crma.2011.01.007.pdf) | +| Mirvaliev (1) | Moment-fitted logistic quadratic form applied to $\log X$ | [Pya (2004), pp. 70–71, eqs. (8)–(15)](https://math.kz/media/journal/journal2017-06-0725590.pdf#page=70) | + +No algebraic changes were needed to the statistic kernels checked here. +All criteria reject in the right tail; directional KS refers to CDF deviation, +not to the rejection tail of the returned nonnegative statistic. + +### Bagdonavicius–Nikulin derivation + +With $z=(\log t-\mu)/s$, the hazard is $h(t)=F(t)/(st)$ and cumulative +hazard is $H(t)=\log(1+e^z)$. The implemented hazard-score coordinates are +$(-S,-1-zS)$, an invertible rescaling of the location/log-scale score at the fit. +Consequently the quadratic form is unchanged by this coordinate choice. + +Boundaries equalize $\sum_i\min(H(t_i),H(a_j))$. With event counts $U_j$, +exposures $e_j$, $Z=(U-e)/\sqrt n$, $A=\operatorname{diag}(U/n)$, cell score +sums $C$ divided by $n$, and event score outer products $I$ divided by $n$, +the implementation returns + +$$ +Z^TA^{-1}Z+(CA^{-1}Z)^T(I-CA^{-1}C^T)^{-1}(CA^{-1}Z). +$$ + +Within-cell centering computes the latter matrix without cancellation. +An independent reference uses SciPy's censored logistic likelihood fit, +numerically integrates exposure over the risk sets, and inverts +$A-C^TI^{-1}C$ directly. Agreement verifies both the coordinate change and +Woodbury rearrangement. Empty event cells return infinity; singular or +ill-conditioned correction matrices raise an error instead of being regularized. + +### Mirvaliev derivation + +Standardized logs use the sample variance with divisor $n$. For the unit-variance +logistic null, $E[Y^4]=21/5$, hence +$V=\operatorname{Cov}(Y,Y^2-1)=\operatorname{diag}(1,16/5)$ and +$K=\operatorname{diag}(1,2)$. The implemented matrices give + +$$ +A=I-qq^T+C(V-C^TC)^{-1}C^T,\quad D=C-BK^{-1}V,\quad L=V+D^TAD, +$$ + +and $v^TAv-(D^TAv)^TL^{-1}(D^TAv)$ for standardized cell residuals $v$. +This reproduces Pya's moment-based correction in standardized coordinates. +An independent check constructs the covariance of fitted cell residuals from +integrals of the mean/standard-deviation influence functions and evaluates its +pseudoinverse quadratic form. No normal-distribution fourth moment is substituted. + +## Numerical correction found during the audit + +The shared distribution adapter previously delegated log-logistic probabilities +to SciPy's Fisk evaluator, which could underflow the ratio $x/\alpha$ before +applying a small shape exponent. For `alpha=1e250`, `beta=0.001`, sample +`[1e-40, 1e-60, 1e-100, 1e-250]` and ten equal-probability cells, Pearson +returned **16 instead of 21**. Freeman–Tukey and Cressie–Read were also affected. +The problem was in cell assignment, not their discrepancy formulas. + +The log-logistic bound distribution now evaluates CDF, SF, log-CDF and log-SF +from log odds. It retains support limits and NaN propagation. This also repairs +premature infinite log probabilities: at `alpha=1`, `beta=2`, `x=1e-250`, +`logcdf` is approximately −1151.292546497, not negative infinity. +EDF kernels already used stable log odds and did not require this correction. +Old calibrations or results computed in the affected numerical regimes should +be regenerated; ordinary-range definitions and normalizations are unchanged. + +## Sources and qualifications + +Full text was inspected for [Zhang](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf), +[Lemeshko et al.](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf), +[Bagdonavicius–Nikulin](https://www.numdam.org/item/10.1016/j.crma.2011.01.007.pdf) +and [Pya](https://math.kz/media/journal/journal2017-06-0725590.pdf). +Cressie–Read's publisher summary identifies the five divergence parameters; +their formulas and limiting zero-count contributions were additionally checked +algebraically and against SciPy. + +The original Liao–Shimokawa full text was inaccessible in this audit. Its +bibliography and fitted-model scope were checked, and the expression was +compared with its use in Al-Zahrani's published study. The implementation uses +a **local maximum of two deviations at each observation**. This is a fixed-null +log-logistic adaptation; original fitted-Weibull critical values do not apply. +The original Mirvaliev (2001) paper was not inspected: the logistic application +is checked against Pya (2004), then transferred through the logarithm. + +These checks establish agreement of the calculations with the stated definitions +on the tested domains. They do not prove finite-sample significance levels, +omnibus consistency of every discrepancy, or power against every alternative. +Ties are computable but continuous-null critical values are not automatically +valid for rounded data. Frequency chi-square approximations require appropriate +cell counts and assumptions. Neither default bin count nor Kuiper correction +makes an asymptotic reference exact. + +Nikulin uses the sample maximum as the observation horizon. The source assumes +an observation scheme and regularity conditions; no exact finite-sample law for +this random horizon is asserted. External calibration must reproduce censoring, +observation/stopping, fitting and grouping. Mirvaliev supports only complete data +and must refit moments in simulation. The package has no registered log-logistic +random generator; the generic Monte Carlo resolver is therefore unavailable. + +## Numerical verification and documentation coverage + +The focused suite passed **230 tests** across: + +- `tests/distributions/test_log_logistic.py`; +- `tests/distributions/test_log_logistic_correctness.py`; +- `tests/distributions/test_log_logistic_mathematical_validation.py`. + +References include EDF integrals (AD, CvM, Watson), SciPy KS and multinomial +power divergences, 250-digit Decimal tail calculations, independent fitted-model +covariance expressions, censored likelihood fits and risk integrals. Checks +cover all 20 criteria, fixed/unknown parameter contracts, transformations, +unsorted input, ties, singletons, invalid data, empty cells, extreme scales, +nonmutation and calibration restrictions. + +The documentation check finds exactly one page per concrete class, verifies its +catalog and navigation entry and scientific URL, and executes every individual +page's Python example. Generated class docstrings also have executable examples. +There are **20 criterion pages, one catalog and this report**; six existing +criterion URLs are preserved. Formula, hypothesis, input, rejection direction, +binning and calibration information are included. + +Ordinary test collection is currently blocked by an unrelated pre-existing +`NameError: AbstractCrammerVonMisesStatistic` in `continuous/log_normal.py`. +The focused run supplies the `continuous` package path without executing its +aggregate `__init__.py`; the actual log-logistic module, factories, kernels and +probability adapter execute normally. Thus these results do not certify that +ordinary package initialization succeeds in the current working tree. + +The shared probability-evaluation suite additionally passed **50 tests** after +the adapter correction. Ruff and whitespace checks passed for the changed code. +MkDocs built the site successfully; its six broken-link warnings concern +pre-existing Weibull audit links, not the log-logistic section. + +To reproduce the isolated focused run from the repository root: + +```python +import sys +import types +from pathlib import Path + +import pytest + +name = "pysatl_criterion.statistics.goodness_of_fit.continuous" +package = types.ModuleType(name) +package.__path__ = [ + str(Path("src/pysatl_criterion/statistics/goodness_of_fit/continuous").resolve()) +] +sys.modules[name] = package +raise SystemExit( + pytest.main( + [ + "tests/distributions/test_log_logistic.py", + "tests/distributions/test_log_logistic_correctness.py", + "tests/distributions/test_log_logistic_mathematical_validation.py", + "tests/distributions/test_distribution_evaluation.py", + "-q", + ] + ) +) +``` + +## Numba optimization follow-up + +The 18 generated criteria retain the compiled shared EDF/frequency kernels. +Local numerical work now uses `@jit(nopython=True, cache=True)` for CDF and log +probabilities, Nikulin likelihood terms and exposure/information accumulation, +and Mirvaliev moment integrands, fitted cell residuals and the final quadratic +form. Validation, SciPy optimization/quadrature and checked matrix solves remain +Python orchestration. All helpers in `log_logistic/log_logistic_statistics.py` are class methods. + +Mirvaliev caches only distribution-dependent edges, derivatives and integrals +by interval count (LRU bound: 32 entries); cached arrays are read-only. Sample +moments and residuals are recomputed for every call. Nikulin reduces likelihood +terms with NumPy to preserve its pairwise summation and optimizer convergence. +No fast-math mode or relaxed optimizer tolerance is used. + +A local warm-cache measurement used 1,000 observations from +`exp(default_rng(13).logistic(size=1000))`, default criterion settings, and the +minimum of three batches of 20 calls. Compilation was excluded: + +| Criterion | Before | After | Approximate speedup | +|---|---:|---:|---:| +| Anderson–Darling | 0.054 ms | 0.053 ms | No material change | +| Nikulin | 2.20 ms | 1.90 ms | 1.16× | +| Mirvaliev | 0.478 ms | 0.111 ms | 4.3× | + +These timings describe this machine and sample, not a universal performance +bound. First-call compilation and uncached quadrature cost extra. Values agree +with the original implementation within floating-point precision on this +sample. The expanded focused suite passes **237 tests**, including independent +likelihood/finite-difference gradient checks, nopython compilation of every +local numerical kernel and all generated criteria, bounded/read-only cache +behavior, and absence of module-level helper functions. The ordinary-import +limitation noted above still applies. diff --git a/docs/criteria/goodness-of-fit/log-logistic/mirvaliev.md b/docs/criteria/goodness-of-fit/log-logistic/mirvaliev.md new file mode 100644 index 00000000..e3e1fa18 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/mirvaliev.md @@ -0,0 +1,90 @@ +# MirvalievLogLogisticGofStatistic + +Mirvaliev moment-fitted statistic on log-transformed complete data. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Parameters + +`parameters`: pass `LogLogisticDistributionDescriptor.DEFAULT.parse({})`. +Both alpha and beta are unknown and are fitted anew on every execution. +Partially or fully fixed parameters are unsupported. + +n_intervals : int, optional + Number of equiprobable cells, at least 2; default 8. + +## Methods +execute_statistic(rvs, **kwargs) + Return a scalar discrepancy. +hypothesis() + Return the fixed parameters; omitted parameters are unknown. + +## Notes +Apply equations (8)-(10) of [1] to log(X), a logistic location-scale +family. Fit its mean and standard deviation with divisor n, per call. +Both log-logistic parameters are unknown. In unit-variance coordinates, +cell residuals are v_j=(N_j-n/r)/sqrt(n/r), q_j=1/sqrt(r). +B contains fixed-boundary probability derivatives divided by sqrt(p). +C contains cell integrals of (Y, Y²-1) divided by sqrt(p), +V=diag(1,16/5), K=diag(1,2). Set A=I-qq'+C(V-C'C)^-1 C', +D=C-B K^-1 V, L=V+D' A D. Return v' A v-v' A D L^-1 D' A v. +Integrals are evaluated by adaptive quadrature. These are logistic +moments, not normal moments. No MLE or survival-hazard correction is used. +Reject large values. Log-location/scale invariance justifies simulation +at alpha=beta=1 with refitting. Preserve n and r. The asymptotic +chi-square(r-1) statement in [1] is not an exact finite-sample law. +No built-in log-logistic generator exists; Monte Carlo is external. +Storage omits r and is blocked; discard old MIRVALIEV calibrations. +The cited paper treats logistic data; logarithms give the log-logistic +application. A source for the former censored version was not found; +censored observations now raise ValueError. No fitted state is retained. + +## References +[1] N. Pya (2004), "Goodness-of-fit tests for the logistic + distribution", Mathematical Journal 4(2), 68-75, equations (8)-(10). + [Source](https://math.kz/media/journal/journal2017-06-0725590.pdf) +## Examples +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + MirvalievLogLogisticGofStatistic, +) + +statistic = MirvalievLogLogisticGofStatistic(LogLogisticDistributionDescriptor.DEFAULT.parse({})) +value = statistic.execute_statistic(np.exp(np.linspace(-2, 2, 100))) +bool(np.isfinite(value)) +``` + +## Input and result + +Compute the statistic independently for the supplied sample. + +## Parameters +rvs : array_like + Positive finite 1D times (at least three, not constant), or + (times, delta) with matching binary indicators, 1 for events. + All indicators must be one; censoring is unsupported. +**kwargs : dict + Accepted for the common interface; unused. + +## Returns +statistic : float or numpy.float64 + Nonnegative discrepancy; larger values reject the null. + +## Raises +ValueError + Invalid sample or singular correction matrix. +RuntimeError + Numerical failure produces a negative quadratic form. + +## Calibration and interpretation + +The moment fit is to $\log X$, not to $X$: with $m=\overline{\log X}$ and +$s^2=n^{-1}\sum(\log X_i-m)^2$, the implied parameters are +$\hat\alpha=e^m$ and $\hat\beta=\pi/(\sqrt3s)$. Computation uses standardized +logs and need not form these possibly overflowing parameters. +This applies the logistic statistic in Pya (2004) after the invertible logarithm +transformation. It is not a censored-data extension. At a fixed number of cells, +the source's limiting law is $\chi^2_{r-1}$ under its assumptions; calibrate finite +samples externally with moment fitting repeated in every replicate. diff --git a/docs/criteria/goodness-of-fit/log-logistic/modified-log-likelihood.md b/docs/criteria/goodness-of-fit/log-logistic/modified-log-likelihood.md new file mode 100644 index 00000000..4cfc7547 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/modified-log-likelihood.md @@ -0,0 +1,71 @@ +# ModifiedLogLikelihoodLogLogisticGofStatistic + +Modified log-likelihood for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +T=2\sum_j E_j\log(E_j/O_j) +$$ + +Here $O_j$ are observed cell counts and $E_j=np_j>0$ are null expected +counts, with equal totals. The keyword `binning` accepts a `BinningStrategy`. +The default `EqualProbabilityBins()` uses `PowerCount()` (at least two cells, +approximately $2n^{0.4}$, rounded up, subject to `max_bins`). To fix the number, +use `EqualProbabilityBins(5)`. Internal boundaries belong to the cell on the +right. The default does not merge small expected counts. +See [binning strategies](../binning/index.md). + +An empty observed cell with positive expectation returns positive infinity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + ModifiedLogLikelihoodLogLogisticGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = ModifiedLogLikelihoodLogLogisticGofStatistic( + parameters, binning=EqualProbabilityBins(4) +) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) diff --git a/docs/criteria/goodness-of-fit/log-logistic/neyman-chi2.md b/docs/criteria/goodness-of-fit/log-logistic/neyman-chi2.md new file mode 100644 index 00000000..62c3ef3e --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/neyman-chi2.md @@ -0,0 +1,69 @@ +# NeymanChi2LogLogisticGofStatistic + +Neyman chi-squared for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +T=\sum_j\frac{(O_j-E_j)^2}{O_j} +$$ + +Here $O_j$ are observed cell counts and $E_j=np_j>0$ are null expected +counts, with equal totals. The keyword `binning` accepts a `BinningStrategy`. +The default `EqualProbabilityBins()` uses `PowerCount()` (at least two cells, +approximately $2n^{0.4}$, rounded up, subject to `max_bins`). To fix the number, +use `EqualProbabilityBins(5)`. Internal boundaries belong to the cell on the +right. The default does not merge small expected counts. +See [binning strategies](../binning/index.md). + +An empty observed cell with positive expectation returns positive infinity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + NeymanChi2LogLogisticGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = NeymanChi2LogLogisticGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) diff --git a/docs/criteria/goodness-of-fit/log-logistic/nikulin.md b/docs/criteria/goodness-of-fit/log-logistic/nikulin.md new file mode 100644 index 00000000..82f63cdb --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/nikulin.md @@ -0,0 +1,94 @@ +# NikulinLogLogisticGofStatistic + +Bagdonavicius-Nikulin statistic with fitted log-logistic survival. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Parameters + +`parameters`: pass `LogLogisticDistributionDescriptor.DEFAULT.parse({})`. +Both alpha and beta are unknown and are fitted anew on every execution. +Partially or fully fixed parameters are unsupported. + +n_intervals : int, optional + Number of equal-exposure intervals, at least 2; default 5. + +## Methods +execute_statistic(rvs, **kwargs) + Return a scalar discrepancy. +hypothesis() + Return the fixed parameters; omitted parameters are unknown. + +## Notes +Both alpha and beta are unknown. Each call fits the right-censored +likelihood in standardized log-time location and log-scale coordinates. +Non-informative right censoring is assumed; delta=1 denotes an event. +H(t)=logaddexp(0, beta*log(t/alpha)); hence h(t)=beta*F(t)/t. +Section 5 of [1] chooses boundaries with sum_i min(H(t_i), H(a_j)) +equal to j/k times total exposure, so all e_j equal total/k. +In Sections 3-4, Z=(U-e)/sqrt(n), A=diag(U/n), C contains cell sums +of event hazard scores divided by n, and I their outer-product mean. +Return Z'A^-1 Z + W'G^-1 W, W=C A^-1 Z, G=I-C A^-1 C'. +Scores use equivalent location/log-scale coordinates. G is calculated +by within-cell centering, without a ridge or pseudoinverse. +Empty event cells have positive exposure and return infinity. Singular +or ill-conditioned G is rejected. Small samples need fewer intervals. +Reject large values. The paper gives an asymptotic chi-square result +under regularity conditions; finite-sample calibration must reproduce +censoring, interval count and refitting. Generic Monte Carlo and storage +are blocked: they cannot express the censoring plan. Old BN_GOF +calibration values must be discarded. No estimates are retained. + +## References +[1] V. Bagdonavicius and M. Nikulin (2011), "Chi-squared tests for + general composite hypotheses from censored samples", Sections 3-5. + [Source](https://doi.org/10.1016/j.crma.2011.01.007) + [Source](https://www.numdam.org/item/10.1016/j.crma.2011.01.007.pdf) +## Examples +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + NikulinLogLogisticGofStatistic, +) + +statistic = NikulinLogLogisticGofStatistic(LogLogisticDistributionDescriptor.DEFAULT.parse({})) +value = statistic.execute_statistic(np.exp(np.linspace(-2, 2, 100))) +bool(np.isfinite(value)) +``` + +## Input and result + +Compute the statistic independently for the supplied sample. + +## Parameters +rvs : array_like + Positive finite 1D times (at least three, not constant), or + (times, delta) with matching binary indicators, 1 for events. + Nikulin requires at least three events at two distinct times. +**kwargs : dict + Accepted for the common interface; unused. + +## Returns +statistic : float or numpy.float64 + Nonnegative discrepancy; larger values reject the null. + Positive infinity when any event cell is empty. + +## Raises +ValueError + Invalid sample or singular correction matrix. +RuntimeError + No finite MLE converges. + +## Calibration and interpretation + +This is the Bagdonavicius–Nikulin survival statistic, not the complete-data +Nikulin–Rao–Robson multinomial statistic. An event flag of **1 means observed +failure**, and 0 means right censoring. Without flags all observations are events. +The risk integral includes censored exposure. Intervals are $(a_{j-1},a_j]$, +so an event on an internal boundary belongs to the preceding interval. +The implementation uses the last observed time as its observation horizon. +The article's asymptotic result requires regularity and an appropriate +observation scheme; this implementation does not establish an exact null law +for a random sample-maximum horizon. Use external calibration reproducing +censoring, stopping, grouping and parameter fitting. diff --git a/docs/criteria/goodness-of-fit/log-logistic/pearson.md b/docs/criteria/goodness-of-fit/log-logistic/pearson.md new file mode 100644 index 00000000..4da6dbfc --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/pearson.md @@ -0,0 +1,69 @@ +# Chi2PearsonLogLogisticGofStatistic + +Pearson chi-squared for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +X^2=\sum_j\frac{(O_j-E_j)^2}{E_j} +$$ + +Here $O_j$ are observed cell counts and $E_j=np_j>0$ are null expected +counts, with equal totals. The keyword `binning` accepts a `BinningStrategy`. +The default `EqualProbabilityBins()` uses `PowerCount()` (at least two cells, +approximately $2n^{0.4}$, rounded up, subject to `max_bins`). To fix the number, +use `EqualProbabilityBins(5)`. Internal boundaries belong to the cell on the +right. The default does not merge small expected counts. +See [binning strategies](../binning/index.md). + +An empty observed cell contributes $E_j$. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + Chi2PearsonLogLogisticGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import EqualProbabilityBins + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = Chi2PearsonLogLogisticGofStatistic(parameters, binning=EqualProbabilityBins(4)) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x); [Pearson (1900)](https://doi.org/10.1080/14786440009463897) diff --git a/docs/criteria/goodness-of-fit/log-logistic/watson.md b/docs/criteria/goodness-of-fit/log-logistic/watson.md new file mode 100644 index 00000000..76307a3e --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/watson.md @@ -0,0 +1,60 @@ +# WatsonLogLogisticGofStatistic + +Watson for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +U^2=W^2-n(\bar u-1/2)^2 +$$ + +The implementation centers the deviations before squaring to avoid cancellation. No finite-sample correction is applied. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + WatsonLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = WatsonLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Lemeshko et al. (2014), equations (1)–(6)](https://doi.org/10.3103/S875669901401004X) ([full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf)); [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109) diff --git a/docs/criteria/goodness-of-fit/log-logistic/zhang-a.md b/docs/criteria/goodness-of-fit/log-logistic/zhang-a.md new file mode 100644 index 00000000..d6a65b70 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/zhang-a.md @@ -0,0 +1,60 @@ +# ZhangALogLogisticGofStatistic + +Zhang A for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +Z_A=-\sum_i\left[\frac{\log u_i}{n-r_i}+\frac{\log(1-u_i)}{r_i}\right] +$$ + +Logarithmic tails are evaluated directly from $z=\beta(\log x-\log\alpha)$, without clipping probabilities. A result beyond float64 range can be positive infinity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + ZhangALogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = ZhangALogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/zhang-c.md b/docs/criteria/goodness-of-fit/log-logistic/zhang-c.md new file mode 100644 index 00000000..0893779c --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/zhang-c.md @@ -0,0 +1,60 @@ +# ZhangCLogLogisticGofStatistic + +Zhang C for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +Z_C=\sum_i\left[\log\frac{1-u_i}{u_i}-\log\frac{n-i+1/4}{i-3/4}\right]^2 +$$ + +Logarithmic tails are evaluated directly from $z=\beta(\log x-\log\alpha)$, without clipping probabilities. A result beyond float64 range can be positive infinity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + ZhangCLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = ZhangCLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-logistic/zhang-k.md b/docs/criteria/goodness-of-fit/log-logistic/zhang-k.md new file mode 100644 index 00000000..e5b82d15 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-logistic/zhang-k.md @@ -0,0 +1,60 @@ +# ZhangKLogLogisticGofStatistic + +Zhang K for a fully specified log-logistic distribution. + +[All log-logistic criteria](index.md) · [Mathematical verification](mathematical-validation.md) + +## Hypothesis and input + +Pass `Distribution.DEFAULT.parse({"alpha": alpha, "beta": beta})` as `parameters`. +Both scale `alpha` and shape `beta` must be fixed, finite and strictly positive. +Neither parameter is estimated. The sample must be a nonempty, finite, strictly +positive one-dimensional array; ties and a single observation are accepted. +Censored samples are not supported. The returned value is a scalar statistic; +large values reject the null (right tail). + +## Definition + +For ordered observations, $u_i=F_{\alpha,\beta}(x_{(i)})$, +$F_{\alpha,\beta}(x)=1/[1+(\alpha/x)^\beta]$ for $x>0$. +Write $r_i=i-1/2$, $D^+=\max_i(i/n-u_i)$ and +$D^-=\max_i(u_i-(i-1)/n)$. + +$$ +Z_K=\max_i\left[r_i\log\frac{r_i}{nu_i}+(n-r_i)\log\frac{n-r_i}{n(1-u_i)}\right] +$$ + +Logarithmic tails are evaluated directly from $z=\beta(\log x-\log\alpha)$, without clipping probabilities. A result beyond float64 range can be positive infinity. + +## Calibration + +For a fixed continuous null, EDF statistics and equal-probability cell counts +can be calibrated through independent Uniform(0,1) samples. Other binning rules +require the actual null and the same rule in every replicate. A rounded-data +null must reproduce rounding. Passing parameters estimated from this sample +as fixed values does not account for fitting. + +The library currently has no built-in log-logistic random generator: use external +simulation (for example `scipy.stats.fisk`). This class computes a statistic, +not a p-value. For frequency statistics, the chi-square law with $k-1$ degrees +of freedom is an asymptotic approximation for fixed cells with adequate expected +counts, not an exact small-sample calibration. Binning is included in the +frequency criterion's storage configuration. + +## Example + +```python +from pysatl_criterion.distribution import LogLogisticDistributionDescriptor as Distribution +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_logistic import ( + ZhangKLogLogisticGofStatistic, +) + +parameters = Distribution.DEFAULT.parse({"alpha": 1.0, "beta": 1.0}) +statistic = ZhangKLogLogisticGofStatistic(parameters) +value = statistic.execute_statistic([0.1, 0.2, 0.5, 0.8, 1.5, 2.0, 4.0, 8.0]) +assert value >= 0 +``` + +## Scientific references + +[Zhang (2002), §§2–3](https://doi.org/10.1111/1467-9868.00337) ([full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf)) diff --git a/docs/criteria/goodness-of-fit/log-normal/anderson_darling_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/anderson_darling_log_normal_criterion.md index 7e3153e7..daa33fd7 100644 --- a/docs/criteria/goodness-of-fit/log-normal/anderson_darling_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/anderson_darling_log_normal_criterion.md @@ -1,60 +1,61 @@ -# Anderson-Darling test for log-normal distribution +# Anderson-Darling test for log-normal data -## Description -Performs Anderson-Darling goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `AndersonDarlingLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `AD_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Anderson-Darling normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - AndersonDarlingLogNormalGofStatistic, -) - - -test_statistic = AndersonDarlingLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Statistic -`rvs` - array-like sample data passed to `execute_statistic`. +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Anderson-Darling A² statistic. -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +Computes -n-sum((2*i-1)*(log(u_i)+log(1-u_(n+1-i))))/n. +Endpoints give positive infinity; no finite-sample correction is applied. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +## References +Anderson, T. W., and Darling, D. A. (1952). Asymptotic Theory of Certain +Goodness of Fit Criteria Based on Stochastic Processes. Annals of +Mathematical Statistics, 23(2), 193-212. +https://doi.org/10.1214/aoms/1177729437 +Computational form: Zhang (2002), Section 2.2. +https://doi.org/10.1111/1467-9868.00337 -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( AndersonDarlingLogNormalGofStatistic, ) - -test_statistic = AndersonDarlingLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = AndersonDarlingLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/bonett_seier_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/bonett_seier_log_normal_criterion.md index e835ba3a..e1ce89ae 100644 --- a/docs/criteria/goodness-of-fit/log-normal/bonett_seier_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/bonett_seier_log_normal_criterion.md @@ -1,60 +1,88 @@ -# Bonett-Seier test for log-normal distribution +# Bonett-Seier test for log-normal data -## Description -Performs Bonett-Seier goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `BonettSeierLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `BS_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Bonett-Seier normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BonettSeierLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = BonettSeierLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +## Logarithmic reduction -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +The implementation computes `BonettSeierNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Underlying normality definition -`rvs` - array-like sample data passed to `execute_statistic`. +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/bonett_seier_normality_criterion.md). -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +The factor sqrt(n+2), the population sample variance (ddof=0), and the +two-sided rejection rule agree with equations (5)–(6) of the [original +article](https://sci2s.ugr.es/keel/pdf/specific/articulo/Normalidad4.pdf). -## Author(s) -Anton Dorosev, Alexey Mironov +Let d=mean(abs(x-mean(x))) and omega=13.29*log(s0/d). +Return sqrt(n+2)*(omega-3)/3.54, a signed kurtosis transform. +The constants are rounded approximations; use finite-sample simulation. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Bonett, D. G. and Seier, E. (2002). + A test of normality with high uniform power. + Computational Statistics & Data Analysis, 40(3), 435-445. + https://doi.org/10.1016/S0167-9473(02)00074-9 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( BonettSeierLogNormalGofStatistic, ) - -test_statistic = BonettSeierLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = BonettSeierLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi1_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi1_log_normal_criterion.md index 5be028f4..6abba4b4 100644 --- a/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi1_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi1_log_normal_criterion.md @@ -1,60 +1,85 @@ -# Bontemps-Meddahi1 test for log-normal distribution +# Bontemps-Meddahi1 test for log-normal data -## Description -Performs Bontemps-Meddahi1 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `BontempsMeddahi1LogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `BM1_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Bontemps-Meddahi1 normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BontempsMeddahi1LogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = BontempsMeddahi1LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `BontempsMeddahi1NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/bontemps_meddahi1_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Let z=(x-mean(x))/s1 and h_j=He_j/sqrt(j!), where He_j +are probabilists' Hermite polynomials. Return +(sum(h_3(z))**2+sum(h_4(z))**2)/n. +The sample-variance convention ddof=1 is part of this implementation. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Bontemps, C. and Meddahi, N. (2005). + Testing normality: a GMM approach. + Journal of Econometrics, 124(1), 149-186. + https://doi.org/10.1016/j.jeconom.2004.02.014 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( BontempsMeddahi1LogNormalGofStatistic, ) - -test_statistic = BontempsMeddahi1LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = BontempsMeddahi1LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi2_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi2_log_normal_criterion.md index 83bc5416..881941dd 100644 --- a/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi2_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/bontemps_meddahi2_log_normal_criterion.md @@ -1,60 +1,85 @@ -# Bontemps-Meddahi2 test for log-normal distribution +# Bontemps-Meddahi2 test for log-normal data -## Description -Performs Bontemps-Meddahi2 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `BontempsMeddahi2LogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `BM2_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Bontemps-Meddahi2 normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BontempsMeddahi2LogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = BontempsMeddahi2LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `BontempsMeddahi2NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/bontemps_meddahi2_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Let z=(x-mean(x))/s1 and h_j=He_j/sqrt(j!), where He_j +are probabilists' Hermite polynomials. Return +sum_j(sum_i(h_j(z_i))**2)/n for j=3,4,5,6. +The sample-variance convention ddof=1 is part of this implementation. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Bontemps, C. and Meddahi, N. (2005). + Testing normality: a GMM approach. + Journal of Econometrics, 124(1), 149-186. + https://doi.org/10.1016/j.jeconom.2004.02.014 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( BontempsMeddahi2LogNormalGofStatistic, ) - -test_statistic = BontempsMeddahi2LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = BontempsMeddahi2LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/cabana_cabana1_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/cabana_cabana1_log_normal_criterion.md index 3328b9ed..10e2c51b 100644 --- a/docs/criteria/goodness-of-fit/log-normal/cabana_cabana1_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/cabana_cabana1_log_normal_criterion.md @@ -1,60 +1,88 @@ -# Cabana-Cabana1 test for log-normal distribution +# Cabana-Cabana1 test for log-normal data -## Description -Performs Cabana-Cabana1 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `CabanaCabana1LogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `CC1_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Cabana-Cabana1 normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CabanaCabana1LogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = CabanaCabana1LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `CabanaCabana1NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/cabana_cabana1_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Use the l=5 process in Cabana and Cabana, equation (7). +For z=(x-mean(x))/s1, h_j=He_j/sqrt(j!), H_j=sum(h_j(z))/sqrt(n), +P(t)=sum_{j=1..5}(h_(j-1)(t)*H_(j+3)/sqrt(j)). Return +sup_t abs(Phi(t)*H_3-phi(t)*P(t)). Evaluate every real stationary +point (roots of H_3+t*P-P') and both limits at infinity. +This is the supremum of the truncated process, not the untruncated +infinite series. Polynomial root solving is subject to float64 accuracy. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Cabaña, A. and Cabaña, E. M. (2003). + Tests of Normality Based on Transformed Empirical Processes. + Methodology and Computing in Applied Probability, 5, 309-335. + https://doi.org/10.1023/A:1026235220018 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( CabanaCabana1LogNormalGofStatistic, ) - -test_statistic = CabanaCabana1LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = CabanaCabana1LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/cabana_cabana2_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/cabana_cabana2_log_normal_criterion.md index 312a1ebb..9ebfb0c5 100644 --- a/docs/criteria/goodness-of-fit/log-normal/cabana_cabana2_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/cabana_cabana2_log_normal_criterion.md @@ -1,60 +1,89 @@ -# Cabana-Cabana2 test for log-normal distribution +# Cabana-Cabana2 test for log-normal data -## Description -Performs Cabana-Cabana2 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `CabanaCabana2LogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `CC2_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Cabana-Cabana2 normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CabanaCabana2LogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = CabanaCabana2LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `CabanaCabana2NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/cabana_cabana2_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Use the l=5 process in Cabana and Cabana, equation (8). +For z=(x-mean(x))/s1, h_j=He_j/sqrt(j!), H_j=sum(h_j(z))/sqrt(n), +Q(t)=sum_{j=2..5}((sqrt(j/(j-1))*h_(j-2)(t)+h_j(t))*H_(j+3)). +Set P(t)=H_3+t*H_4+Q(t). Return +sup_t abs(Phi(t)*H_4-phi(t)*P(t)). Evaluate every real stationary +point (roots of H_4+t*P-P') and both limits at infinity. +The H_8 term occurs once. This is the truncated-process supremum; +polynomial root solving is subject to float64 accuracy. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Cabaña, A. and Cabaña, E. M. (2003). + Tests of Normality Based on Transformed Empirical Processes. + Methodology and Computing in Applied Probability, 5, 309-335. + https://doi.org/10.1023/A:1026235220018 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( CabanaCabana2LogNormalGofStatistic, ) - -test_statistic = CabanaCabana2LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = CabanaCabana2LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/chen_shapiro_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/chen_shapiro_log_normal_criterion.md index 210f3f72..55a5b13d 100644 --- a/docs/criteria/goodness-of-fit/log-normal/chen_shapiro_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/chen_shapiro_log_normal_criterion.md @@ -1,60 +1,84 @@ -# Chen-Shapiro test for log-normal distribution +# Chen-Shapiro test for log-normal data -## Description -Performs Chen-Shapiro goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `ChenShapiroLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `CS_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Chen-Shapiro normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ChenShapiroLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = ChenShapiroLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `ChenShapiroNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/chen_shapiro_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +For u_i=Phi**-1((i-3/8)/(n+1/4)), return +sqrt(n)*(1-sum_i((x_(i+1)-x_(i))/(u_(i+1)-u_i))/((n-1)*s1)). +This is the upper-tail QH* version, not the lower-tail raw QH. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Chen, L. and Shapiro, S. S. (1995). + An alternative test for normality based on normalized spacings. + Journal of Statistical Computation and Simulation, 53(3-4), 269-287. + https://doi.org/10.1080/00949659508811711 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( ChenShapiroLogNormalGofStatistic, ) - -test_statistic = ChenShapiroLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = ChenShapiroLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/chi2_pearson_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/chi2_pearson_log_normal_criterion.md new file mode 100644 index 00000000..ab64c835 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/chi2_pearson_log_normal_criterion.md @@ -0,0 +1,64 @@ +# Pearson chi-squared for log-normal data + +**Class:** `Chi2PearsonLogNormalGofStatistic` + +**Code:** `CHI2_PEARSON_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic and binning + +Pearson chi-square: sum((observed - expected)**2 / expected). + +## References +Pearson, K. (1900). On the criterion that a given system of deviations +from the probable in the case of a correlated system of variables is +such that it can be reasonably supposed to have arisen from random sampling. +Philosophical Magazine, 50(302), 157-175. +https://doi.org/10.1080/14786440009463897 + +The constructor accepts `binning: BinningStrategy`; its default is +`EqualProbabilityBins()`. Bins use the fixed log-normal distribution in the +original sample units. Define observed counts O_j and expected counts +E_j = n * P(X in cell j). The zero-count limits are part of the definition; +Neyman and modified log-likelihood can return positive infinity when O_j=0 exp(a) * X**b`, b > 0. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Underlying normality definition -`rvs` - array-like sample data passed to `execute_statistic`. +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/coin_normality_criterion.md). -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Author(s) -Anton Dorosev, Alexey Mironov +Regress z_(i)=(x_(i)-mean(x))/s1 on a_i and a_i**3 without +an intercept, where a_i are approximate expected normal order scores +from nscor2. Return the square of the cubic coefficient. Normal-score +approximations are only supported here for n<=2000. The reference +identifies the regression procedure; its score approximation is +retained and must be reproduced in calibration. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Coin, D. (2008). + A goodness-of-fit test for normality based on polynomial regression. + Computational Statistics & Data Analysis, 52(4), 2185-2198. + https://doi.org/10.1016/j.csda.2007.07.012 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( CoinLogNormalGofStatistic, ) - -test_statistic = CoinLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = CoinLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/cressie_read_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/cressie_read_log_normal_criterion.md new file mode 100644 index 00000000..e90b3139 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/cressie_read_log_normal_criterion.md @@ -0,0 +1,65 @@ +# Cressie–Read for log-normal data + +**Class:** `CressieReadLogNormalGofStatistic` + +**Code:** `CRESSIE_READ_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic and binning + +Cressie-Read power divergence with lambda = 2/3. + +Computes 9/5 * sum(observed * ((observed / expected)**(2/3) - 1)). +Zero observed counts contribute zero, by continuity. + +## References +Cressie, N. and Read, T. R. C. (1984). Multinomial Goodness-of-Fit Tests. +JRSS B, 46(3), 440-464. +https://doi.org/10.1111/j.2517-6161.1984.tb01318.x + +The constructor accepts `binning: BinningStrategy`; its default is +`EqualProbabilityBins()`. Bins use the fixed log-normal distribution in the +original sample units. Define observed counts O_j and expected counts +E_j = n * P(X in cell j). The zero-count limits are part of the definition; +Neyman and modified log-likelihood can return positive infinity when O_j=0 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Statistic -`rvs` - array-like sample data passed to `execute_statistic`. +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Cramér-von Mises W² statistic. -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +Computes 1/(12*n)+sum((u_i-(i-0.5)/n)**2). -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Section 2.3. +https://doi.org/10.1111/1467-9868.00337 -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( CramerVonMiseLogNormalGofStatistic, ) - -test_statistic = CramerVonMiseLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = CramerVonMiseLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/dagostino_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/dagostino_log_normal_criterion.md index 22a2e931..81735f53 100644 --- a/docs/criteria/goodness-of-fit/log-normal/dagostino_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/dagostino_log_normal_criterion.md @@ -1,60 +1,84 @@ -# D'Agostino test for log-normal distribution +# D'Agostino test for log-normal data -## Description -Performs D'Agostino goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `DagostinoLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `D_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped DAgostino normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DagostinoLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = DagostinoLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `DagostinoNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/dagostino_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +D=sum_i((i-(n+1)/2)*x_(i))/(n**2*s0). Return +sqrt(n)*(D-0.28209479)/0.02998598. This is the signed, +asymptotically standardized D statistic, not D'Agostino-Pearson K2. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] D'Agostino, R. B. (1971). + An omnibus test of normality for moderate and large size samples. + Biometrika, 58(2), 341-348. + https://doi.org/10.1093/biomet/58.2.341 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( DagostinoLogNormalGofStatistic, ) - -test_statistic = DagostinoLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = DagostinoLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/dagostino_pearson_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/dagostino_pearson_log_normal_criterion.md index 2a4bb5bc..fd14e976 100644 --- a/docs/criteria/goodness-of-fit/log-normal/dagostino_pearson_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/dagostino_pearson_log_normal_criterion.md @@ -1,60 +1,84 @@ -# D'Agostino-Pearson test for log-normal distribution +# D’Agostino–Pearson omnibus test -## Description -Performs D'Agostino-Pearson goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `DAPLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `DAP_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped combined skewness-kurtosis normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DAPLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = DAPLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `DAPNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/dagostino_pearson_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The upper tail of the statistic defines rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +K2 = Z_skew**2 + Z_kurtosis**2 using the signed transforms +implemented by SkewNormalityGofStatistic and KurtosisNormalityGofStatistic. +The resulting nonnegative discrepancy uses the upper tail. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +.. [1] D'Agostino, R. B. and Pearson, E. S. (1973). Tests for departure + from normality. Empirical results for the distributions of b2 and + sqrt(b1). Biometrika, 60(3), 613-622. + https://doi.org/10.1093/biomet/60.3.613 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( DAPLogNormalGofStatistic, ) - -test_statistic = DAPLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = DAPLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/desgagne_lafaye_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/desgagne_lafaye_log_normal_criterion.md index ccc6d256..5f2113d2 100644 --- a/docs/criteria/goodness-of-fit/log-normal/desgagne_lafaye_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/desgagne_lafaye_log_normal_criterion.md @@ -1,60 +1,89 @@ -# Desgagne-Lafaye test for log-normal distribution +# Desgagne-Lafaye test for log-normal data -## Description -Performs Desgagne-Lafaye goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `DesgagneLafayeLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `DLDMZEPD_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Desgagne-Lafaye normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DesgagneLafayeLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = DesgagneLafayeLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `DesgagneLafayeNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/desgagne_lafaye_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +For z=(x-mean(x))/s0, let r=(0.18240929-mean(z**2*log(abs(z)))/2, +0.5348223-mean(log(1+abs(z))), +0.20981558-mean(log(log(e+abs(z))))). Return n*r.T*A*r, where +A is the rounded inverse fitted-score covariance in stat35. +The first integrand is zero at z=0 by continuity. Theorem 1 of the +author preprint accounts for fitting mean and variance. A is ill +conditioned; rounding its constants limits precision. Small-sample +chi-square calibration is inappropriate. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Desgagne, A., Lafaye de Micheaux, P., and Leblanc, A. (2013). + "Test of Normality Against Generalized Exponential Power + Alternatives." Communications in Statistics - Theory and Methods, + 42(1), 164-190. https://doi.org/10.1080/03610926.2011.577548 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( DesgagneLafayeLogNormalGofStatistic, ) - -test_statistic = DesgagneLafayeLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = DesgagneLafayeLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/doornik_hansen_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/doornik_hansen_log_normal_criterion.md index f5365ea4..cb661d7c 100644 --- a/docs/criteria/goodness-of-fit/log-normal/doornik_hansen_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/doornik_hansen_log_normal_criterion.md @@ -1,60 +1,85 @@ -# Doornik-Hansen test for log-normal distribution +# Doornik-Hansen test for log-normal data -## Description -Performs Doornik-Hansen goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `DoornikHansenLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `DH_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Doornik-Hansen normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DoornikHansenLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = DoornikHansenLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `DoornikHansenNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/doornik_hansen_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return Z1**2+Z2**2, with the Doornik-Hansen transformations of +g1=m3/m2**1.5 and g2=m4/m2**2 (Appendix A of the author preprint). +Z1 uses asinh; Z2 uses the real cube root and includes the g1**2 +adjustment to kurtosis. The chi-square law is asymptotic. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Doornik, J. A. and Hansen, H. (2008). + An Omnibus Test for Univariate and Multivariate Normality. + Oxford Bulletin of Economics and Statistics, 70(s1), 927-939. + https://doi.org/10.1111/j.1468-0084.2008.00537.x + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( DoornikHansenLogNormalGofStatistic, ) - -test_statistic = DoornikHansenLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = DoornikHansenLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/epps_pulley_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/epps_pulley_log_normal_criterion.md index 09ebfb9d..10b0dd9b 100644 --- a/docs/criteria/goodness-of-fit/log-normal/epps_pulley_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/epps_pulley_log_normal_criterion.md @@ -1,60 +1,85 @@ -# Epps-Pulley test for log-normal distribution +# Epps-Pulley test for log-normal data -## Description -Performs Epps-Pulley goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `EppsPulleyLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `EP_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Epps-Pulley normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - EppsPulleyLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = EppsPulleyLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `EppsPulleyNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/epps_pulley_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +For z=(x-mean(x))/s0, return +n/sqrt(3) + sum_ij(exp(-(z_i-z_j)**2/2))/n +- sqrt(2)*sum_i(exp(-z_i**2/4)). +This equals n times a Gaussian-weighted squared characteristic-function +distance. The double sum includes its diagonal; computation is O(n**2). ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Epps, T. W. and Pulley, L. B. (1983). A test for normality based + on the empirical characteristic function. Biometrika, 70(3), 723-726. + https://doi.org/10.1093/biomet/70.3.723 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( EppsPulleyLogNormalGofStatistic, ) - -test_statistic = EppsPulleyLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = EppsPulleyLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/filliben_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/filliben_log_normal_criterion.md index fc8a980a..b5593ccf 100644 --- a/docs/criteria/goodness-of-fit/log-normal/filliben_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/filliben_log_normal_criterion.md @@ -1,60 +1,82 @@ -# Filliben test for log-normal distribution +# Filliben test for log-normal data -## Description -Performs Filliben goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `FilliLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `FILLI_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Filliben normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - FilliLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = FilliLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `FilliNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/filliben_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return corr(x_(i), Phi**-1(p_i)). The interior plotting positions +are (i-0.3175)/(n+0.365); endpoints are 1-0.5**(1/n) and 0.5**(1/n). ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Filliben, J. J. (1975). The Probability Plot Correlation + Coefficient Test for Normality. Technometrics, 17(1), 111-117. + https://doi.org/10.1080/00401706.1975.10489279 + + +## Rejection and calibration + +Rejection tail: **left**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( FilliLogNormalGofStatistic, ) - -test_statistic = FilliLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = FilliLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/freeman_tukey_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/freeman_tukey_log_normal_criterion.md new file mode 100644 index 00000000..16afa7aa --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/freeman_tukey_log_normal_criterion.md @@ -0,0 +1,64 @@ +# Freeman–Tukey for log-normal data + +**Class:** `FreemanTukeyLogNormalGofStatistic` + +**Code:** `FREEMAN_TUKEY_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic and binning + +Freeman-Tukey: 4 * sum((sqrt(observed) - sqrt(expected))**2). + +Zero observed counts contribute 4 * expected to the statistic. + +## References +Cressie, N. and Read, T. R. C. (1984). Multinomial Goodness-of-Fit Tests. +JRSS B, 46(3), 440-464; power divergence with lambda = -1/2. +https://doi.org/10.1111/j.2517-6161.1984.tb01318.x + +The constructor accepts `binning: BinningStrategy`; its default is +`EqualProbabilityBins()`. Bins use the fixed log-normal distribution in the +original sample units. Define observed counts O_j and expected counts +E_j = n * P(X in cell j). The zero-count limits are part of the definition; +Neyman and modified log-likelihood can return positive infinity when O_j=0 exp(a) * X**b`, b > 0. + +## Underlying normality definition + +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/glen_leemis_barr_normality_criterion.md). + + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +For z=(x-mean(x))/s1, form u_i=Phi(z_(i)), then +v_i=BetaCDF(u_i; i,n+1-i), and sort the v_i again. Return +-n-sum_i((2*n+1-2*i)*log(v_(i))+(2*i-1)*log(1-v_(i)))/n. +These are reversed Anderson-Darling weights, not the ordinary AD +statistic. A primary source confirming this exact fitted formula was +not located in the review; no author-specific calibration is claimed. +The beta transforms are dependent and are not uniform after fitting. +Use simulation of this formula only. Log-binomial sums recover +beta tails that underflow in direct probability arithmetic. -## Description -Performs Glen-Leemis-Barr goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. - -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. - -Test Statistic -The statistic is based on the wrapped Glen-Leemis-Barr normality statistic applied to standardized log observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GlenLeemisBarrLogNormalGofStatistic, -) - - -test_statistic = GlenLeemisBarrLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. - -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. +## References -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Glen, A. G., Leemis, L. M., Barr, D. R. (2001). Order statistics in goodness-of-fit testing. IEEE Transactions on Reliability, 50(2), 209–213. +https://doi.org/10.1109/24.963129 -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +This identifies the order-statistic approach. The primary full text was not accessible during this audit; the reversed-weight, fitted-normal implementation is checked as the formula documented here, not certified as an exact reproduction of that paper. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( GlenLeemisBarrLogNormalGofStatistic, ) - -test_statistic = GlenLeemisBarrLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = GlenLeemisBarrLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/gmg_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/gmg_log_normal_criterion.md index 58b9c78d..8188e94d 100644 --- a/docs/criteria/goodness-of-fit/log-normal/gmg_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/gmg_log_normal_criterion.md @@ -1,60 +1,85 @@ -# GMG test for log-normal distribution +# GMG test for log-normal data -## Description -Performs GMG goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `GMGLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `GMG_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped GMG normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GMGLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = GMGLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `GMGNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/gmg_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return s0/J, where J=sqrt(pi/2)*mean(abs(x-median(x))). +This is a directed upper-tail statistic for heavy-tailed departures. +The ddof=0 convention is retained; its finite-sample law differs +from versions using the unbiased sample variance. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Gel, Y. R., Miao, W. and Gastwirth, J. L. (2007). + Robust directed tests of normality against heavy-tailed alternatives. + Computational Statistics & Data Analysis, 51(5), 2734-2746. + https://doi.org/10.1016/j.csda.2006.08.022 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( GMGLogNormalGofStatistic, ) - -test_statistic = GMGLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = GMGLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/hosking1_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/hosking1_log_normal_criterion.md index 0608bec6..efebe32e 100644 --- a/docs/criteria/goodness-of-fit/log-normal/hosking1_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/hosking1_log_normal_criterion.md @@ -1,60 +1,94 @@ -# Hosking1 test for log-normal distribution +# Hosking1 test for log-normal data + +**Class:** `Hosking1LogNormalGofStatistic` + +**Code:** `HOSKING1_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. + +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. + +## Logarithmic reduction + +The implementation computes `Hosking1NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. + +## Underlying normality definition + +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/hosking1_normality_criterion.md). + + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Local quadratic discrepancy of L-moment ratios with trim t=0. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -## Description -Performs Hosking1 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. - -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. - -Test Statistic -The statistic is based on the wrapped Hosking1 normality statistic applied to standardized log observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking1LogNormalGofStatistic, -) - - -test_statistic = Hosking1LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. - -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## References -`rvs` - array-like sample data passed to `execute_statistic`. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +These articles justify the L-moment construction, not the three local rows of calibration constants used here. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( Hosking1LogNormalGofStatistic, ) - -test_statistic = Hosking1LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = Hosking1LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/hosking2_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/hosking2_log_normal_criterion.md index d74045ed..fe198a2d 100644 --- a/docs/criteria/goodness-of-fit/log-normal/hosking2_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/hosking2_log_normal_criterion.md @@ -1,60 +1,94 @@ -# Hosking2 test for log-normal distribution +# Hosking2 test for log-normal data + +**Class:** `Hosking2LogNormalGofStatistic` + +**Code:** `HOSKING2_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. + +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. + +## Logarithmic reduction + +The implementation computes `Hosking2NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. + +## Underlying normality definition + +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/hosking2_normality_criterion.md). + + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 6 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Local quadratic discrepancy of L-moment ratios with trim t=1. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -## Description -Performs Hosking2 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. - -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. - -Test Statistic -The statistic is based on the wrapped Hosking2 normality statistic applied to standardized log observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking2LogNormalGofStatistic, -) - - -test_statistic = Hosking2LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. - -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## References -`rvs` - array-like sample data passed to `execute_statistic`. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +These articles justify the L-moment construction, not the three local rows of calibration constants used here. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( Hosking2LogNormalGofStatistic, ) - -test_statistic = Hosking2LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = Hosking2LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/hosking3_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/hosking3_log_normal_criterion.md index 98453479..075b1d3e 100644 --- a/docs/criteria/goodness-of-fit/log-normal/hosking3_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/hosking3_log_normal_criterion.md @@ -1,60 +1,94 @@ -# Hosking3 test for log-normal distribution +# Hosking3 test for log-normal data + +**Class:** `Hosking3LogNormalGofStatistic` + +**Code:** `HOSKING3_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. + +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. + +## Logarithmic reduction + +The implementation computes `Hosking3NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. + +## Underlying normality definition + +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/hosking3_normality_criterion.md). + + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Local quadratic discrepancy of L-moment ratios with trim t=2. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -## Description -Performs Hosking3 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. - -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. - -Test Statistic -The statistic is based on the wrapped Hosking3 normality statistic applied to standardized log observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking3LogNormalGofStatistic, -) - - -test_statistic = Hosking3LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. - -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## References -`rvs` - array-like sample data passed to `execute_statistic`. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +These articles justify the L-moment construction, not the three local rows of calibration constants used here. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( Hosking3LogNormalGofStatistic, ) - -test_statistic = Hosking3LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = Hosking3LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/hosking4_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/hosking4_log_normal_criterion.md index fb937749..ce490999 100644 --- a/docs/criteria/goodness-of-fit/log-normal/hosking4_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/hosking4_log_normal_criterion.md @@ -1,60 +1,94 @@ -# Hosking4 test for log-normal distribution +# Hosking4 test for log-normal data + +**Class:** `Hosking4LogNormalGofStatistic` + +**Code:** `HOSKING4_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. + +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. + +## Logarithmic reduction + +The implementation computes `Hosking4NormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. + +## Underlying normality definition + +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/hosking4_normality_criterion.md). + + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 10 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Local quadratic discrepancy of L-moment ratios with trim t=3. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -## Description -Performs Hosking4 goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. - -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. - -Test Statistic -The statistic is based on the wrapped Hosking4 normality statistic applied to standardized log observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking4LogNormalGofStatistic, -) - - -test_statistic = Hosking4LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. - -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## References -`rvs` - array-like sample data passed to `execute_statistic`. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +These articles justify the L-moment construction, not the three local rows of calibration constants used here. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( Hosking4LogNormalGofStatistic, ) - -test_statistic = Hosking4LogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = Hosking4LogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/index.md b/docs/criteria/goodness-of-fit/log-normal/index.md new file mode 100644 index 00000000..00723393 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/index.md @@ -0,0 +1,117 @@ +# Log-normal goodness-of-fit statistics + +All **55 concrete statistics** exported by `continuous.log_normal` are listed +below. There are 15 EDF variants, 5 frequency statistics, one spacing statistic, +32 logarithmic normality wrappers and two KL functionals. The abstract base is +not itself a test. Every row links to a formula, executable example and scientific +sources; the [mathematical verification](mathematical-validation.md) distinguishes +verified definitions from unresolved historical attribution. + +## Choosing the hypothesis + +- **Fixed:** `LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8})` or + `LogNormal.SHAPE_SCALE.parse({"s": 0.8, "scale": exp(0.4)})`. + These 21 criteria test a specified CDF; `s` is log standard deviation, + `mu` is log mean and `scale` is the median. The mean of X is exp(mu+s²/2). +- **Family:** `LogNormal.DEFAULT.parse({})`. The 34 shape criteria remove + log-location and log-scale. Fully fixed schemas remain accepted for API + compatibility, but their values are ignored by the shape statistic. These + criteria cannot distinguish log-normal laws with different parameters. +- Omitted parameters are never silently filled into a hypothesis. Both coordinate + schemas are supported, partial schemas are rejected, and `hypothesis()` + preserves the input. Family calibration explicitly chooses mu=0,s=1 for + sampling; it does not change the hypothesis. + +All inputs must be finite, real, one-dimensional and unmasked. Logarithmic +statistics additionally require strictly positive observations and sufficient +nonconstant log data; individual pages state their minimum sizes. EDF statistics +may assign a finite discrepancy to out-of-support data. Frequency zero-count +limits may legitimately be infinite. Undefined input raises `ValueError`. + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + KolmogorovSmirnovLogNormalGofStatistic, + ShapiroWilkLogNormalGofStatistic, +) +from pysatl_criterion.utils.generator import get_hypothesis_generator + +sample = np.exp([-1.3, -0.8, -0.4, -0.1, 0.1, 0.3, 0.7, 0.9, 1.4, 2.0]) +fixed = KolmogorovSmirnovLogNormalGofStatistic(LogNormal.DEFAULT.parse({"mu": 0, "s": 1})) +family = ShapiroWilkLogNormalGofStatistic(LogNormal.DEFAULT.parse({})) +assert np.isfinite(fixed.execute_statistic(sample)) +assert np.isfinite(family.execute_statistic(sample)) +assert family.hypothesis().parameters() == {} +assert get_hypothesis_generator(family).parameters() == {"mu": 0, "s": 1} +``` + +## Complete catalog + +| Class | Full code | Hypothesis | Rejection tail | Page | +| --- | --- | --- | --- | --- | +| `AndersonDarlingLogNormalGofStatistic` | `AD_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Anderson-Darling test for log-normal data](anderson_darling_log_normal_criterion.md) | +| `BonettSeierLogNormalGofStatistic` | `BS_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [Bonett-Seier test for log-normal data](bonett_seier_log_normal_criterion.md) | +| `BontempsMeddahi1LogNormalGofStatistic` | `BM1_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Bontemps-Meddahi1 test for log-normal data](bontemps_meddahi1_log_normal_criterion.md) | +| `BontempsMeddahi2LogNormalGofStatistic` | `BM2_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Bontemps-Meddahi2 test for log-normal data](bontemps_meddahi2_log_normal_criterion.md) | +| `CabanaCabana1LogNormalGofStatistic` | `CC1_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Cabana-Cabana1 test for log-normal data](cabana_cabana1_log_normal_criterion.md) | +| `CabanaCabana2LogNormalGofStatistic` | `CC2_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Cabana-Cabana2 test for log-normal data](cabana_cabana2_log_normal_criterion.md) | +| `ChenShapiroLogNormalGofStatistic` | `CS_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Chen-Shapiro test for log-normal data](chen_shapiro_log_normal_criterion.md) | +| `Chi2PearsonLogNormalGofStatistic` | `CHI2_PEARSON_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Pearson chi-squared for log-normal data](chi2_pearson_log_normal_criterion.md) | +| `CoinLogNormalGofStatistic` | `COIN_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Coin test for log-normal data](coin_log_normal_criterion.md) | +| `CramerVonMiseLogNormalGofStatistic` | `CVM_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Cramer-von Mises test for log-normal data](cvm_log_normal_criterion.md) | +| `CressieReadLogNormalGofStatistic` | `CRESSIE_READ_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Cressie–Read for log-normal data](cressie_read_log_normal_criterion.md) | +| `DAPLogNormalGofStatistic` | `DAP_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [D’Agostino–Pearson omnibus test](dagostino_pearson_log_normal_criterion.md) | +| `DagostinoLogNormalGofStatistic` | `D_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [D'Agostino test for log-normal data](dagostino_log_normal_criterion.md) | +| `DesgagneLafayeLogNormalGofStatistic` | `DLDMZEPD_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Desgagne-Lafaye test for log-normal data](desgagne_lafaye_log_normal_criterion.md) | +| `DoornikHansenLogNormalGofStatistic` | `DH_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Doornik-Hansen test for log-normal data](doornik_hansen_log_normal_criterion.md) | +| `EppsPulleyLogNormalGofStatistic` | `EP_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Epps-Pulley test for log-normal data](epps_pulley_log_normal_criterion.md) | +| `FilliLogNormalGofStatistic` | `FILLI_LOGNORMAL_GOODNESS_OF_FIT` | Family | left | [Filliben test for log-normal data](filliben_log_normal_criterion.md) | +| `FreemanTukeyLogNormalGofStatistic` | `FREEMAN_TUKEY_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Freeman–Tukey for log-normal data](freeman_tukey_log_normal_criterion.md) | +| `GMGLogNormalGofStatistic` | `GMG_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [GMG test for log-normal data](gmg_log_normal_criterion.md) | +| `GlenLeemisBarrLogNormalGofStatistic` | `GLB_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Glen-Leemis-Barr test for log-normal data](glen_leemis_barr_log_normal_criterion.md) | +| `Hosking1LogNormalGofStatistic` | `HOSKING1_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Hosking1 test for log-normal data](hosking1_log_normal_criterion.md) | +| `Hosking2LogNormalGofStatistic` | `HOSKING2_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Hosking2 test for log-normal data](hosking2_log_normal_criterion.md) | +| `Hosking3LogNormalGofStatistic` | `HOSKING3_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Hosking3 test for log-normal data](hosking3_log_normal_criterion.md) | +| `Hosking4LogNormalGofStatistic` | `HOSKING4_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Hosking4 test for log-normal data](hosking4_log_normal_criterion.md) | +| `JBLogNormalGofStatistic` | `JB_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Jarque-Bera test for log-normal data](jarque_bera_log_normal_criterion.md) | +| `KLIntegralLogNormalGoFStatistic` | `KL_INT_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [KL integral test for log-normal distribution](kl_integral_log_normal_criterion.md) | +| `KLSupremumLogNormalGoFStatistic` | `KL_SUP_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [KL supremum test for log-normal distribution](kl_supremum_log_normal_criterion.md) | +| `KolmogorovSmirnovDMinusLogNormalGofStatistic` | `KS_MINUS_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Kolmogorov–Smirnov D− for log-normal data](kolmogorov_smirnov_d_minus_log_normal_criterion.md) | +| `KolmogorovSmirnovDPlusLogNormalGofStatistic` | `KS_PLUS_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Kolmogorov–Smirnov D+ for log-normal data](kolmogorov_smirnov_d_plus_log_normal_criterion.md) | +| `KolmogorovSmirnovLogNormalGofStatistic` | `KS_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Kolmogorov-Smirnov test for log-normal data](kolmogorov_smirnov_log_normal_criterion.md) | +| `KuiperCorrectedLogNormalGofStatistic` | `KUIPER_CORRECTED_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Corrected Kuiper for log-normal data](kuiper_corrected_log_normal_criterion.md) | +| `KuiperLogNormalGofStatistic` | `KUIPER_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Kuiper for log-normal data](kuiper_log_normal_criterion.md) | +| `KuiperScaledLogNormalGofStatistic` | `KUIPER_SCALED_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Scaled Kuiper for log-normal data](kuiper_scaled_log_normal_criterion.md) | +| `KurtosisLogNormalGofStatistic` | `KURTOSIS_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [Kurtosis test for log-normal data](kurtosis_log_normal_criterion.md) | +| `LiaoShimokawaLogNormalGofStatistic` | `LIAO_SHIMOKAWA_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Liao–Shimokawa for log-normal data](liao_shimokawa_log_normal_criterion.md) | +| `LooneyGulledgeLogNormalGofStatistic` | `LG_LOGNORMAL_GOODNESS_OF_FIT` | Family | left | [Looney-Gulledge test for log-normal data](looney_gulledge_log_normal_criterion.md) | +| `MartinezIglewiczLogNormalGofStatistic` | `MI_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Martinez-Iglewicz test for log-normal data](martinez_iglewicz_log_normal_criterion.md) | +| `ModifiedLogLikelihoodLogNormalGofStatistic` | `MODIFIED_LOG_LIKELIHOOD_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Modified log likelihood for log-normal data](modified_log_likelihood_log_normal_criterion.md) | +| `NeymanChi2LogNormalGofStatistic` | `CHI2_NEYMAN_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Neyman chi-squared for log-normal data](neyman_chi2_log_normal_criterion.md) | +| `QuesenberryMillerLogNormalGofStatistic` | `QUESENBERRY_MILLER_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Quesenberry-Miller test for log-normal distribution](quesenberry_miller_log_normal_criterion.md) | +| `RobustJarqueBeraLogNormalGofStatistic` | `RJB_LOGNORMAL_GOODNESS_OF_FIT` | Family | right | [Robust Jarque-Bera test for log-normal data](robust_jarque_bera_log_normal_criterion.md) | +| `RyanJoinerLogNormalGofStatistic` | `RJ_LOGNORMAL_GOODNESS_OF_FIT` | Family | left | [Ryan-Joiner test for log-normal data](ryan_joiner_log_normal_criterion.md) | +| `SFLogNormalGofStatistic` | `SF_LOGNORMAL_GOODNESS_OF_FIT` | Family | left | [SF test for log-normal data](sf_log_normal_criterion.md) | +| `SWRGLogNormalGofStatistic` | `SWRG_LOGNORMAL_GOODNESS_OF_FIT` | Family | left | [SWRG test for log-normal data](swrg_log_normal_criterion.md) | +| `ShapiroWilkLogNormalGofStatistic` | `SW_LOGNORMAL_GOODNESS_OF_FIT` | Family | left | [Shapiro-Wilk test for log-normal data](shapiro_wilk_log_normal_criterion.md) | +| `SkewLogNormalGofStatistic` | `SKEW_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [Skewness test for log-normal data](skew_log_normal_criterion.md) | +| `SpiegelhalterLogNormalGofStatistic` | `SH_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [Spiegelhalter test for log-normal data](spiegelhalter_log_normal_criterion.md) | +| `WatsonLogNormalGofStatistic` | `WATSON_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Watson for log-normal data](watson_log_normal_criterion.md) | +| `ZhangALogNormalGofStatistic` | `ZHANG_ZA_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Zhang A for log-normal data](zhang_a_log_normal_criterion.md) | +| `ZhangCLogNormalGofStatistic` | `ZHANG_ZC_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Zhang C for log-normal data](zhang_c_log_normal_criterion.md) | +| `ZhangKLogNormalGofStatistic` | `ZHANG_ZK_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Zhang K for log-normal data](zhang_k_log_normal_criterion.md) | +| `ZhangQLogNormalGofStatistic` | `ZQ_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [Zhang Q test for log-normal data](zhang_q_log_normal_criterion.md) | +| `ZhangQStarLogNormalGofStatistic` | `ZQS_LOGNORMAL_GOODNESS_OF_FIT` | Family | two_tailed | [Zhang Q-star test for log-normal data](zhang_q_star_log_normal_criterion.md) | +| `ZhangWuALogNormalGofStatistic` | `ZWA_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Zhang-Wu A test for log-normal data](zhang_wu_a_log_normal_criterion.md) | +| `ZhangWuCLogNormalGofStatistic` | `ZWC_LOGNORMAL_GOODNESS_OF_FIT` | Fixed | right | [Zhang-Wu C test for log-normal data](zhang_wu_c_log_normal_criterion.md) | + +## Calibration and limitations + +Fixed-CDF EDF formulas use u=F(X); fitted-normal tables do not apply. +Family statistics reuse the normality functional on log observations. Their +normality approximations and qualifications remain applicable: particularly +Hosking 1–4, GLB, Coin and finite-order moment tests. KL uses a finite r window; +its legacy critical-value regressions are not certified. The report explains +what was independently checked and what remains unverified. Recalibrate changed +statistics; old unversioned stored values are not evidence of correct size. diff --git a/docs/criteria/goodness-of-fit/log-normal/jarque_bera_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/jarque_bera_log_normal_criterion.md index 78f7d858..a76861a2 100644 --- a/docs/criteria/goodness-of-fit/log-normal/jarque_bera_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/jarque_bera_log_normal_criterion.md @@ -1,60 +1,82 @@ -# Jarque-Bera test for log-normal distribution +# Jarque-Bera test for log-normal data -## Description -Performs Jarque-Bera goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `JBLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `JB_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Jarque-Bera normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - JBLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = JBLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `JBNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/jarque_bera_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +JB = n*(g1**2/6 + (g2-3)**2/24), where +g1=m3/m2**1.5, g2=m4/m2**2, and mk=mean((x-mean(x))**k). ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Jarque, C. M. and Bera, A. K. (1987). A Test for Normality of + Observations and Regression Residuals. International Statistical + Review, 55(2), 163-172. https://doi.org/10.2307/1403192 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( JBLogNormalGofStatistic, ) - -test_statistic = JBLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = JBLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kl_integral_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kl_integral_log_normal_criterion.md index 4bac76f2..fda5954e 100644 --- a/docs/criteria/goodness-of-fit/log-normal/kl_integral_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/kl_integral_log_normal_criterion.md @@ -1,60 +1,87 @@ # KL integral test for log-normal distribution -## Description -Performs KL integral goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `KLIntegralLogNormalGoFStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `KL_INT_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the integral of squared standardized Kullback-Leibler divergence components. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KLIntegralLogNormalGoFStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = KLIntegralLogNormalGoFStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Statistic -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +At least two positive, nonconstant observations are required. Set +$y_i=\log x_i$, $z_i=(y_i-\bar y)/s_0$ with +$s_0^2=n^{-1}\sum_i(y_i-\bar y)^2$. Define -`rvs` - array-like sample data passed to `execute_statistic`. +$$K(r)=\log\left(n^{-1}\sum_i e^{r z_i}\right),\qquad +D(r)=2K(r)-rK'(r),$$ +$$\sigma^2(r)=e^{r^2}(r^4-3r^2+4)-(4+r^2),\qquad R(r)=D(r)/\sigma(r).$$ -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +The returned value is $n\int_{-5}^5 R(r)^2\,dr$, computed with adaptive +quadrature split at zero (absolute and relative tolerance 1e-9). It is a +**truncated** integral; no bound on the omitted infinite tails is asserted. -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +Centering cancels from D exactly. The implementation avoids forming powers +of X and uses log-sum-exp. Near zero it uses cumulants through order 10 and +a positive-coefficient variance series. If m3 = mean(z**3), +$\lim_{r\downarrow0}R(r)=-m_3/\sqrt6$ and +$\lim_{r\to0}R(r)^2=m_3^2/6$. This removes the spurious 0/0 singularity. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +## Critical values and source limitations -## Author(s) -Anton Dorosev, Alexey Mironov +`calculate_critical_value(n, alpha)` retains the historical numerical +regressions at alpha=0.01 and 0.05. These are **not verified finite-sample +quantiles**. Their published validity range and compatibility with this +truncated implementation have not been established from accessible full text. +Do not use them as a certified significance rule. Invalid n/alpha and +nonpositive or nonfinite regression outputs are rejected; +other significance levels raise `NotImplementedError`, because the old generic +formula could produce negative critical values. Prefer Monte Carlo simulation +of this exact implementation at the actual sample size. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[Batsidis, Economou and Tzavelas (2016), Tests of fit for a lognormal distribution, +Journal of Statistical Computation and Simulation 86(2), 215–235](https://doi.org/10.1080/00949655.2014.1003138). +The publisher abstract verifies the KL size-bias symmetry motivation; full text +was inaccessible. The formulas above were checked independently with 70-digit +arithmetic and quadrature, not certified as an exact reproduction of every +normalization and integration domain in that paper. + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( KLIntegralLogNormalGoFStatistic, ) - -test_statistic = KLIntegralLogNormalGoFStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = KLIntegralLogNormalGoFStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kl_supremum_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kl_supremum_log_normal_criterion.md index 32b65f9f..af6e6aed 100644 --- a/docs/criteria/goodness-of-fit/log-normal/kl_supremum_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/kl_supremum_log_normal_criterion.md @@ -1,60 +1,87 @@ # KL supremum test for log-normal distribution -## Description -Performs KL supremum goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `KLSupremumLogNormalGoFStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `KL_SUP_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the supremum of standardized Kullback-Leibler divergence components over a fixed grid. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KLSupremumLogNormalGoFStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = KLSupremumLogNormalGoFStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Statistic -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +At least two positive, nonconstant observations are required. Set +$y_i=\log x_i$, $z_i=(y_i-\bar y)/s_0$ with +$s_0^2=n^{-1}\sum_i(y_i-\bar y)^2$. Define -`rvs` - array-like sample data passed to `execute_statistic`. +$$K(r)=\log\left(n^{-1}\sum_i e^{r z_i}\right),\qquad +D(r)=2K(r)-rK'(r),$$ +$$\sigma^2(r)=e^{r^2}(r^4-3r^2+4)-(4+r^2),\qquad R(r)=D(r)/\sigma(r).$$ -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +The returned value is $\sqrt n\max_{r\in G}|R(r)|$, where G has 1000 +equally spaced points including -5 and 5. This is a grid maximum, **not** +a continuous supremum, nor a supremum over the whole real line. -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +Centering cancels from D exactly. The implementation avoids forming powers +of X and uses log-sum-exp. Near zero it uses cumulants through order 10 and +a positive-coefficient variance series. If m3 = mean(z**3), +$\lim_{r\downarrow0}R(r)=-m_3/\sqrt6$ and +$\lim_{r\to0}R(r)^2=m_3^2/6$. This removes the spurious 0/0 singularity. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +## Critical values and source limitations -## Author(s) -Anton Dorosev, Alexey Mironov +`calculate_critical_value(n, alpha)` retains the historical numerical +regressions at alpha=0.01 and 0.05. These are **not verified finite-sample +quantiles**. Their published validity range and compatibility with this +truncated implementation have not been established from accessible full text. +Do not use them as a certified significance rule. Invalid n/alpha and +nonpositive or nonfinite regression outputs are rejected; +other significance levels raise `NotImplementedError`, because the old generic +formula could produce negative critical values. Prefer Monte Carlo simulation +of this exact implementation at the actual sample size. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[Batsidis, Economou and Tzavelas (2016), Tests of fit for a lognormal distribution, +Journal of Statistical Computation and Simulation 86(2), 215–235](https://doi.org/10.1080/00949655.2014.1003138). +The publisher abstract verifies the KL size-bias symmetry motivation; full text +was inaccessible. The formulas above were checked independently with 70-digit +arithmetic and quadrature, not certified as an exact reproduction of every +normalization and integration domain in that paper. + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( KLSupremumLogNormalGoFStatistic, ) - -test_statistic = KLSupremumLogNormalGoFStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = KLSupremumLogNormalGoFStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_d_minus_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_d_minus_log_normal_criterion.md new file mode 100644 index 00000000..943da4c0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_d_minus_log_normal_criterion.md @@ -0,0 +1,55 @@ +# Kolmogorov–Smirnov D− for log-normal data + +**Class:** `KolmogorovSmirnovDMinusLogNormalGofStatistic` + +**Code:** `KS_MINUS_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +One-sided D- deviation for sorted CDF values. + +## References +Smirnov, N. (1948). Table for Estimating the Goodness of Fit of Empirical +Distributions. Annals of Mathematical Statistics, 19(2), 279-281. +https://doi.org/10.1214/aoms/1177730256 + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + KolmogorovSmirnovDMinusLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = KolmogorovSmirnovDMinusLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_d_plus_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_d_plus_log_normal_criterion.md new file mode 100644 index 00000000..2ee79a7c --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_d_plus_log_normal_criterion.md @@ -0,0 +1,55 @@ +# Kolmogorov–Smirnov D+ for log-normal data + +**Class:** `KolmogorovSmirnovDPlusLogNormalGofStatistic` + +**Code:** `KS_PLUS_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +One-sided D+ deviation for sorted CDF values. + +## References +Smirnov, N. (1948). Table for Estimating the Goodness of Fit of Empirical +Distributions. Annals of Mathematical Statistics, 19(2), 279-281. +https://doi.org/10.1214/aoms/1177730256 + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + KolmogorovSmirnovDPlusLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = KolmogorovSmirnovDPlusLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_log_normal_criterion.md index 7002d120..b3188199 100644 --- a/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/kolmogorov_smirnov_log_normal_criterion.md @@ -1,60 +1,59 @@ -# Kolmogorov-Smirnov test for log-normal distribution +# Kolmogorov-Smirnov test for log-normal data -## Description -Performs Kolmogorov-Smirnov goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `KolmogorovSmirnovLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `KS_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the maximum distance between the empirical distribution function and the reference log-normal CDF. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KolmogorovSmirnovLogNormalGofStatistic, -) +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. -test_statistic = KolmogorovSmirnovLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Statistic -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. -`rvs` - array-like sample data passed to `execute_statistic`. +Two-sided Kolmogorov-Smirnov D statistic. -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +Returns max(D+, D-), without squaring or sqrt(n) scaling. -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Section 2.1. +https://doi.org/10.1111/1467-9868.00337 -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +`alternative_type=RIGHT` selects D+; `LEFT` selects D−; the default selects D. All three reject large values. `mode` is retained for compatibility and does not change the statistic. -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( KolmogorovSmirnovLogNormalGofStatistic, ) - -test_statistic = KolmogorovSmirnovLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = KolmogorovSmirnovLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kuiper_corrected_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kuiper_corrected_log_normal_criterion.md new file mode 100644 index 00000000..e0541171 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/kuiper_corrected_log_normal_criterion.md @@ -0,0 +1,59 @@ +# Corrected Kuiper for log-normal data + +**Class:** `KuiperCorrectedLogNormalGofStatistic` + +**Code:** `KUIPER_CORRECTED_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Kuiper statistic with a finite-sample correction. + +Computes (sqrt(n) + 0.155 + 0.24 / sqrt(n)) * (D+ + D-). + +## References +Lemeshko et al. (2014), Eq. (3). +https://doi.org/10.3103/S875669901401004X + +Stephens (1970). +https://doi.org/10.1111/j.2517-6161.1970.tb00821.x + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + KuiperCorrectedLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = KuiperCorrectedLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kuiper_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kuiper_log_normal_criterion.md new file mode 100644 index 00000000..3bcaefb3 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/kuiper_log_normal_criterion.md @@ -0,0 +1,55 @@ +# Kuiper for log-normal data + +**Class:** `KuiperLogNormalGofStatistic` + +**Code:** `KUIPER_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Kuiper statistic computed from CDF values of a sorted sample. +Kuiper (1960), https://doi.org/10.1016/S1385-7258(60)50006-0; unscaled D+ + D-. + +## References + +[Kuiper (1960), Tests concerning random points on a circle](https://doi.org/10.1016/S1385-7258(60)50006-0). + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + KuiperLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = KuiperLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kuiper_scaled_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kuiper_scaled_log_normal_criterion.md new file mode 100644 index 00000000..a0ed9967 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/kuiper_scaled_log_normal_criterion.md @@ -0,0 +1,54 @@ +# Scaled Kuiper for log-normal data + +**Class:** `KuiperScaledLogNormalGofStatistic` + +**Code:** `KUIPER_SCALED_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Kuiper statistic scaled by sqrt(n). + +## References +Lemeshko et al. (2014), section "Kuiper Test", before Eq. (2). +https://doi.org/10.3103/S875669901401004X + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + KuiperScaledLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = KuiperScaledLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/kurtosis_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/kurtosis_log_normal_criterion.md index 93f6d014..2ba36b45 100644 --- a/docs/criteria/goodness-of-fit/log-normal/kurtosis_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/kurtosis_log_normal_criterion.md @@ -1,60 +1,85 @@ -# Kurtosis test for log-normal distribution +# Kurtosis test for log-normal data -## Description -Performs Kurtosis goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `KurtosisLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `KURTOSIS_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped kurtosis normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KurtosisLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = KurtosisLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `KurtosisNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/kurtosis_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 5 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return the signed Anscombe-Glynn transform of g2=m4/m2**2, +using the finite-n expectation, variance and skewness of g2. A real +cube root is used. A zero transformation denominator is undefined. +Both light and heavy tails matter; the normal approximation is +particularly inaccurate for small samples. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Anscombe, F. J. and Glynn, W. J. (1983). Distribution of the + kurtosis statistic b2 for normal samples. Biometrika, 70(1), 227-234. + https://doi.org/10.1093/biomet/70.1.227 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( KurtosisLogNormalGofStatistic, ) - -test_statistic = KurtosisLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = KurtosisLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/liao_shimokawa_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/liao_shimokawa_log_normal_criterion.md new file mode 100644 index 00000000..fc2119a5 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/liao_shimokawa_log_normal_criterion.md @@ -0,0 +1,62 @@ +# Liao–Shimokawa for log-normal data + +**Class:** `LiaoShimokawaLogNormalGofStatistic` + +**Code:** `LIAO_SHIMOKAWA_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Liao–Shimokawa L_n statistic for sorted sample CDF values. + +Computes sum(max(i/n-u_i, u_i-(i-1)/n)/sqrt(u_i*(1-u_i)))/sqrt(n). +Endpoints give positive infinity. Applying this kernel to a specified +uniform CDF requires uniform-null calibration; fitted Weibull/extreme-value +critical values from the paper do not apply. + +## References +Liao, M., & Shimokawa, T. (1999). +A new goodness-of-fit test for type-I extreme-value and +2-parameter Weibull distributions with estimated parameters. +Journal of Statistical Computation and Simulation, 64(1), 23–48. +https://doi.org/10.1080/00949659908811965 + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + LiaoShimokawaLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = LiaoShimokawaLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/lilliefors_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/lilliefors_log_normal_criterion.md deleted file mode 100644 index eba1fcc7..00000000 --- a/docs/criteria/goodness-of-fit/log-normal/lilliefors_log_normal_criterion.md +++ /dev/null @@ -1,60 +0,0 @@ -# Lilliefors test for log-normal distribution - -## Description -Performs Lilliefors goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. - -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. - -Test Statistic -The statistic is based on the wrapped Lilliefors normality statistic applied to standardized log observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsLogNormalGofStatistic, -) - - -test_statistic = LillieforsLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. - -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -For dynamically generated log-normal tests, the implementation transforms observations with - -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ - -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. - -## Author(s) -Anton Dorosev, Alexey Mironov - -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. - -## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsLogNormalGofStatistic, -) - - -test_statistic = LillieforsLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` diff --git a/docs/criteria/goodness-of-fit/log-normal/looney_gulledge_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/looney_gulledge_log_normal_criterion.md index 79420f15..5a0a106b 100644 --- a/docs/criteria/goodness-of-fit/log-normal/looney_gulledge_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/looney_gulledge_log_normal_criterion.md @@ -1,60 +1,83 @@ -# Looney-Gulledge test for log-normal distribution +# Looney-Gulledge test for log-normal data -## Description -Performs Looney-Gulledge goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `LooneyGulledgeLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `LG_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Looney-Gulledge normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LooneyGulledgeLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = LooneyGulledgeLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `LooneyGulledgeNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/looney_gulledge_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return corr(x_(i), Phi**-1((i-3/8)/(n+1/4))). +The Blom plotting-position version is used without averaging ties. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Looney, S. W. and Gulledge, T. R., Jr. (1985). Use of the + Correlation Coefficient with Normal Probability Plots. The American + Statistician, 39(1), 75-79. + https://doi.org/10.1080/00031305.1985.10479395 + + +## Rejection and calibration + +Rejection tail: **left**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( LooneyGulledgeLogNormalGofStatistic, ) - -test_statistic = LooneyGulledgeLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = LooneyGulledgeLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/martinez_iglewicz_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/martinez_iglewicz_log_normal_criterion.md index e50c9b9d..e637af3e 100644 --- a/docs/criteria/goodness-of-fit/log-normal/martinez_iglewicz_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/martinez_iglewicz_log_normal_criterion.md @@ -1,60 +1,87 @@ -# Martinez-Iglewicz test for log-normal distribution +# Martinez-Iglewicz test for log-normal data -## Description -Performs Martinez-Iglewicz goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `MartinezIglewiczLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `MI_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Martinez-Iglewicz normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MartinezIglewiczLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = MartinezIglewiczLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `MartinezIglewiczNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/martinez_iglewicz_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Let M=median(x), A=median(abs(x-M)), u=(x-M)/(9*A), +and I={i: abs(u_i)<1}. Define B=n*sum_I((x_i-M)**2* +(1-u_i**2)**4)/(sum_I((1-u_i**2)*(1-5*u_i**2)))**2. +Return sum((x-M)**2)/((n-1)*B). Contributions with abs(u)>=1 +are zero in both biweight sums. Zero MAD or a zero biweight +denominator makes the estimator undefined and raises ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Martinez, J. and Iglewicz, B. (1981). + A test for departure from normality based on a biweight estimator of scale. + Biometrika, 68(1), 331-333. + https://doi.org/10.1093/biomet/68.1.331 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( MartinezIglewiczLogNormalGofStatistic, ) - -test_statistic = MartinezIglewiczLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = MartinezIglewiczLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/mathematical-validation.md b/docs/criteria/goodness-of-fit/log-normal/mathematical-validation.md new file mode 100644 index 00000000..605d6ae6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/mathematical-validation.md @@ -0,0 +1,294 @@ +# Mathematical verification of log-normal statistics + +Audit date: 2026-10-17. Scope: **all 55 concrete classes** exported by +`statistics.goodness_of_fit.continuous.log_normal`: 15 EDF variants, five +frequency statistics, one spacing statistic, 32 logarithmic normality wrappers +and two KL functionals. The [catalog](index.md) lists every class, full code, +hypothesis, rejection tail and individual documentation page. + +## Findings and corrections + +1. **Shape tests were presented as tests of fixed parameter values.** Normality + statistics on logs and both KL statistics eliminate log-location and log-scale. + They now accept an empty hypothesis in either coordinate system; Monte Carlo + sampling explicitly selects mu=0,s=1. Fully fixed schemas remain accepted for + compatibility and remain in `hypothesis()`, but these shape statistics are + invariant to those values. They cannot distinguish two log-normal distributions + with different parameters. The 21 fixed-CDF/spacing/frequency tests continue to + require both parameters. This is an explicit contract distinction, not implicit + parameter filling or a claim that every shape test is omnibus. +2. **Invalid logarithmic data could become a rejection-tail error.** A universal + `+inf` penalty is inappropriate for lower-tail tests such as Shapiro–Wilk and + Filliben. Logarithmic wrappers and KL now raise `ValueError` for nonpositive + input. Empty, multidimensional, nonfinite, complex and actively masked data + are rejected before conversion. Quesenberry–Miller now validates its input too. + EDF and frequency behavior follows their mathematical support/zero-count limits. +3. **KL powers and cancellations were unstable.** Forming X**(1/sigma_hat) could + overflow solely because the measurement unit changed. KL now uses centered, + standardized logs, log-sum-exp and a near-zero cumulant series. The former + near-zero expression used uncentered log moments and the wrong coefficient; + the squared limiting integrand is m3²/6, not its former expression. No + integration warnings are suppressed, and zero dispersion is rejected. +4. **The general-alpha KL threshold regression could return impossible negative + thresholds.** For example, the old supremum expression at n=50, alpha=0.025 + gave approximately -103.91 although the statistic is nonnegative. That branch + now raises `NotImplementedError`. The historical alpha=0.01/0.05 formulas + remain available for compatibility, explicitly labelled unverified regressions. + Their finite-sample level and published domain are not certified by this audit. + Nonpositive or nonfinite regression results now raise `ValueError` too. +5. **Documentation coverage was incomplete.** There were 40 pages for 55 classes, + without a complete catalog or a log-normal validation report. The pages now + state formulas, hypotheses, tails, input restrictions, executable examples and + scientific references; all 15 missing pages and MkDocs entries were added. + References to the implementation itself were replaced by scientific sources. +6. **Shared kernels and normality definitions were retained.** Direct CDF + evaluation, KS directions, Zhang–Wu's 10*Z_A-32 normalization and frequency + zero-count limits passed independent comparisons. Qualifications for Hosking, + GLB and approximate normal-score methods are retained, not silently certified. + +## Mathematical reduction and hypothesis conventions + +For X>0, log(X) ~ N(mu,s²) if and only if X is log-normal. There is no density +Jacobian in a test statistic evaluated on transformed observations: the normality +functional is simply T(log(X_1),...,log(X_n)). For location-scale-invariant T, +T(a+b*log(X))=T(log(X)) for b>0. This proves the transfer of the implemented +functional and its null distribution, but does not prove consistency or verify +the scientific provenance of a legacy T. + +For a fully specified null set u_i=Phi((log(x_(i))-mu)/s). The probability +integral transform reduces fixed-CDF EDF and spacing criteria to their uniform +functionals. No mean/variance is fitted. In shape statistics the normality +functional may use s0 (ddof=0), s1 (ddof=1), robust scales or other estimates; +those individual conventions are preserved. They must not be confused with +the specified log-normal shape parameter s. `scale=exp(mu)` is the median; +the arithmetic mean of X is exp(mu+s²/2). + +All statistics reject in the tail listed in the catalog. Signed two-tail +statistics need two simulated quantiles; symmetry is not assumed. D+ and D− +are directional CDF discrepancies but both reject **large** values. Frequency +statistics use O_j and E_j=n*p_j in original sample units; only fixed positive +cell probabilities justify the ordinary multinomial k-1 asymptotic reference. +Adaptive partitions require calibration of the whole binning procedure. + +## Formula-by-formula coverage + +Every row below corresponds to one concrete exported class. “Local” means that +an independently checked mathematical functional is available but equality to +the original named publication or its calibration is unresolved. The independent +normality tests are rerun along with log-transform composition tests; composition +checks alone are not presented as independent verification of an underlying +normality formula. Related references are distinguished from exact provenance. + +| Code and page | Definition checked | Qualification / evidence | Scientific source | +| --- | --- | --- | --- | +| [`AD`](anderson_darling_log_normal_criterion.md) | Weighted EDF integral; density and EDF quadrature using the fixed mu and s | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Anderson & Darling (1954)](https://doi.org/10.1080/01621459.1954.10501232); [Stephens (1976)](https://doi.org/10.1214/aos/1176343411) | +| [`BS`](bonett_seier_log_normal_criterion.md) | sqrt(n+2)*(13.29*log(s0/mean(abs(x-mean(x))))-3)/3.54; original eqs. (5)–(6) | Geary-kurtosis component; both tails | [Bonett & Seier (2002)](https://doi.org/10.1016/S0167-9473(02)00074-9) | +| [`BM1`](bontemps_meddahi1_log_normal_criterion.md) | Sum of squared normalized Hermite means for orders 3–4; scipy.special evaluation | s1 finite-sample convention; iid only | [Bontemps & Meddahi (2005)](https://doi.org/10.1016/j.jeconom.2004.02.014) | +| [`BM2`](bontemps_meddahi2_log_normal_criterion.md) | Same construction for orders 3–6; scipy.special evaluation | s1 finite-sample convention; iid only | [Bontemps & Meddahi (2005)](https://doi.org/10.1016/j.jeconom.2004.02.014) | +| [`CC1`](cabana_cabana1_log_normal_criterion.md) | Continuous supremum of the skewness-focused Hermite process; scalar optimization versus polynomial roots | Truncation five; no claim of consistency against every alternative | [Cabaña & Cabaña (2003)](https://doi.org/10.1023/A:1026235220018) | +| [`CC2`](cabana_cabana2_log_normal_criterion.md) | Continuous supremum of the kurtosis-focused Hermite process; scalar optimization | Truncation five | [Cabaña & Cabaña (2003)](https://doi.org/10.1023/A:1026235220018) | +| [`CS`](chen_shapiro_log_normal_criterion.md) | sqrt(n)*(1-mean(normalized adjacent spacings)/s1) | Approximate normal scores | [Chen & Shapiro (1995)](https://doi.org/10.1080/00949659508811711) | +| [`CHI2_PEARSON`](chi2_pearson_log_normal_criterion.md) | Power divergence lambda=1; independent scipy.stats.power_divergence | Fixed null; independent multinomial power divergence; zero-count limits | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`COIN`](coin_log_normal_criterion.md) | Squared cubic OLS coefficient on normal order scores; independent order-density quadrature and least squares | Approximation: nscor2, 4<=n<=2000; original finite-sample implementation not fully certified | [Coin (2008)](https://doi.org/10.1016/j.csda.2007.07.012) | +| [`CVM`](cvm_log_normal_criterion.md) | Integral of squared EDF discrepancy; independent quadrature and scipy.stats.cramervonmises | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Cramér (1928)](https://doi.org/10.1080/03461238.1928.10416872) | +| [`CRESSIE_READ`](cressie_read_log_normal_criterion.md) | Power divergence lambda=2/3, including factor 9/5 | Fixed null; independent multinomial power divergence; zero-count limits | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`DAP`](dagostino_pearson_log_normal_criterion.md) | Z_skew²+Z_kurtosis²; scipy.stats.normaltest | Upper tail, not signed skewness | [D’Agostino & Pearson (1973)](https://doi.org/10.1093/biomet/60.3.613) | +| [`D`](dagostino_log_normal_criterion.md) | Normalized rank-weighted contrast; independent pairwise absolute-distance representation | Rounded asymptotic centering/scaling; both tails | [D’Agostino (1971)](https://doi.org/10.1093/biomet/58.2.341) | +| [`DLDMZEPD`](desgagne_lafaye_log_normal_criterion.md) | n*r.T*A*r; quadrature of score means, covariance and scale-score projection | Ill-conditioned matrix and rounded coefficients; rel tolerance 2e-4 | [Desgagné, Lafaye de Micheaux & Leblanc (2013)](https://doi.org/10.1080/03610926.2011.577548) | +| [`DH`](doornik_hansen_log_normal_criterion.md) | Squared transformed skewness plus conditional kurtosis; published appendix numerical example | n>=8; finite-sample chi-square approximation is not exact | [Doornik & Hansen (2008)](https://doi.org/10.1111/j.1468-0084.2008.00537.x) | +| [`EP`](epps_pulley_log_normal_criterion.md) | Gaussian-weighted empirical-characteristic-function distance; numerical integration | z0 standardization | [Epps & Pulley (1983)](https://doi.org/10.1093/biomet/70.3.723) | +| [`FILLI`](filliben_log_normal_criterion.md) | Correlation with approximate normal order medians; scipy.stats.probplot | Approximate plotting positions | [Filliben (1975)](https://doi.org/10.1080/00401706.1975.10489279) | +| [`FREEMAN_TUKEY`](freeman_tukey_log_normal_criterion.md) | Power divergence lambda=-1/2, including factor 4 | Fixed null; independent multinomial power divergence; zero-count limits | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`GMG`](gmg_log_normal_criterion.md) | s0 divided by sqrt(pi/2)*mean(abs(x-median(x))) | Directed heavy-tail test; upper tail | [Gel, Miao & Gastwirth (2007)](https://doi.org/10.1016/j.csda.2006.08.022) | +| [`GLB`](glen_leemis_barr_log_normal_criterion.md) | Beta order-CDF transformation and reversed-weight logarithmic sum; binomial-tail identity | Local fitted-normal functional; exact author attribution unconfirmed | [Glen, Leemis & Barr (2001)](https://doi.org/10.1109/24.963129); exact attribution unconfirmed | +| [`HOSKING1`](hosking1_log_normal_criterion.md) | Quadratic ratios of L-moments with trim 0; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`HOSKING2`](hosking2_log_normal_criterion.md) | Quadratic ratios of L-moments with trim 1; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`HOSKING3`](hosking3_log_normal_criterion.md) | Quadratic ratios of L-moments with trim 2; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`HOSKING4`](hosking4_log_normal_criterion.md) | Quadratic ratios of L-moments with trim 3; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`JB`](jarque_bera_log_normal_criterion.md) | n*(skew²/6+excess_kurtosis²/24); scipy.stats.jarque_bera | Asymptotic calibration requires care at small n | [Jarque & Bera (1987)](https://doi.org/10.2307/1403192) | +| [`KL_INT`](kl_integral_log_normal_criterion.md) | n times integral of (D/sigma)^2 on [-5,5] | Truncated numerical functional; original full-text normalization and critical regressions not certified | [Batsidis, Economou and Tzavelas (2016)](https://doi.org/10.1080/00949655.2014.1003138) | +| [`KL_SUP`](kl_supremum_log_normal_criterion.md) | sqrt(n) max |D/sigma| on 1000 equally spaced r in [-5,5] | Truncated numerical functional; original full-text normalization and critical regressions not certified | [Batsidis, Economou and Tzavelas (2016)](https://doi.org/10.1080/00949655.2014.1003138) | +| [`KS_MINUS`](kolmogorov_smirnov_d_minus_log_normal_criterion.md) | max(u_i-(i-1)/n); independent density quadrature | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256); [Lilliefors (1967)](https://doi.org/10.1080/01621459.1967.10482916) (parameter-fitting context) | +| [`KS_PLUS`](kolmogorov_smirnov_d_plus_log_normal_criterion.md) | max(i/n-u_i); independent density quadrature | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256); [Lilliefors (1967)](https://doi.org/10.1080/01621459.1967.10482916) (parameter-fitting context) | +| [`KS`](kolmogorov_smirnov_log_normal_criterion.md) | max(D+,D−) against specified normal CDF; scipy.stats.kstest in all directions | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256) | +| [`KUIPER_CORRECTED`](kuiper_corrected_log_normal_criterion.md) | (sqrt(n)+0.155+0.24/sqrt(n))*(D++D−) | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014)](https://doi.org/10.3103/S875669901401004X) | +| [`KUIPER`](kuiper_log_normal_criterion.md) | D++D− | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0) | +| [`KUIPER_SCALED`](kuiper_scaled_log_normal_criterion.md) | sqrt(n)*(D++D−) | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014)](https://doi.org/10.3103/S875669901401004X) | +| [`KURTOSIS`](kurtosis_log_normal_criterion.md) | Signed Anscombe–Glynn cube-root transform; scipy.stats.kurtosistest | n>=5; approximate calibration, especially below 20 | [Anscombe & Glynn (1983)](https://doi.org/10.1093/biomet/70.1.227) | +| [`LIAO_SHIMOKAWA`](liao_shimokawa_log_normal_criterion.md) | Sum of local EDF maxima weighted by 1/sqrt(u*(1-u)*n) | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Liao & Shimokawa (1999)](https://doi.org/10.1080/00949659908811965) | +| [`LG`](looney_gulledge_log_normal_criterion.md) | Correlation with Blom normal scores; independent correlation matrix | Approximate plotting positions | [Looney & Gulledge (1985)](https://doi.org/10.1080/00031305.1985.10479395) | +| [`MI`](martinez_iglewicz_log_normal_criterion.md) | Classical median-centered scale divided by truncated biweight scale; direct outlier calculation | Positive MAD and nonzero biweight denominator required | [Martinez & Iglewicz (1981)](https://doi.org/10.1093/biomet/68.1.331) | +| [`MODIFIED_LOG_LIKELIHOOD`](modified_log_likelihood_log_normal_criterion.md) | Power divergence lambda=-1; explicit empty-cell limit | Fixed null; independent multinomial power divergence; zero-count limits | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`CHI2_NEYMAN`](neyman_chi2_log_normal_criterion.md) | Power divergence lambda=-2; explicit empty-cell limit | Fixed null; independent multinomial power divergence; zero-count limits | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`QUESENBERRY_MILLER`](quesenberry_miller_log_normal_criterion.md) | Sum of squared n+1 spacings plus adjacent products, with no cyclic product | Fixed-CDF probability integral transform; hand-calculated example | [Quesenberry and Miller (1977)](https://doi.org/10.1080/00949657708810150) | +| [`RJB`](robust_jarque_bera_log_normal_criterion.md) | n*m3²/(6*J^6)+n*(m4/J^4-3)²/64; direct moments and median absolute deviations | Upper tail; J uses the median | [Gel & Gastwirth (2008)](https://doi.org/10.1016/j.econlet.2007.05.022) | +| [`RJ`](ryan_joiner_log_normal_criterion.md) | Normal-score correlation; independent plotting positions for every alpha and averaged tied ranks | Weighted/alpha options change calibration | [Ryan & Joiner (1976), technical report](https://www.additive-net.de/en/component/jdownloads/send/70-support/236-normal-probability-plots-and-tests-for-normality-thomas-a-ryan-jr-bryan-l-joiner) | +| [`SF`](sf_log_normal_criterion.md) | Squared Blom-score correlation | Approximation to expected normal order statistics | [Shapiro & Francia (1972)](https://doi.org/10.1080/01621459.1972.10481232); [Weisberg & Bingham (1975)](https://doi.org/10.1080/00401706.1975.10489283) | +| [`SWRG`](swrg_log_normal_criterion.md) | Normalized score contrast squared; inverse Brownian-bridge quantile covariance calculation | Approximate order-score covariance; lower tail | [Rahman & Govindarajulu (1997)](https://doi.org/10.1080/02664769723828) | +| [`SW`](shapiro_wilk_log_normal_criterion.md) | Royston approximation to Shapiro–Wilk W; SciPy at n=3,4,5,6,8,20,100,1000 | Coefficient approximation, not exact covariance inversion | [Shapiro & Wilk (1965)](https://doi.org/10.1093/biomet/52.3-4.591); [Royston (1995)](https://doi.org/10.2307/2986146) | +| [`SKEW`](skew_log_normal_criterion.md) | Signed D’Agostino transform; scipy.stats.skewtest and exact zero-skew regression | n>=8; both tails | [D’Agostino (1970)](https://doi.org/10.1093/biomet/57.3.679) | +| [`SH`](spiegelhalter_log_normal_criterion.md) | Power combination of standardized range and absolute deviations; direct powers versus log-space code | Documented symmetric-alternative functional; original full text not inspected | [Spiegelhalter (1977)](https://doi.org/10.1093/biomet/64.2.415) | +| [`WATSON`](watson_log_normal_criterion.md) | Centered EDF squared integral | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109) | +| [`ZHANG_ZA`](zhang_a_log_normal_criterion.md) | Reciprocal-rank weighted logarithmic tails | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [`ZHANG_ZC`](zhang_c_log_normal_criterion.md) | Squared log-odds discrepancies with quarter-rank correction | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [`ZHANG_ZK`](zhang_k_log_normal_criterion.md) | Maximum rank-weighted binary log-likelihood discrepancy | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [`ZQ`](zhang_q_log_normal_criterion.md) | log of mean endpoint spacings divided by mean lag-four spacings | n>=8; both tails; exact original text not inspected | [Zhang (1999)](https://doi.org/10.1080/02664769922395) | +| [`ZQS`](zhang_q_star_log_normal_criterion.md) | ZQ applied to the reflected sample; independent spacing expression | n>=8; both tails | [Zhang (1999)](https://doi.org/10.1080/02664769922395) | +| [`ZWA`](zhang_wu_a_log_normal_criterion.md) | 10*Zhang_A-32; density-quadrature CDF and independent rank sum | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Zhang & Wu (2005)](https://doi.org/10.1016/j.csda.2004.05.034) | +| [`ZWC`](zhang_wu_c_log_normal_criterion.md) | Zhang_C log-odds discrepancy; independent rank sum | Fixed-CDF adaptation; independent density/EDF quadrature or rank sum | [Zhang & Wu (2005)](https://doi.org/10.1016/j.csda.2004.05.034) | + +## KL derivation, numerical definition and limits of verification + +Let z_i be centered log observations standardized with ddof=0, K(r) the empirical +log moment-generating function and kappa_k its cumulants. With +D(r)=2*K(r)-r*K'(r), its power series begins + +$$D(r)=-\frac{\kappa_3r^3}{6}-\frac{\kappa_4r^4}{12}+O(r^5).$$ + +The denominator satisfies + +$$\sigma^2(r)=e^{r^2}(r^4-3r^2+4)-(4+r^2) +=r^6\sum_{j=0}^{\infty}\frac{(j+1)^2r^{2j}}{(j+3)!}.$$ + +Thus R(r)=D(r)/sigma(r) has opposite one-sided limits when skewness is nonzero, +but its absolute value and square have continuous extensions. In particular, +R(0+)=-kappa3/sqrt(6), R(0+)²=kappa3²/6. The implementation uses these extensions, +not a denominator floor. Centering cancels algebraically: replacing log data +by log data+c adds cr to K and c to K', cancelling the explicit r*mean term in +the uncentered formula. Positive rescaling cancels through the fitted log SD. + +`KL_SUP` retains the legacy 1000-point equally spaced grid on [-5,5]; this is +only a **grid approximation** to a finite-window supremum. `KL_INT` integrates +n*R(r)² on [-5,5] with adaptive quadrature, split at zero and absolute/relative +tolerance 1e-9. No error bound for omitted infinite tails or missed grid maxima +is asserted. Decimal 70-digit direct expressions independently check both signs +of r, including +/-1e-6, plus the integral; scale tests shift log data by +/-600. +The cumulant expansion is used through order 10 when |r|*max|z|<=0.05. + +[Batsidis, Economou and Tzavelas (2016)](https://doi.org/10.1080/00949655.2014.1003138) +provides the KL size-weighted symmetry motivation. The publisher abstract and +author bibliography were available; the primary full text was not. Consequently +this audit verifies the **documented truncated functionals**, not the exact +paper's domain, normalization, critical-value regressions or reported power. +The old test comments calling two data values “from the article” cannot serve +as independent provenance without a pinpoint source. Those rounded regressions +are retained as compatibility checks, not used as the mathematical proof. + +## Scientific sources and inherited qualifications + +The accessible [Zhang (2002) paper, §§2–3](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf) +provides the fixed-null EDF expressions and likelihood-ratio ranks. The +noncyclic Quesenberry–Miller definition is available in the authors' comparative +study, [Sreedevi and Kattumannil, §4.1](https://arxiv.org/html/2106.06368v1#S4.SS1). +Original bibliographic links appear in every page. A bibliography entry or an +accessible abstract is not claimed to be a full-text formula check. + +For the 32 wrappers, the detailed scientific-source audit and independent +functional constructions are in the [normality report](../normality/mathematical-validation.md). +Their numerical verification was rerun; inherited limitations remain: + +- **Hosking 1–4:** L-moments agree with exhaustive order-statistic combinations. + The three local rows of centering/variance constants have no established + primary-source calibration here and do not shrink as an asymptotic variance + sequence. They define local discrepancies; simulate at the actual n. +- **GLB:** the fitted beta/order-probability transformation and reversed log + weights agree with the documented local expression. Equality to the original + Glen–Leemis–Barr test remains unconfirmed; do not use its tables by name alone. +- **Coin, SW, SF, SWRG, correlations and spacings:** normal order scores or + their covariance are approximated. Coin retains its 4<=n<=2000 restriction. + These are not exact finite-sample normal covariance inversions. +- **Hermite/moment and directed shape tests:** finite-order moments and directed + alternatives do not guarantee power against every nonnormal log distribution. +- **Zhang–Wu variants:** historical normalization is retained; the log-normal + versions use a fixed CDF rather than fitted normality probabilities. +- **Liao–Shimokawa:** a fixed-log-normal application of the general EDF functional; + the original extreme-value-family calibration is not transferred. + +## Numerical checks and reproducibility + +Result: **1576 tests passed** with ordinary imports. Ruff and stub freshness +checks passed. MkDocs built successfully; its existing broken-link warnings +concern other families, not the log-normal pages. This count includes the +normality reference suite and hypothesis-generator checks listed below. + +The focused checks exercise all 55 public statistics and both coordinate systems. +They include independent normal-density and EDF quadrature, rank sums, SciPy +multinomial power divergences, hand-calculated spacing sums, 70-digit KL +expressions, normality functional references, log-affine invariance, invalid +samples, unchanged input, hypothesis preservation and composite-null sampling. + +Typical checked tolerances are rel=2e-9, abs=2e-10 for EDF identities; +rel=3e-8, abs=2e-9 for log-transform composition at large log offsets; +rel=2e-7, abs=2e-9 for KL pointwise comparisons, and rel=2e-8 for KL integration. +These bound the tested cases, not a global error or exact significance level. +No Monte Carlo level/power study was performed. In particular, the legacy KL +threshold regressions and unresolved historical calibrations are not certified. + +Run from the repository root using ordinary package imports (no isolation shim): + +```sh +PYTHONPATH=src .venv/bin/python -m pytest \ + tests/distributions/test_log_normal.py \ + tests/distributions/test_log_normal_parameters.py \ + tests/distributions/test_log_normal_mathematical_validation.py \ + tests/distributions/test_log_normal_documentation.py \ + tests/statistics/test_log_normal_factory.py \ + tests/distributions/test_normal_correctness.py \ + tests/distributions/test_normal_mathematical_validation.py \ + tests/utils/test_hypothesis_generator.py -q +.venv/bin/python scripts/generate_log_normal_stub.py --check +.venv/bin/python -m mkdocs build --site-dir /tmp/pysatl-log-normal-audit +``` + +## Documentation coverage + +The catalog, report, navigation and 55 individual pages are checked against +runtime exports. Every page names its exact Python class and code, supplies an +executable example and scientific links, and links back to this report. Python +examples and public-class docstring examples execute in tests; local Markdown +links are checked. `log_normal/__init__.pyi` is regenerated and checked with `--check`. + +## Numba optimization verification + +Optimization checked on 2026-10-23. All 55 public criteria reach numerical +kernels compiled with `@jit(nopython=True, cache=True)`. EDF, frequency and +normality wrappers reuse their existing compiled kernels. Quesenberry–Miller +now compiles sorting and the spacing sum; KL compiles cumulant coefficients, +the stable ratio, the entire 1000-point supremum loop and the squared integrand. +SciPy retains CDF/log-tail evaluation and adaptive quadrature with the same +window, tolerance and split at zero. No fast-math reassociation is enabled. +The public call is therefore not claimed to be wholly compiled. + +All implementation helpers, including validation, class generation and factory +adapters, are methods inside classes in `log_normal/log_normal_statistics.py`. +There are no module-level function definitions. The public import path and +statistic names are unchanged; the package stub describes the class methods. + +The 117 tests in `tests/distributions/test_log_normal_numba.py` verify actual +nopython signatures, disk-cache configuration, compiled/Python kernel agreement, +unchanged input and execution through every public criterion on continuous and +tied samples. Together with the mathematical, documentation and generator suites +listed above, **1693 tests passed**. Ruff and stub freshness checks also passed. + +A local comparison against the saved pre-optimization implementation used +n=200, seed 123 and the minimum of three batches of ten warmed public calls. +All 55 values agreed (`rtol=2e-8`, `atol=2e-9`). Measured results for the changed +numerical paths were: + +| Statistic | Before, microseconds | After, microseconds | Speedup | +| --- | ---: | ---: | ---: | +| KL supremum | 42886.4 | 1491.3 | 28.76x | +| KL integral | 6543.8 | 619.8 | 10.56x | +| Quesenberry–Miller | 38.0 | 30.2 | 1.26x | + +These are local warmed timings, not performance guarantees. Existing shared +kernels were already compiled. First-call timings include compilation or disk +cache loading and are reported separately by the benchmark: + +```sh +PYTHONPATH=src .venv/bin/python benchmarks/benchmark_log_normal_pipeline.py --size 200 --number 10 +PYTHONPATH=src .venv/bin/python -m pytest tests/distributions/test_log_normal_numba.py -q +``` + +The benchmark's optional `--baseline /path/to/saved/log_normal.py` compares +against a saved prior module and checks values before reporting speedups. diff --git a/docs/criteria/goodness-of-fit/log-normal/modified_log_likelihood_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/modified_log_likelihood_log_normal_criterion.md new file mode 100644 index 00000000..87a0d904 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/modified_log_likelihood_log_normal_criterion.md @@ -0,0 +1,64 @@ +# Modified log likelihood for log-normal data + +**Class:** `ModifiedLogLikelihoodLogNormalGofStatistic` + +**Code:** `MODIFIED_LOG_LIKELIHOOD_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic and binning + +Modified log likelihood: 2 * sum(expected * log(expected / observed)). + +Returns positive infinity if any observed count is zero. + +## References +Cressie, N. and Read, T. R. C. (1984). Multinomial Goodness-of-Fit Tests. +JRSS B, 46(3), 440-464; power divergence with lambda = -1. +https://doi.org/10.1111/j.2517-6161.1984.tb01318.x + +The constructor accepts `binning: BinningStrategy`; its default is +`EqualProbabilityBins()`. Bins use the fixed log-normal distribution in the +original sample units. Define observed counts O_j and expected counts +E_j = n * P(X in cell j). The zero-count limits are part of the definition; +Neyman and modified log-likelihood can return positive infinity when O_j=0 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic and binning + +Neyman modified chi-square: sum((observed - expected)**2 / observed). + +Returns positive infinity if any observed count is zero. + +## References +Cressie, N. and Read, T. R. C. (1984). Multinomial Goodness-of-Fit Tests. +JRSS B, 46(3), 440-464; power divergence with lambda = -2. +https://doi.org/10.1111/j.2517-6161.1984.tb01318.x + +The constructor accepts `binning: BinningStrategy`; its default is +`EqualProbabilityBins()`. Bins use the fixed log-normal distribution in the +original sample units. Define observed counts O_j and expected counts +E_j = n * P(X in cell j). The zero-count limits are part of the definition; +Neyman and modified log-likelihood can return positive infinity when O_j=0 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. -test_statistic = QuesenberryMillerLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Statistic -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +Set $u_i=F_{\mu,s}(x_{(i)})$, $u_0=0$, $u_{n+1}=1$ and +$D_i=u_i-u_{i-1}$ for $i=1,\ldots,n+1$. Then -`rvs` - array-like sample data passed to `execute_statistic`. +$$Q=\sum_{i=1}^{n+1}D_i^2+\sum_{i=1}^{n}D_iD_{i+1}.$$ -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +There is no cyclic term $D_{n+1}D_1$. All n+1 spacings, including both +boundary gaps, are present. Uniform quantile samples provide an exact +hand-calculated reference. The null CDF must be specified in advance. -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +## References -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +- [Quesenberry and Miller (1977), Power studies of some tests for uniformity](https://doi.org/10.1080/00949657708810150). +- The explicit noncyclic formula is also given in the authors' comparative study, + [Sreedevi and Kattumannil, §4.1](https://arxiv.org/html/2106.06368v1#S4.SS1). -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( QuesenberryMillerLogNormalGofStatistic, ) - -test_statistic = QuesenberryMillerLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = QuesenberryMillerLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/robust_jarque_bera_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/robust_jarque_bera_log_normal_criterion.md index d422809c..b9681c52 100644 --- a/docs/criteria/goodness-of-fit/log-normal/robust_jarque_bera_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/robust_jarque_bera_log_normal_criterion.md @@ -1,60 +1,86 @@ -# Robust Jarque-Bera test for log-normal distribution +# Robust Jarque-Bera test for log-normal data -## Description -Performs Robust Jarque-Bera goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `RobustJarqueBeraLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `RJB_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped robust Jarque-Bera normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - RobustJarqueBeraLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = RobustJarqueBeraLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `RobustJarqueBeraNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/robust_jarque_bera_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Let J=sqrt(pi/2)*mean(abs(x-median(x))). Return +n*(m3/J**3)**2/6 + n*(m4/J**4-3)**2/64. +Moments are centered at the sample mean, whereas J uses the median. +The reference identifies this robust-scale modification; small-sample +chi-square calibration is not justified. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Gel, Y. R. and Gastwirth, J. L. (2008). + A robust modification of the Jarque-Bera test of normality. + Economics Letters, 99(1), 30-32. + https://doi.org/10.1016/j.econlet.2007.05.022 + + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( RobustJarqueBeraLogNormalGofStatistic, ) - -test_statistic = RobustJarqueBeraLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = RobustJarqueBeraLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/ryan_joiner_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/ryan_joiner_log_normal_criterion.md index afb4bb76..e5b401c5 100644 --- a/docs/criteria/goodness-of-fit/log-normal/ryan_joiner_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/ryan_joiner_log_normal_criterion.md @@ -1,60 +1,86 @@ -# Ryan-Joiner test for log-normal distribution +# Ryan-Joiner test for log-normal data -## Description -Performs Ryan-Joiner goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `RyanJoinerLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `RJ_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Ryan-Joiner normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - RyanJoinerLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = RyanJoinerLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `RyanJoinerNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/ryan_joiner_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return corr(x_(i), Phi**-1(p_i)), p_i=(i-alpha)/(n+1-2*alpha). +cte_alpha selects alpha=0, 3/8, or 1/2. If weighted=True, replace +positions of tied observations by their group mean before taking +normal quantiles. This tie convention and nondefault positions need +separate calibration; they are not fixed distribution parameters. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Ryan, T. A., Jr. and Joiner, B. L. (1976). Normal Probability + Plots and Tests for Normality. Technical report, Statistics + Department, The Pennsylvania State University. Original report: + https://www.additive-net.de/en/component/jdownloads/send/70-support/236-normal-probability-plots-and-tests-for-normality-thomas-a-ryan-jr-bryan-l-joiner + + +## Rejection and calibration + +Rejection tail: **left**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( RyanJoinerLogNormalGofStatistic, ) - -test_statistic = RyanJoinerLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = RyanJoinerLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/sf_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/sf_log_normal_criterion.md index d0b34422..cfcfb83c 100644 --- a/docs/criteria/goodness-of-fit/log-normal/sf_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/sf_log_normal_criterion.md @@ -1,60 +1,88 @@ -# SF test for log-normal distribution +# SF test for log-normal data -## Description -Performs SF goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `SFLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `SF_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped SF normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SFLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = SFLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `SFNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/sf_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return corr(x_(i), Phi**-1((i-3/8)/(n+1/4)))**2. +This Shapiro-Francia approximation uses Blom scores in place of +exact expected normal order statistics. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Shapiro, S. S. and Francia, R. S. (1972). An Approximate + Analysis of Variance Test for Normality. Journal of the American + Statistical Association, 67(337), 215-216. + https://doi.org/10.1080/01621459.1972.10481232 +[2] Weisberg, S. and Bingham, C. (1975). An Approximate Analysis of + Variance Test for Non-Normality Suitable for Machine Calculation. + Technometrics, 17(1), 133-134. + https://doi.org/10.1080/00401706.1975.10489283 + + +## Rejection and calibration + +Rejection tail: **left**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( SFLogNormalGofStatistic, ) - -test_statistic = SFLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = SFLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/shapiro_wilk_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/shapiro_wilk_log_normal_criterion.md index 559d3709..743dca56 100644 --- a/docs/criteria/goodness-of-fit/log-normal/shapiro_wilk_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/shapiro_wilk_log_normal_criterion.md @@ -1,60 +1,87 @@ -# Shapiro-Wilk test for log-normal distribution +# Shapiro-Wilk test for log-normal data -## Description -Performs Shapiro-Wilk goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `ShapiroWilkLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `SW_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Shapiro-Wilk normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ShapiroWilkLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = ShapiroWilkLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `ShapiroWilkNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/shapiro_wilk_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +W = (sum(a_i*x_(i)))**2 / sum((x-mean(x))**2). +The normalized symmetric weights use the Royston polynomial +approximation, with the exact three-observation weights. This is a +weight approximation to Shapiro-Wilk, not exact covariance inversion. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Shapiro, S. S. and Wilk, M. B. (1965). An analysis of variance + test for normality (complete samples). Biometrika, 52(3-4), 591-611. + https://doi.org/10.1093/biomet/52.3-4.591 +[2] Royston, P. (1995). Remark AS R94: A Remark on Algorithm AS 181: + The W-test for Normality. Applied Statistics, 44(4), 547-551. + https://doi.org/10.2307/2986146 + + +## Rejection and calibration + +Rejection tail: **left**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( ShapiroWilkLogNormalGofStatistic, ) - -test_statistic = ShapiroWilkLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = ShapiroWilkLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/skew_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/skew_log_normal_criterion.md index 928c22cf..d23835bc 100644 --- a/docs/criteria/goodness-of-fit/log-normal/skew_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/skew_log_normal_criterion.md @@ -1,60 +1,84 @@ -# Skewness test for log-normal distribution +# Skewness test for log-normal data -## Description -Performs Skewness goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `SkewLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `SKEW_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped skewness normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SkewLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = SkewLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `SkewNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/skew_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +Return the signed D'Agostino transform delta*asinh(y/alpha) of +g1=m3/m2**1.5, with the sample-size coefficients in skew_test. +In particular, exactly zero sample skewness maps to zero. This tests +skewness departures in either direction; it is not an omnibus test. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] D'Agostino, R. B. (1970). Transformation to normality of the null + distribution of g1. Biometrika, 57(3), 679-681. + https://doi.org/10.1093/biomet/57.3.679 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( SkewLogNormalGofStatistic, ) - -test_statistic = SkewLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = SkewLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/spiegelhalter_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/spiegelhalter_log_normal_criterion.md index 507cd8ec..393beab8 100644 --- a/docs/criteria/goodness-of-fit/log-normal/spiegelhalter_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/spiegelhalter_log_normal_criterion.md @@ -1,60 +1,89 @@ -# Spiegelhalter test for log-normal distribution +# Spiegelhalter test for log-normal data -## Description -Performs Spiegelhalter goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `SpiegelhalterLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `SH_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Spiegelhalter normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SpiegelhalterLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = SpiegelhalterLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +## Logarithmic reduction -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +The implementation computes `SpiegelhalterNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Underlying normality definition -`rvs` - array-like sample data passed to `execute_statistic`. +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/spiegelhalter_normality_criterion.md). -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Author(s) -Anton Dorosev, Alexey Mironov +Let U=(max(x)-min(x))/s1, G=sum(abs(x-mean(x)))/ +(s1*sqrt(n*(n-1))), and c_n=Gamma(n+1)**(1/(n-1))/(2*n). +Return ((c_n*U)**(-(n-1))+G**(-(n-1)))**(1/(n-1)). +Log-gamma and logaddexp evaluate this expression without overflowing. +Both critical tails are retained; the full primary formula and +its tail convention could not be independently checked in this review. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Spiegelhalter, D. J. (1977). "A test for normality against + symmetric alternatives." Biometrika, 64(2), 415-418. + https://doi.org/10.1093/biomet/64.2.415 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( SpiegelhalterLogNormalGofStatistic, ) - -test_statistic = SpiegelhalterLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = SpiegelhalterLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/swrg_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/swrg_log_normal_criterion.md index fb5bbddd..4f666f39 100644 --- a/docs/criteria/goodness-of-fit/log-normal/swrg_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/swrg_log_normal_criterion.md @@ -1,60 +1,86 @@ -# SWRG test for log-normal distribution +# SWRG test for log-normal data -## Description -Performs SWRG goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `SWRGLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `SWRG_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped SWRG normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SWRGLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = SWRGLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` - -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +## Logarithmic reduction -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +The implementation computes `SWRGNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`rvs` - array-like sample data passed to `execute_statistic`. +## Underlying normality definition -## Details -For dynamically generated log-normal tests, the implementation transforms observations with +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/swrg_normality_criterion.md). -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Author(s) -Anton Dorosev, Alexey Mironov +For m_i=Phi**-1(i/(n+1)), f_i=phi(m_i), form weights +a*_i=-(n+1)*(n+2)*f_i*(m_(i-1)*f_(i-1)-2*m_i*f_i ++m_(i+1)*f_(i+1)), taking missing endpoint terms as zero. +Normalize a=a*/sqrt(sum(a* **2)); return +(sum(a_i*x_(i)))**2/sum((x-mean(x))**2). Small W_RG rejects. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Rahman, M. M. and Govindarajulu, Z. (1997). + A modification of the test of Shapiro and Wilk for normality. + Journal of Applied Statistics, 24(2), 219-236. + https://doi.org/10.1080/02664769723828 + + +## Rejection and calibration + +Rejection tail: **left**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( SWRGLogNormalGofStatistic, ) - -test_statistic = SWRGLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = SWRGLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/watson_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/watson_log_normal_criterion.md new file mode 100644 index 00000000..5a4839ce --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/watson_log_normal_criterion.md @@ -0,0 +1,58 @@ +# Watson for log-normal data + +**Class:** `WatsonLogNormalGofStatistic` + +**Code:** `WATSON_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Watson U² statistic for CDF values of a sorted sample. + +Returns W²-n*(mean(u)-1/2)**2, evaluated as a centered sum of squares +plus 1/(12*n) to avoid cancellation. No finite-sample correction is used. + +## References +Lemeshko et al. (2014), Eq. (6). +https://doi.org/10.3103/S875669901401004X +Watson (1961), https://doi.org/10.1093/biomet/48.1-2.109; sorted CDF input. + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + WatsonLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = WatsonLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_a_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_a_log_normal_criterion.md new file mode 100644 index 00000000..0820aa40 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_a_log_normal_criterion.md @@ -0,0 +1,58 @@ +# Zhang A for log-normal data + +**Class:** `ZhangALogNormalGofStatistic` + +**Code:** `ZHANG_ZA_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Zhang Z_A statistic for nonempty, sorted CDF values in [0, 1]. + +Endpoints give positive infinity. Logarithms are evaluated separately +to avoid overflow in tail probability ratios. + +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Eq. (3.2). +https://doi.org/10.1111/1467-9868.00337. + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + ZhangALogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = ZhangALogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_c_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_c_log_normal_criterion.md new file mode 100644 index 00000000..a879a9be --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_c_log_normal_criterion.md @@ -0,0 +1,58 @@ +# Zhang C for log-normal data + +**Class:** `ZhangCLogNormalGofStatistic` + +**Code:** `ZHANG_ZC_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Zhang Z_C statistic for nonempty, sorted CDF values in [0, 1]. + +Endpoints give positive infinity. Logarithms are evaluated separately +to avoid overflow in tail probability ratios. + +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Eq. (3.3). +https://doi.org/10.1111/1467-9868.00337. + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + ZhangCLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = ZhangCLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_k_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_k_log_normal_criterion.md new file mode 100644 index 00000000..7e0b37d7 --- /dev/null +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_k_log_normal_criterion.md @@ -0,0 +1,58 @@ +# Zhang K for log-normal data + +**Class:** `ZhangKLogNormalGofStatistic` + +**Code:** `ZHANG_ZK_LOGNORMAL_GOODNESS_OF_FIT` + +## Hypothesis and inputs + +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. + +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. + +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. + +Zhang Z_K statistic for nonempty, sorted CDF values in [0, 1]. + +Endpoints give positive infinity. Logarithms are evaluated separately +to avoid overflow in tail probability ratios. + +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Eq. (3.1). +https://doi.org/10.1111/1467-9868.00337. + +## Rejection and calibration + +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. + +## Examples + +```python +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( + ZhangKLogNormalGofStatistic, +) + +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = ZhangKLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_q_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_q_log_normal_criterion.md index 501c537e..0c7333b2 100644 --- a/docs/criteria/goodness-of-fit/log-normal/zhang_q_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_q_log_normal_criterion.md @@ -1,60 +1,91 @@ -# Zhang Q test for log-normal distribution +# Zhang Q test for log-normal data -## Description -Performs Zhang Q goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `ZhangQLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `ZQ_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Zhang Q normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangQLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = ZhangQLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +## Logarithmic reduction -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +The implementation computes `ZhangQNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Underlying normality definition -`rvs` - array-like sample data passed to `execute_statistic`. +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/zhang_q_normality_criterion.md). -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Author(s) -Anton Dorosev, Alexey Mironov +For u_i=Phi**-1((i-3/8)/(n+1/4)), set +q1=mean_{i=2..n}((x_(i)-x_(1))/(u_i-u_1)), +q2=mean_{i=1..n-4}((x_(i+4)-x_(i))/(u_(i+4)-u_i)). +Return log(q1)-log(q2). The four-spacing construction and Blom +approximation are explicit implementation choices. Both contrasts +must be positive. Both critical tails are used for the signed log ratio; +this is the Q component, not a combined Q/Q* p-value procedure. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Zhang, P. (1999). + Omnibus test of normality using the Q statistic. + Journal of Applied Statistics, 26(4), 519-528. + https://doi.org/10.1080/02664769922395 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( ZhangQLogNormalGofStatistic, ) - -test_statistic = ZhangQLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = ZhangQLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_q_star_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_q_star_log_normal_criterion.md index 666fe4cc..ed7a0ef1 100644 --- a/docs/criteria/goodness-of-fit/log-normal/zhang_q_star_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_q_star_log_normal_criterion.md @@ -1,60 +1,89 @@ -# Zhang Q-star test for log-normal distribution +# Zhang Q-star test for log-normal data -## Description -Performs Zhang Q-star goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `ZhangQStarLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `ZQS_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Zhang Q-star normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangQStarLogNormalGofStatistic, -) +This is a **log-normal family/shape** statistic: log(X) is normal with unknown +location and positive scale. Use `LogNormalDistributionDescriptor.DEFAULT.parse({})`. +An empty `SHAPE_SCALE` schema is also accepted. All observations must be finite, +real, strictly positive and one-dimensional. Active masks and undefined +constant-sample contrasts raise `ValueError`; minimum sizes are specified below. +For compatibility, fully specified `mu, s` or `s, scale` coordinates are also +accepted and preserved by `hypothesis()`. They do **not** enter this shape +statistic: it cannot detect a wrong location/scale within the log-normal family. +Use a fixed-CDF EDF or frequency criterion when those particular values are +part of the hypothesis. Partial parameter sets are rejected. -test_statistic = ZhangQStarLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +## Logarithmic reduction -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +The implementation computes `ZhangQStarNormalityGofStatistic` on `y = log(rvs)` with an empty +normal-family hypothesis. Thus its formula, sample-size limits, normalization +and rejection tail are exactly those of the normality statistic at its default +settings. Constructor-specific normality options are not exposed by this wrapper. +The identity was checked on normal, nonnormal and tied logarithmic samples and +under transformations `X -> exp(a) * X**b`, b > 0. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +## Underlying normality definition -`rvs` - array-like sample data passed to `execute_statistic`. +**In this section, x denotes y = log(X), not the original positive sample.** +The normal-family hypothesis and dispersion conventions below concern these +log observations. See also the [normality source page](../normality/zhang_q_star_normality_criterion.md). -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Author(s) -Anton Dorosev, Alexey Mironov +Return Zhang Q evaluated on the reflected sample -x, using +u_i=Phi**-1((i-3/8)/(n+1/4)), the mean spacing from the minimum +for q1 and mean four-spacing for q2; return log(q1)-log(q2). +Both contrasts must be positive. Both tails of the signed log ratio +are used. This is a reflected component, not combined Q/Q* inference. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. + +[1] Zhang, P. (1999). + Omnibus test of normality using the Q statistic. + Journal of Applied Statistics, 26(4), 519-528. + https://doi.org/10.1080/02664769922395 + + +## Rejection and calibration + +Rejection tail: **two_tailed**. A statistic value alone is not a p-value. +For the composite null, simulation can use log-normal mu=0, s=1 because +log-location and log-scale are removed by the statistic. Every replicate must +call `execute_statistic` again. This does not make every directed shape test +omnibus. Signed two-tail tests require both null quantiles, without assuming +symmetry. Legacy attribution qualifications carry over from normality. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( ZhangQStarLogNormalGofStatistic, ) - -test_statistic = ZhangQStarLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({}) +statistic = ZhangQStarLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_wu_a_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_wu_a_log_normal_criterion.md index 44a614a5..43b55e9e 100644 --- a/docs/criteria/goodness-of-fit/log-normal/zhang_wu_a_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_wu_a_log_normal_criterion.md @@ -1,60 +1,63 @@ -# Zhang-Wu A test for log-normal distribution +# Zhang-Wu A test for log-normal data -## Description -Performs Zhang-Wu A goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `ZhangWuALogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `ZWA_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Zhang-Wu A normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangWuALogNormalGofStatistic, -) +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. -test_statistic = ZhangWuALogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +Zhang Z_A statistic for nonempty, sorted CDF values in [0, 1]. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +Endpoints give positive infinity. Logarithms are evaluated separately +to avoid overflow in tail probability ratios. -`rvs` - array-like sample data passed to `execute_statistic`. +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Eq. (3.2). +https://doi.org/10.1111/1467-9868.00337. -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +The historical Zhang–Wu variant requires n >= 4. It returns **10 * Z_A - 32**, not raw Z_A. This is a fixed-CDF adaptation; fitted-normal critical values do not apply. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Scientific context: [Zhang and Wu (2005)](https://doi.org/10.1016/j.csda.2004.05.034). -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( ZhangWuALogNormalGofStatistic, ) - -test_statistic = ZhangWuALogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = ZhangWuALogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/log-normal/zhang_wu_c_log_normal_criterion.md b/docs/criteria/goodness-of-fit/log-normal/zhang_wu_c_log_normal_criterion.md index 35d28985..277ae4a8 100644 --- a/docs/criteria/goodness-of-fit/log-normal/zhang_wu_c_log_normal_criterion.md +++ b/docs/criteria/goodness-of-fit/log-normal/zhang_wu_c_log_normal_criterion.md @@ -1,60 +1,63 @@ -# Zhang-Wu C test for log-normal distribution +# Zhang-Wu C test for log-normal data -## Description -Performs Zhang-Wu C goodness-of-fit test for the hypothesis that the sample comes from a log-normal distribution. -The implementation uses positive observations and either evaluates the log-normal model directly or applies a normality statistic to standardized logarithms. +**Class:** `ZhangWuCLogNormalGofStatistic` -Hypothesis of Log-Normal Distribution -The null hypothesis is that the data comes from a log-normal distribution with positive shape parameter `s` and positive scale parameter `scale`. -Observations passed to `execute_statistic` should be positive; tests that receive non-positive observations may return `inf`. +**Code:** `ZWC_LOGNORMAL_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the wrapped Zhang-Wu C normality statistic applied to standardized log observations. +## Hypothesis and inputs -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangWuCLogNormalGofStatistic, -) +Both parameters must be supplied before observing the sample: `mu` is the +mean of log(X), `s > 0` is its standard deviation. The alternative coordinates +are `s` and `scale = exp(mu)`, the **median**, not the mean of X. +Use `LOG_LOCATION_SCALE.parse({"mu": ..., "s": ...})` or +`SHAPE_SCALE.parse({"s": ..., "scale": ...})`. Partial and empty hypotheses +are rejected. No parameters are fitted to the sample. +The sample must be nonempty, finite, real and one-dimensional; masked values +are rejected. Ties are permitted. EDF/spacing formulas use the null CDF, which +is zero at nonpositive observations; finite penalties are possible. This is +not the same policy as logarithmic family statistics, which reject such input. -test_statistic = ZhangWuCLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) -``` +## Statistic + +Set $u_i=\Phi((\log x_{(i)}-\mu)/s)$ for positive observations. +The following general EDF definition is evaluated at these fixed-null probabilities. -## Arguments -`s` - positive shape parameter of the log-normal distribution. Default value is `1`. +Zhang Z_C statistic for nonempty, sorted CDF values in [0, 1]. -`scale` - positive scale parameter of the log-normal distribution. Default value is `1`. +Endpoints give positive infinity. Logarithms are evaluated separately +to avoid overflow in tail probability ratios. -`rvs` - array-like sample data passed to `execute_statistic`. +## References +Zhang, J. (2002). Powerful goodness-of-fit tests based on the likelihood +ratio. JRSS B, 64(2), 281-294, Eq. (3.3). +https://doi.org/10.1111/1467-9868.00337. -## Details -For dynamically generated log-normal tests, the implementation transforms observations with -$$ Z_i = \frac{\log X_i - \log(scale)}{s} $$ +The historical Zhang–Wu variant requires n >= 4. It returns the same functional as Zhang C. This is a fixed-CDF adaptation; fitted-normal critical values do not apply. -and applies the corresponding normality statistic to the standardized values. Explicit EDF and KL-based implementations use the formulas in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Scientific context: [Zhang and Wu (2005)](https://doi.org/10.1016/j.csda.2004.05.034). -## Author(s) -Anton Dorosev, Alexey Mironov +## Rejection and calibration -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.log_normal`. +Rejection tail: **right**. A statistic value alone is not a p-value. +Use the fixed null and the same sample size, settings and binning for calibration. +Do not substitute fitted-normality tables. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +import numpy as np +from pysatl_criterion.distribution import LogNormalDistributionDescriptor as LogNormal +from pysatl_criterion.statistics.goodness_of_fit.continuous.log_normal import ( ZhangWuCLogNormalGofStatistic, ) - -test_statistic = ZhangWuCLogNormalGofStatistic(s=1, scale=1) -statistic_result = test_statistic.execute_statistic( - [0.42, 0.58, 0.76, 0.93, 1.12, 1.35, 1.61, 1.92, 2.28, 2.71, 3.23, 3.84] -) -print(statistic_result) +parameters = LogNormal.DEFAULT.parse({"mu": 0.4, "s": 0.8}) +statistic = ZhangWuCLogNormalGofStatistic(parameters) +sample = np.exp([-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1]) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/anderson_darling_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/anderson_darling_normality_criterion.md index cf82d031..a054432a 100644 --- a/docs/criteria/goodness-of-fit/normality/anderson_darling_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/anderson_darling_normality_criterion.md @@ -1,55 +1,59 @@ # Anderson-Darling test for normality -## Description -Performs the Anderson-Darling goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `AndersonDarlingNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `AD_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on ordered standardized observations with the log CDF and log survival function of the normal distribution. +Anderson-Darling statistic for the normal location-scale family. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - AndersonDarlingNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = AndersonDarlingNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Anderson-Darling statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +A2 = -n - sum((2*i-1)*(log(Phi(z_(i))) + +log(1-Phi(z_(n+1-i)))))/n, where z=(x-mean(x))/s1. +This is the unadjusted fitted-normal statistic. Log-CDF and log-survival +functions avoid rounding probabilities to zero or one. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Anderson, T. W. and Darling, D. A. (1954). A Test of Goodness + of Fit. Journal of the American Statistical Association, 49(268), + 765-769. https://doi.org/10.1080/01621459.1954.10501232 +[2] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit + Statistics with Unknown Parameters. The Annals of Statistics, + 4(2), 357-369. https://doi.org/10.1214/aos/1176343411 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( AndersonDarlingNormalityGofStatistic, ) - -test_statistic = AndersonDarlingNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = AndersonDarlingNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/bhs_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/bhs_normality_criterion.md index 486b5d9b..8b990e38 100644 --- a/docs/criteria/goodness-of-fit/normality/bhs_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/bhs_normality_criterion.md @@ -1,55 +1,60 @@ # BHS test for normality -## Description -Performs the BHS goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. - -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. - -Test Statistic -The statistic is based on a robust medcouple-based skewness statistic. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BHSNormalityGofStatistic, -) - - -test_statistic = BHSNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. - -`var` - reference normal variance. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the BHS statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +**Class:** `BHSNormalityGofStatistic` + +**Code:** `BHS_NORMALITY_GOODNESS_OF_FIT` + +Brys-Hubert-Struyf MC-LR statistic for the normal family. + +## Methods + +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. + +## Notes + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Return n*v.T*V**-1*v with v=(MC, LMC-0.198828, RMC-0.198828), +V=[[1.24581,0.322918,-0.322918],[0.322918,2.62068,-0.0123455], +[-0.322918,-0.0123455,2.62068]]. LMC=-MC(xmedian(x)); median observations belong to neither half. +MC is the median of (upper+lower-2*median)/(upper-lower) over +lower<=median<=upper, with antisymmetric rank values for zero ties. +At least two observations must remain in each strict half. Constant +halves have MC=0. The exact kernel median uses O(n**2) time and +memory, unlike the fast selection algorithm in the paper. Constants +agree with the rounded normal row in Table 1; simulate for finite n. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Brys, G., Hubert, M., and Struyf, A. (2008). "Goodness-of-fit tests + based on a robust measure of skewness." Computational Statistics, + 23, 429-442. https://doi.org/10.1007/s00180-007-0083-7 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BHSNormalityGofStatistic, -) - -test_statistic = BHSNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import BHSNormalityGofStatistic + +statistic = BHSNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/bonett_seier_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/bonett_seier_normality_criterion.md index e0d6fa8b..3b3b9989 100644 --- a/docs/criteria/goodness-of-fit/normality/bonett_seier_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/bonett_seier_normality_criterion.md @@ -1,55 +1,60 @@ # Bonett-Seier test for normality -## Description -Performs the Bonett-Seier goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `BonettSeierNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `BS_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a transformed measure comparing standard deviation and mean absolute deviation. +Bonett-Seier statistic based on a modified Geary kurtosis measure. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BonettSeierNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = BonettSeierNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. +The factor sqrt(n+2), the population sample variance (ddof=0), and the +two-sided rejection rule agree with equations (5)–(6) of the [original +article](https://sci2s.ugr.es/keel/pdf/specific/articulo/Normalidad4.pdf). -## Details -The implementation evaluates the Bonett-Seier statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Let d=mean(abs(x-mean(x))) and omega=13.29*log(s0/d). +Return sqrt(n+2)*(omega-3)/3.54, a signed kurtosis transform. +The constants are rounded approximations; use finite-sample simulation. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Bonett, D. G. and Seier, E. (2002). + A test of normality with high uniform power. + Computational Statistics & Data Analysis, 40(3), 435-445. + https://doi.org/10.1016/S0167-9473(02)00074-9 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( BonettSeierNormalityGofStatistic, ) - -test_statistic = BonettSeierNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = BonettSeierNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/bontemps_meddahi1_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/bontemps_meddahi1_normality_criterion.md index b45cb231..c69b1d17 100644 --- a/docs/criteria/goodness-of-fit/normality/bontemps_meddahi1_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/bontemps_meddahi1_normality_criterion.md @@ -1,55 +1,57 @@ # Bontemps-Meddahi1 test for normality -## Description -Performs the Bontemps-Meddahi1 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `BontempsMeddahi1NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `BM1_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on Hermite-polynomial components of standardized observations up to orders three and four. +Bontemps-Meddahi normality statistic using Hermite orders 3 and 4. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BontempsMeddahi1NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = BontempsMeddahi1NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Bontemps-Meddahi1 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Let z=(x-mean(x))/s1 and h_j=He_j/sqrt(j!), where He_j +are probabilists' Hermite polynomials. Return +(sum(h_3(z))**2+sum(h_4(z))**2)/n. +The sample-variance convention ddof=1 is part of this implementation. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Bontemps, C. and Meddahi, N. (2005). + Testing normality: a GMM approach. + Journal of Econometrics, 124(1), 149-186. + https://doi.org/10.1016/j.jeconom.2004.02.014 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( BontempsMeddahi1NormalityGofStatistic, ) - -test_statistic = BontempsMeddahi1NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = BontempsMeddahi1NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/bontemps_meddahi2_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/bontemps_meddahi2_normality_criterion.md index 4f23e678..1bf05fcb 100644 --- a/docs/criteria/goodness-of-fit/normality/bontemps_meddahi2_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/bontemps_meddahi2_normality_criterion.md @@ -1,55 +1,57 @@ # Bontemps-Meddahi2 test for normality -## Description -Performs the Bontemps-Meddahi2 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `BontempsMeddahi2NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `BM2_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on Hermite-polynomial components of standardized observations up to order six. +Bontemps-Meddahi normality statistic using Hermite orders 3 through 6. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - BontempsMeddahi2NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = BontempsMeddahi2NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Bontemps-Meddahi2 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Let z=(x-mean(x))/s1 and h_j=He_j/sqrt(j!), where He_j +are probabilists' Hermite polynomials. Return +sum_j(sum_i(h_j(z_i))**2)/n for j=3,4,5,6. +The sample-variance convention ddof=1 is part of this implementation. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Bontemps, C. and Meddahi, N. (2005). + Testing normality: a GMM approach. + Journal of Econometrics, 124(1), 149-186. + https://doi.org/10.1016/j.jeconom.2004.02.014 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( BontempsMeddahi2NormalityGofStatistic, ) - -test_statistic = BontempsMeddahi2NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = BontempsMeddahi2NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/cabana_cabana1_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/cabana_cabana1_normality_criterion.md index dd805512..2fe0d95e 100644 --- a/docs/criteria/goodness-of-fit/normality/cabana_cabana1_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/cabana_cabana1_normality_criterion.md @@ -1,55 +1,60 @@ # Cabana-Cabana1 test for normality -## Description -Performs the Cabana-Cabana1 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `CabanaCabana1NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `CC1_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on Hermite-polynomial components and fitted normal CDF/PDF values. +Cabaña-Cabaña normality statistic focused on skewness departures. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CabanaCabana1NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = CabanaCabana1NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Cabana-Cabana1 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Use the l=5 process in Cabana and Cabana, equation (7). +For z=(x-mean(x))/s1, h_j=He_j/sqrt(j!), H_j=sum(h_j(z))/sqrt(n), +P(t)=sum_{j=1..5}(h_(j-1)(t)*H_(j+3)/sqrt(j)). Return +sup_t abs(Phi(t)*H_3-phi(t)*P(t)). Evaluate every real stationary +point (roots of H_3+t*P-P') and both limits at infinity. +This is the supremum of the truncated process, not the untruncated +infinite series. Polynomial root solving is subject to float64 accuracy. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Cabaña, A. and Cabaña, E. M. (2003). + Tests of Normality Based on Transformed Empirical Processes. + Methodology and Computing in Applied Probability, 5, 309-335. + https://doi.org/10.1023/A:1026235220018 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( CabanaCabana1NormalityGofStatistic, ) - -test_statistic = CabanaCabana1NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = CabanaCabana1NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/cabana_cabana2_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/cabana_cabana2_normality_criterion.md index f83f0a52..4bfb7277 100644 --- a/docs/criteria/goodness-of-fit/normality/cabana_cabana2_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/cabana_cabana2_normality_criterion.md @@ -1,55 +1,61 @@ # Cabana-Cabana2 test for normality -## Description -Performs the Cabana-Cabana2 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. - -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. - -Test Statistic -The statistic is based on higher-order Hermite-polynomial components and fitted normal CDF/PDF values. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CabanaCabana2NormalityGofStatistic, -) - - -test_statistic = CabanaCabana2NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. - -`var` - reference normal variance. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Cabana-Cabana2 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +**Class:** `CabanaCabana2NormalityGofStatistic` + +**Code:** `CC2_NORMALITY_GOODNESS_OF_FIT` + +Cabaña-Cabaña-style normality statistic focused on kurtosis departures. + +## Methods + +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. + +## Notes + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Use the l=5 process in Cabana and Cabana, equation (8). +For z=(x-mean(x))/s1, h_j=He_j/sqrt(j!), H_j=sum(h_j(z))/sqrt(n), +Q(t)=sum_{j=2..5}((sqrt(j/(j-1))*h_(j-2)(t)+h_j(t))*H_(j+3)). +Set P(t)=H_3+t*H_4+Q(t). Return +sup_t abs(Phi(t)*H_4-phi(t)*P(t)). Evaluate every real stationary +point (roots of H_4+t*P-P') and both limits at infinity. +The H_8 term occurs once. This is the truncated-process supremum; +polynomial root solving is subject to float64 accuracy. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Cabaña, A. and Cabaña, E. M. (2003). + Tests of Normality Based on Transformed Empirical Processes. + Methodology and Computing in Applied Probability, 5, 309-335. + https://doi.org/10.1023/A:1026235220018 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( CabanaCabana2NormalityGofStatistic, ) - -test_statistic = CabanaCabana2NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = CabanaCabana2NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/chen_shapiro_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/chen_shapiro_normality_criterion.md index 1a88921c..e0624b76 100644 --- a/docs/criteria/goodness-of-fit/normality/chen_shapiro_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/chen_shapiro_normality_criterion.md @@ -1,55 +1,56 @@ # Chen-Shapiro test for normality -## Description -Performs the Chen-Shapiro goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `ChenShapiroNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `CS_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on normalized spacings of ordered observations and expected normal quantiles. +Chen-Shapiro normality statistic based on normalized spacings. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ChenShapiroNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = ChenShapiroNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Chen-Shapiro statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +For u_i=Phi**-1((i-3/8)/(n+1/4)), return +sqrt(n)*(1-sum_i((x_(i+1)-x_(i))/(u_(i+1)-u_i))/((n-1)*s1)). +This is the upper-tail QH* version, not the lower-tail raw QH. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Chen, L. and Shapiro, S. S. (1995). + An alternative test for normality based on normalized spacings. + Journal of Statistical Computation and Simulation, 53(3-4), 269-287. + https://doi.org/10.1080/00949659508811711 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( ChenShapiroNormalityGofStatistic, ) - -test_statistic = ChenShapiroNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = ChenShapiroNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/chi2_pearson_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/chi2_pearson_normality_criterion.md new file mode 100644 index 00000000..20bbf8bb --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/chi2_pearson_normality_criterion.md @@ -0,0 +1,52 @@ +# Pearson chi-squared for normality + +**Class:** `Chi2PearsonNormalityGofStatistic` + +**Code:** `CHI2_PEARSON_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +Let `O_j` be the observed count and `E_j=n*p_j>0` the fitted expected count. + +`Σ (O_j-E_j)²/E_j`. A zero observed count contributes `E_j`. + +## Binning and calibration + +The optional `binning` keyword accepts a `BinningStrategy`; the default is +`EqualProbabilityBins()`. `ExplicitBins` boundaries are in the original data units. +Fit mean and unbiased variance on each replicate, then rebuild the same bins. +Do not assume a universal chi-square distribution with `k-3` degrees of freedom: +raw-data estimates, adaptive boundaries and the bin-count rule affect calibration. +Zero-probability categories and any configured minimum-expected-count merging +follow the [shared binning contract](../binning/index.md). + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + Chi2PearsonNormalityGofStatistic, +) +import numpy as np + +statistic = Chi2PearsonNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/coin_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/coin_normality_criterion.md index 264ceeff..cdb4aa03 100644 --- a/docs/criteria/goodness-of-fit/normality/coin_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/coin_normality_criterion.md @@ -1,55 +1,60 @@ # Coin test for normality -## Description -Performs the Coin goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `CoinNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `COIN_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on normal scores and standardized ordered observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CoinNormalityGofStatistic, -) +Coin normality statistic based on polynomial regression. +## Methods -test_statistic = CoinNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Details -The implementation evaluates the Coin statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Regress z_(i)=(x_(i)-mean(x))/s1 on a_i and a_i**3 without +an intercept, where a_i are approximate expected normal order scores +from nscor2. Return the square of the cubic coefficient. Normal-score +approximations are only supported here for n<=2000. The reference +identifies the regression procedure; its score approximation is +retained and must be reproduced in calibration. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Coin, D. (2008). + A goodness-of-fit test for normality based on polynomial regression. + Computational Statistics & Data Analysis, 52(4), 2185-2198. + https://doi.org/10.1016/j.csda.2007.07.012 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CoinNormalityGofStatistic, -) - -test_statistic = CoinNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import CoinNormalityGofStatistic + +statistic = CoinNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/cressie_read_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/cressie_read_normality_criterion.md new file mode 100644 index 00000000..b18099f6 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/cressie_read_normality_criterion.md @@ -0,0 +1,52 @@ +# Cressie–Read for normality + +**Class:** `CressieReadNormalityGofStatistic` + +**Code:** `CRESSIE_READ_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +Let `O_j` be the observed count and `E_j=n*p_j>0` the fitted expected count. + +`(9/5) Σ O_j [(O_j/E_j)^(2/3)-1]`. Terms with zero observed count are zero by continuity. + +## Binning and calibration + +The optional `binning` keyword accepts a `BinningStrategy`; the default is +`EqualProbabilityBins()`. `ExplicitBins` boundaries are in the original data units. +Fit mean and unbiased variance on each replicate, then rebuild the same bins. +Do not assume a universal chi-square distribution with `k-3` degrees of freedom: +raw-data estimates, adaptive boundaries and the bin-count rule affect calibration. +Zero-probability categories and any configured minimum-expected-count merging +follow the [shared binning contract](../binning/index.md). + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + CressieReadNormalityGofStatistic, +) +import numpy as np + +statistic = CressieReadNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/cvm_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/cvm_normality_criterion.md index 418df019..06a259f5 100644 --- a/docs/criteria/goodness-of-fit/normality/cvm_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/cvm_normality_criterion.md @@ -1,55 +1,63 @@ # Cramer-von Mises test for normality -## Description -Performs the Cramer-von Mises goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `CramerVonMiseNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `CVM_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on squared differences between the normal cumulative distribution function values and expected plotting positions. +Cramer-von Mises statistic for a specified normal distribution. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - CramerVonMiseNormalityGofStatistic, -) +## Parameters - -test_statistic = CramerVonMiseNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with mean, var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Cramer-von Mises statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mean,var) with both parameters fixed; hypothesis() reports both. +Constant samples are valid. Simulate the specified normal law. +Large values of the statistic define rejection. Use at least 1 +finite real observations in one dimension. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +W2 = 1/(12*n) + sum((F0(x_(i)) - (2*i-1)/(2*n))**2). +F0 is the normal CDF with the fixed mean and variance. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Cramer, H. (1928). On the composition of elementary errors. + Second paper: Statistical applications. Scandinavian Actuarial + Journal, 1928(1), 141-180. + https://doi.org/10.1080/03461238.1928.10416872 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( CramerVonMiseNormalityGofStatistic, ) - -test_statistic = CramerVonMiseNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = CramerVonMiseNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"mean": 0, "var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/dagostino_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/dagostino_normality_criterion.md index bb64e02a..07b07f88 100644 --- a/docs/criteria/goodness-of-fit/normality/dagostino_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/dagostino_normality_criterion.md @@ -1,55 +1,56 @@ # D'Agostino test for normality -## Description -Performs the D'Agostino goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `DagostinoNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `D_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a transformed linear combination of ordered observations. +D'Agostino's normality statistic based on ordered observations. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DagostinoNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = DagostinoNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the D'Agostino statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +D=sum_i((i-(n+1)/2)*x_(i))/(n**2*s0). Return +sqrt(n)*(D-0.28209479)/0.02998598. This is the signed, +asymptotically standardized D statistic, not D'Agostino-Pearson K2. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] D'Agostino, R. B. (1971). + An omnibus test of normality for moderate and large size samples. + Biometrika, 58(2), 341-348. + https://doi.org/10.1093/biomet/58.2.341 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( DagostinoNormalityGofStatistic, ) - -test_statistic = DagostinoNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = DagostinoNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/dagostino_pearson_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/dagostino_pearson_normality_criterion.md index cf03cbcc..86ad0a82 100644 --- a/docs/criteria/goodness-of-fit/normality/dagostino_pearson_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/dagostino_pearson_normality_criterion.md @@ -1,55 +1,60 @@ -# D'Agostino-Pearson test for normality +# D’Agostino–Pearson omnibus test -## Description -Performs the D'Agostino-Pearson goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `DAPNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `DAP_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the sum of squared transformed skewness and kurtosis statistics. +D'Agostino-Pearson omnibus ``K_squared`` statistic for normality. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DAPNormalityGofStatistic, -) +## Parameters +parameters : ParameterValues + An empty distribution schema; all distribution parameters are unknown. -test_statistic = DAPNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the D'Agostino-Pearson statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The upper tail of the statistic defines rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +K2 = Z_skew**2 + Z_kurtosis**2 using the signed transforms +implemented by SkewNormalityGofStatistic and KurtosisNormalityGofStatistic. +The resulting nonnegative discrepancy uses the upper tail. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +.. [1] D'Agostino, R. B. and Pearson, E. S. (1973). Tests for departure + from normality. Empirical results for the distributions of b2 and + sqrt(b1). Biometrika, 60(3), 613-622. + https://doi.org/10.1093/biomet/60.3.613 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DAPNormalityGofStatistic, -) - -test_statistic = DAPNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +import numpy as np +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import DAPNormalityGofStatistic + +statistic = DAPNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = np.random.default_rng(42).normal(size=24) +value = statistic.execute_statistic(sample) +assert np.isfinite(value) and value >= 0 ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/desgagne_lafaye_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/desgagne_lafaye_normality_criterion.md index cc78d18e..4ab212af 100644 --- a/docs/criteria/goodness-of-fit/normality/desgagne_lafaye_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/desgagne_lafaye_normality_criterion.md @@ -1,55 +1,61 @@ # Desgagne-Lafaye test for normality -## Description -Performs the Desgagne-Lafaye goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. - -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. - -Test Statistic -The statistic is based on logarithmic moment components of standardized observations. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DesgagneLafayeNormalityGofStatistic, -) - - -test_statistic = DesgagneLafayeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. - -`var` - reference normal variance. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Desgagne-Lafaye statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +**Class:** `DesgagneLafayeNormalityGofStatistic` + +**Code:** `DLDMZEPD_NORMALITY_GOODNESS_OF_FIT` + +Desgagne-Lafaye de Micheaux-Leblanc R_n normality statistic. + +## Methods + +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. + +## Notes + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +For z=(x-mean(x))/s0, let r=(0.18240929-mean(z**2*log(abs(z)))/2, +0.5348223-mean(log(1+abs(z))), +0.20981558-mean(log(log(e+abs(z))))). Return n*r.T*A*r, where +A is the rounded inverse fitted-score covariance in stat35. +The first integrand is zero at z=0 by continuity. Theorem 1 of the +author preprint accounts for fitting mean and variance. A is ill +conditioned; rounding its constants limits precision. Small-sample +chi-square calibration is inappropriate. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Desgagne, A., Lafaye de Micheaux, P., and Leblanc, A. (2013). + "Test of Normality Against Generalized Exponential Power + Alternatives." Communications in Statistics - Theory and Methods, + 42(1), 164-190. https://doi.org/10.1080/03610926.2011.577548 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( DesgagneLafayeNormalityGofStatistic, ) - -test_statistic = DesgagneLafayeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = DesgagneLafayeNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/doornik_hansen_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/doornik_hansen_normality_criterion.md index 7f7cb875..663001ab 100644 --- a/docs/criteria/goodness-of-fit/normality/doornik_hansen_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/doornik_hansen_normality_criterion.md @@ -1,55 +1,57 @@ # Doornik-Hansen test for normality -## Description -Performs the Doornik-Hansen goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `DoornikHansenNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `DH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on transformed skewness and kurtosis components. +Univariate Doornik-Hansen normality statistic. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - DoornikHansenNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = DoornikHansenNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Doornik-Hansen statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return Z1**2+Z2**2, with the Doornik-Hansen transformations of +g1=m3/m2**1.5 and g2=m4/m2**2 (Appendix A of the author preprint). +Z1 uses asinh; Z2 uses the real cube root and includes the g1**2 +adjustment to kurtosis. The chi-square law is asymptotic. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Doornik, J. A. and Hansen, H. (2008). + An Omnibus Test for Univariate and Multivariate Normality. + Oxford Bulletin of Economics and Statistics, 70(s1), 927-939. + https://doi.org/10.1111/j.1468-0084.2008.00537.x ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( DoornikHansenNormalityGofStatistic, ) - -test_statistic = DoornikHansenNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = DoornikHansenNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/epps_pulley_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/epps_pulley_normality_criterion.md index a2f1a446..3ad99779 100644 --- a/docs/criteria/goodness-of-fit/normality/epps_pulley_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/epps_pulley_normality_criterion.md @@ -1,55 +1,57 @@ # Epps-Pulley test for normality -## Description -Performs the Epps-Pulley goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `EppsPulleyNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `EP_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on an empirical characteristic-function statistic. +Epps-Pulley empirical-characteristic-function statistic for normality. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - EppsPulleyNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = EppsPulleyNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Epps-Pulley statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +For z=(x-mean(x))/s0, return +n/sqrt(3) + sum_ij(exp(-(z_i-z_j)**2/2))/n +- sqrt(2)*sum_i(exp(-z_i**2/4)). +This equals n times a Gaussian-weighted squared characteristic-function +distance. The double sum includes its diagonal; computation is O(n**2). ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Epps, T. W. and Pulley, L. B. (1983). A test for normality based + on the empirical characteristic function. Biometrika, 70(3), 723-726. + https://doi.org/10.1093/biomet/70.3.723 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( EppsPulleyNormalityGofStatistic, ) - -test_statistic = EppsPulleyNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = EppsPulleyNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/filliben_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/filliben_normality_criterion.md index 3e8bb3c5..33bbce3b 100644 --- a/docs/criteria/goodness-of-fit/normality/filliben_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/filliben_normality_criterion.md @@ -1,55 +1,52 @@ # Filliben test for normality -## Description -Performs the Filliben goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `FilliNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `FILLI_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the correlation between ordered sample values and normal order medians. +Filliben probability-plot correlation statistic for normality. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - FilliNormalityGofStatistic, -) - - -test_statistic = FilliNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Methods -## Arguments -`mean` - reference normal mean. Default value is `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`var` - reference normal variance. Default value is `1`. +## Notes -`rvs` - array-like sample data passed to `execute_statistic`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Details -The implementation evaluates the Filliben statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return corr(x_(i), Phi**-1(p_i)). The interior plotting positions +are (i-0.3175)/(n+0.365); endpoints are 1-0.5**(1/n) and 0.5**(1/n). ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Filliben, J. J. (1975). The Probability Plot Correlation + Coefficient Test for Normality. Technometrics, 17(1), 111-117. + https://doi.org/10.1080/00401706.1975.10489279 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - FilliNormalityGofStatistic, -) - -test_statistic = FilliNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import FilliNormalityGofStatistic + +statistic = FilliNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/freeman_tukey_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/freeman_tukey_normality_criterion.md new file mode 100644 index 00000000..a4d90fa2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/freeman_tukey_normality_criterion.md @@ -0,0 +1,52 @@ +# Freeman–Tukey for normality + +**Class:** `FreemanTukeyNormalityGofStatistic` + +**Code:** `FREEMAN_TUKEY_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +Let `O_j` be the observed count and `E_j=n*p_j>0` the fitted expected count. + +`4 Σ (sqrt(O_j)-sqrt(E_j))²`. A zero observed count contributes `4*E_j`. + +## Binning and calibration + +The optional `binning` keyword accepts a `BinningStrategy`; the default is +`EqualProbabilityBins()`. `ExplicitBins` boundaries are in the original data units. +Fit mean and unbiased variance on each replicate, then rebuild the same bins. +Do not assume a universal chi-square distribution with `k-3` degrees of freedom: +raw-data estimates, adaptive boundaries and the bin-count rule affect calibration. +Zero-probability categories and any configured minimum-expected-count merging +follow the [shared binning contract](../binning/index.md). + +## References + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + FreemanTukeyNormalityGofStatistic, +) +import numpy as np + +statistic = FreemanTukeyNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/glen_leemis_barr_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/glen_leemis_barr_normality_criterion.md index 93bfb16f..e1bb4552 100644 --- a/docs/criteria/goodness-of-fit/normality/glen_leemis_barr_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/glen_leemis_barr_normality_criterion.md @@ -1,55 +1,62 @@ # Glen-Leemis-Barr test for normality -## Description -Performs the Glen-Leemis-Barr goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. - -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. - -Test Statistic -The statistic is based on transformed fitted normal probabilities and beta distribution values. - -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GlenLeemisBarrNormalityGofStatistic, -) - - -test_statistic = GlenLeemisBarrNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. - -`var` - reference normal variance. Default value is `1`. - -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Glen-Leemis-Barr statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +**Class:** `GlenLeemisBarrNormalityGofStatistic` + +**Code:** `GLB_NORMALITY_GOODNESS_OF_FIT` + +Glen-Leemis-Barr order-statistic goodness-of-fit statistic. + +## Methods + +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. + +## Notes + +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +For z=(x-mean(x))/s1, form u_i=Phi(z_(i)), then +v_i=BetaCDF(u_i; i,n+1-i), and sort the v_i again. Return +-n-sum_i((2*n+1-2*i)*log(v_(i))+(2*i-1)*log(1-v_(i)))/n. +These are reversed Anderson-Darling weights, not the ordinary AD +statistic. A primary source confirming this exact fitted formula was +not located in the review; no author-specific calibration is claimed. +The beta transforms are dependent and are not uniform after fitting. +Use simulation of this formula only. Log-binomial sums recover +beta tails that underflow in direct probability arithmetic. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Glen, A. G., Leemis, L. M., Barr, D. R. (2001). Order statistics in goodness-of-fit testing. IEEE Transactions on Reliability, 50(2), 209–213. +https://doi.org/10.1109/24.963129 + +This identifies the order-statistic approach. The primary full text was not accessible during this audit; the reversed-weight, fitted-normal implementation is checked as the formula documented here, not certified as an exact reproduction of that paper. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GlenLeemisBarrNormalityGofStatistic, ) - -test_statistic = GlenLeemisBarrNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = GlenLeemisBarrNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/gmg_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/gmg_normality_criterion.md index b05728c3..506ef6ac 100644 --- a/docs/criteria/goodness-of-fit/normality/gmg_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/gmg_normality_criterion.md @@ -1,55 +1,55 @@ # GMG test for normality -## Description -Performs the GMG goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GMGNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `GMG_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the ratio of sample standard deviation to a robust median-based scale estimate. +Gel-Miao-Gastwirth normality statistic directed at heavy tails. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GMGNormalityGofStatistic, -) - - -test_statistic = GMGNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Methods -## Arguments -`mean` - reference normal mean. Default value is `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`var` - reference normal variance. Default value is `1`. +## Notes -`rvs` - array-like sample data passed to `execute_statistic`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Details -The implementation evaluates the GMG statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return s0/J, where J=sqrt(pi/2)*mean(abs(x-median(x))). +This is a directed upper-tail statistic for heavy-tailed departures. +The ddof=0 convention is retained; its finite-sample law differs +from versions using the unbiased sample variance. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Gel, Y. R., Miao, W. and Gastwirth, J. L. (2007). + Robust directed tests of normality against heavy-tailed alternatives. + Computational Statistics & Data Analysis, 51(5), 2734-2746. + https://doi.org/10.1016/j.csda.2006.08.022 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GMGNormalityGofStatistic, -) - -test_statistic = GMGNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import GMGNormalityGofStatistic + +statistic = GMGNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/graph_average_degree_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/graph_average_degree_normality_criterion.md index 5b6ae538..4bcd7b9c 100644 --- a/docs/criteria/goodness-of-fit/normality/graph_average_degree_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/graph_average_degree_normality_criterion.md @@ -1,55 +1,68 @@ # Graph average degree test for normality -## Description -Performs the Graph average degree goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GraphAverageDegreeNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `AVGDEGREE_GRAPH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the average degree in a proximity graph built from the sample. +Average vertex degree for a normal sample with known variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphAverageDegreeNormalityGofStatistic, -) +## Parameters - -test_statistic = GraphAverageDegreeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Graph average degree statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,var), with unknown mu and fixed var; hypothesis() reports var. +Calibrate at this variance; setting the simulation mean to zero is valid. +Both tails of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Connect i and j when abs(x_i-x_j) < (max(x)-min(x))/(10*m2), +where m2=mean((x-mean(x))**2). Return the mean vertex degree. +This local construction is translation invariant but not scale invariant. +var selects the null law for calibration; it is not inserted in the radius. +A primary source for this exact normality test was not located. No +published null law or omnibus power claim is made. Extreme scales that +make the radius or variance unrepresentable raise ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Ebner, B., Nestmann, F., Schulte, M. (2020). Testing multivariate uniformity based on random geometric graphs. Author preprint, arXiv:1812.08638v2. +https://arxiv.org/abs/1812.08638 + +This is related research on graph-based goodness-of-fit, not a source for this normality statistic or its sample-dependent radius. No scientific article establishing this exact normal test has been identified. The implementation is a local graph functional requiring simulation at the specified variance. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GraphAverageDegreeNormalityGofStatistic, ) - -test_statistic = GraphAverageDegreeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = GraphAverageDegreeNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/graph_clique_number_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/graph_clique_number_normality_criterion.md index 6db9e0d7..02b56802 100644 --- a/docs/criteria/goodness-of-fit/normality/graph_clique_number_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/graph_clique_number_normality_criterion.md @@ -1,55 +1,68 @@ # Graph clique number test for normality -## Description -Performs the Graph clique number goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GraphCliqueNumberNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `CLIQUENUMBER_GRAPH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the maximum clique size in a proximity graph built from the sample. +Clique-number statistic for a normal sample with known variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphCliqueNumberNormalityGofStatistic, -) +## Parameters - -test_statistic = GraphCliqueNumberNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Graph clique number statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,var), with unknown mu and fixed var; hypothesis() reports var. +Calibrate at this variance; setting the simulation mean to zero is valid. +Both tails of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Connect i and j when abs(x_i-x_j) < (max(x)-min(x))/(10*m2), +where m2=mean((x-mean(x))**2). Return the largest clique size (using sorted intervals). +This local construction is translation invariant but not scale invariant. +var selects the null law for calibration; it is not inserted in the radius. +A primary source for this exact normality test was not located. No +published null law or omnibus power claim is made. Extreme scales that +make the radius or variance unrepresentable raise ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Ebner, B., Nestmann, F., Schulte, M. (2020). Testing multivariate uniformity based on random geometric graphs. Author preprint, arXiv:1812.08638v2. +https://arxiv.org/abs/1812.08638 + +This is related research on graph-based goodness-of-fit, not a source for this normality statistic or its sample-dependent radius. No scientific article establishing this exact normal test has been identified. The implementation is a local graph functional requiring simulation at the specified variance. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GraphCliqueNumberNormalityGofStatistic, ) - -test_statistic = GraphCliqueNumberNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = GraphCliqueNumberNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/graph_connected_components_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/graph_connected_components_normality_criterion.md index 746d8e30..6dd26133 100644 --- a/docs/criteria/goodness-of-fit/normality/graph_connected_components_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/graph_connected_components_normality_criterion.md @@ -1,55 +1,68 @@ # Graph connected components test for normality -## Description -Performs the Graph connected components goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GraphConnectedComponentsNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `CONNECTEDCOMPONENTS_GRAPH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the number of connected components in a proximity graph built from the sample. +Number of connected components for a normal sample with known variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphConnectedComponentsNormalityGofStatistic, -) +## Parameters - -test_statistic = GraphConnectedComponentsNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Graph connected components statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,var), with unknown mu and fixed var; hypothesis() reports var. +Calibrate at this variance; setting the simulation mean to zero is valid. +Both tails of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Connect i and j when abs(x_i-x_j) < (max(x)-min(x))/(10*m2), +where m2=mean((x-mean(x))**2). Return the number of connected components. +This local construction is translation invariant but not scale invariant. +var selects the null law for calibration; it is not inserted in the radius. +A primary source for this exact normality test was not located. No +published null law or omnibus power claim is made. Extreme scales that +make the radius or variance unrepresentable raise ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Ebner, B., Nestmann, F., Schulte, M. (2020). Testing multivariate uniformity based on random geometric graphs. Author preprint, arXiv:1812.08638v2. +https://arxiv.org/abs/1812.08638 + +This is related research on graph-based goodness-of-fit, not a source for this normality statistic or its sample-dependent radius. No scientific article establishing this exact normal test has been identified. The implementation is a local graph functional requiring simulation at the specified variance. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GraphConnectedComponentsNormalityGofStatistic, ) - -test_statistic = GraphConnectedComponentsNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = GraphConnectedComponentsNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/graph_edges_number_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/graph_edges_number_normality_criterion.md index e1c8e200..4e72c883 100644 --- a/docs/criteria/goodness-of-fit/normality/graph_edges_number_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/graph_edges_number_normality_criterion.md @@ -1,55 +1,68 @@ # Graph edges number test for normality -## Description -Performs the Graph edges number goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GraphEdgesNumberNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `EDGESNUMBER_GRAPH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the number of edges in a proximity graph built from the sample. +Number of edges for a normal sample with known variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphEdgesNumberNormalityGofStatistic, -) +## Parameters - -test_statistic = GraphEdgesNumberNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Graph edges number statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,var), with unknown mu and fixed var; hypothesis() reports var. +Calibrate at this variance; setting the simulation mean to zero is valid. +Both tails of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Connect i and j when abs(x_i-x_j) < (max(x)-min(x))/(10*m2), +where m2=mean((x-mean(x))**2). Return the number of edges. +This local construction is translation invariant but not scale invariant. +var selects the null law for calibration; it is not inserted in the radius. +A primary source for this exact normality test was not located. No +published null law or omnibus power claim is made. Extreme scales that +make the radius or variance unrepresentable raise ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Ebner, B., Nestmann, F., Schulte, M. (2020). Testing multivariate uniformity based on random geometric graphs. Author preprint, arXiv:1812.08638v2. +https://arxiv.org/abs/1812.08638 + +This is related research on graph-based goodness-of-fit, not a source for this normality statistic or its sample-dependent radius. No scientific article establishing this exact normal test has been identified. The implementation is a local graph functional requiring simulation at the specified variance. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GraphEdgesNumberNormalityGofStatistic, ) - -test_statistic = GraphEdgesNumberNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = GraphEdgesNumberNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/graph_independence_number_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/graph_independence_number_normality_criterion.md index 45cf2ffe..ba54bb1f 100644 --- a/docs/criteria/goodness-of-fit/normality/graph_independence_number_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/graph_independence_number_normality_criterion.md @@ -1,55 +1,68 @@ # Graph independence number test for normality -## Description -Performs the Graph independence number goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GraphIndependenceNumberNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `INDEPENDENCENUMBER_GRAPH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the independence number of a proximity graph built from the sample. +Independence-number statistic for a normal sample with known variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphIndependenceNumberNormalityGofStatistic, -) +## Parameters - -test_statistic = GraphIndependenceNumberNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Graph independence number statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,var), with unknown mu and fixed var; hypothesis() reports var. +Calibrate at this variance; setting the simulation mean to zero is valid. +Both tails of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Connect i and j when abs(x_i-x_j) < (max(x)-min(x))/(10*m2), +where m2=mean((x-mean(x))**2). Return the largest independent set size (using a sorted greedy scan). +This local construction is translation invariant but not scale invariant. +var selects the null law for calibration; it is not inserted in the radius. +A primary source for this exact normality test was not located. No +published null law or omnibus power claim is made. Extreme scales that +make the radius or variance unrepresentable raise ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Ebner, B., Nestmann, F., Schulte, M. (2020). Testing multivariate uniformity based on random geometric graphs. Author preprint, arXiv:1812.08638v2. +https://arxiv.org/abs/1812.08638 + +This is related research on graph-based goodness-of-fit, not a source for this normality statistic or its sample-dependent radius. No scientific article establishing this exact normal test has been identified. The implementation is a local graph functional requiring simulation at the specified variance. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GraphIndependenceNumberNormalityGofStatistic, ) - -test_statistic = GraphIndependenceNumberNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = GraphIndependenceNumberNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/graph_max_degree_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/graph_max_degree_normality_criterion.md index 429af2e4..87101520 100644 --- a/docs/criteria/goodness-of-fit/normality/graph_max_degree_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/graph_max_degree_normality_criterion.md @@ -1,55 +1,68 @@ # Graph max degree test for normality -## Description -Performs the Graph max degree goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `GraphMaxDegreeNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `MAXDEGREE_GRAPH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the maximum degree in a proximity graph built from the sample. +Maximum vertex degree for a normal sample with known variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - GraphMaxDegreeNormalityGofStatistic, -) +## Parameters - -test_statistic = GraphMaxDegreeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with var fixed; omitted parameters are unknown. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Graph max degree statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,var), with unknown mu and fixed var; hypothesis() reports var. +Calibrate at this variance; setting the simulation mean to zero is valid. +Both tails of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Connect i and j when abs(x_i-x_j) < (max(x)-min(x))/(10*m2), +where m2=mean((x-mean(x))**2). Return the maximum degree. +This local construction is translation invariant but not scale invariant. +var selects the null law for calibration; it is not inserted in the radius. +A primary source for this exact normality test was not located. No +published null law or omnibus power claim is made. Extreme scales that +make the radius or variance unrepresentable raise ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +Ebner, B., Nestmann, F., Schulte, M. (2020). Testing multivariate uniformity based on random geometric graphs. Author preprint, arXiv:1812.08638v2. +https://arxiv.org/abs/1812.08638 + +This is related research on graph-based goodness-of-fit, not a source for this normality statistic or its sample-dependent radius. No scientific article establishing this exact normal test has been identified. The implementation is a local graph functional requiring simulation at the specified variance. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( GraphMaxDegreeNormalityGofStatistic, ) - -test_statistic = GraphMaxDegreeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = GraphMaxDegreeNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/hosking1_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/hosking1_normality_criterion.md index a491aecc..3e38f875 100644 --- a/docs/criteria/goodness-of-fit/normality/hosking1_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/hosking1_normality_criterion.md @@ -1,55 +1,66 @@ # Hosking1 test for normality -## Description -Performs the Hosking1 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `Hosking1NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `HOSKING1_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on sample L-moment ratios for skewness and kurtosis. +Hosking L-moment normality statistic without trimming. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking1NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = Hosking1NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Notes -## Arguments -`mean` - reference normal mean. Default value is `0`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`var` - reference normal variance. Default value is `1`. +Local quadratic discrepancy of L-moment ratios with trim t=0. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -`rvs` - array-like sample data passed to `execute_statistic`. +## References -## Details -The implementation evaluates the Hosking1 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -## Author(s) -Alexey Mironov +These articles justify the L-moment construction, not the three local rows of calibration constants used here. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( Hosking1NormalityGofStatistic, ) - -test_statistic = Hosking1NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = Hosking1NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/hosking2_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/hosking2_normality_criterion.md index 487ceeef..729e8beb 100644 --- a/docs/criteria/goodness-of-fit/normality/hosking2_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/hosking2_normality_criterion.md @@ -1,55 +1,66 @@ # Hosking2 test for normality -## Description -Performs the Hosking2 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `Hosking2NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `HOSKING2_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on trimmed L-moment ratios for skewness and kurtosis. +Hosking normality statistic with symmetric trimming level 1. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking2NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = Hosking2NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Notes -## Arguments -`mean` - reference normal mean. Default value is `0`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 6 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`var` - reference normal variance. Default value is `1`. +Local quadratic discrepancy of L-moment ratios with trim t=1. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -`rvs` - array-like sample data passed to `execute_statistic`. +## References -## Details -The implementation evaluates the Hosking2 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -## Author(s) -Alexey Mironov +These articles justify the L-moment construction, not the three local rows of calibration constants used here. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( Hosking2NormalityGofStatistic, ) - -test_statistic = Hosking2NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = Hosking2NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/hosking3_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/hosking3_normality_criterion.md index 7fe21985..3a95930a 100644 --- a/docs/criteria/goodness-of-fit/normality/hosking3_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/hosking3_normality_criterion.md @@ -1,55 +1,66 @@ # Hosking3 test for normality -## Description -Performs the Hosking3 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `Hosking3NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `HOSKING3_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on higher-trimmed L-moment ratios for skewness and kurtosis. +Hosking normality statistic with symmetric trimming level 2. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking3NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = Hosking3NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Notes -## Arguments -`mean` - reference normal mean. Default value is `0`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`var` - reference normal variance. Default value is `1`. +Local quadratic discrepancy of L-moment ratios with trim t=2. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -`rvs` - array-like sample data passed to `execute_statistic`. +## References -## Details -The implementation evaluates the Hosking3 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -## Author(s) -Alexey Mironov +These articles justify the L-moment construction, not the three local rows of calibration constants used here. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( Hosking3NormalityGofStatistic, ) - -test_statistic = Hosking3NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = Hosking3NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/hosking4_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/hosking4_normality_criterion.md index d1ea4de0..c7cdd1d6 100644 --- a/docs/criteria/goodness-of-fit/normality/hosking4_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/hosking4_normality_criterion.md @@ -1,55 +1,66 @@ # Hosking4 test for normality -## Description -Performs the Hosking4 goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `Hosking4NormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `HOSKING4_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on third-level trimmed L-moment ratios for skewness and kurtosis. +Hosking normality statistic with symmetric trimming level 3. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - Hosking4NormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = Hosking4NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Notes -## Arguments -`mean` - reference normal mean. Default value is `0`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 10 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`var` - reference normal variance. Default value is `1`. +Local quadratic discrepancy of L-moment ratios with trim t=3. +For r=2,3,4, L_r=sum_i x_(i)*sum_{k=0..r-1}((-1)**k* +C(r-1,k)*C(i-1,r+t-1-k)*C(n-i,t+k))/(r*C(n,r+2*t)). +Return (L3/L2)**2/v3+(L4/L2-mu4)**2/v4. The constants +(mu4,v3,v4) are the three historical rows in the implementation +for n<=25, 2550. They are not a consistent +asymptotic covariance sequence. A primary source for this exact +omnibus formula and these rows was not located; the L-moment +papers alone do not validate this test. Treat it as a local +statistic and simulate its null law at the actual n. L2 must be positive. -`rvs` - array-like sample data passed to `execute_statistic`. +## References -## Details -The implementation evaluates the Hosking4 statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Hosking, J. R. M. (1990). L-moments: analysis and estimation of distributions using linear combinations of order statistics. JRSS B, 52(1), 105–124. +https://doi.org/10.1111/j.2517-6161.1990.tb01775.x -## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. +Hosking, J. R. M. (2007). Some theory and practical uses of trimmed L-moments. Journal of Statistical Planning and Inference, 137(9), 3024–3039. +https://doi.org/10.1016/j.jspi.2006.12.002 -## Author(s) -Alexey Mironov +These articles justify the L-moment construction, not the three local rows of calibration constants used here. ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( Hosking4NormalityGofStatistic, ) - -test_statistic = Hosking4NormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = Hosking4NormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/index.md b/docs/criteria/goodness-of-fit/normality/index.md new file mode 100644 index 00000000..b924e1e0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/index.md @@ -0,0 +1,119 @@ +# Normality statistics + +The module `pysatl_criterion.statistics.goodness_of_fit.continuous.normal` +exports **60 concrete statistics**: 16 generated EDF statistics, 5 generated +frequency statistics and 39 explicit statistics, including six graph functionals. +Every entry below links to a separate page with its formula, runnable example, +scientific references and the qualifications on its interpretation. + +Read the [mathematical verification report](mathematical-validation.md) before +reusing a published table or interpreting a legacy name as a certified test. + +## Hypotheses and calibration + +- **Fixed:** KS and CVM require `{'mean': mu, 'var': sigma_squared}`. They accept a + singleton or a constant sample. Variance is not standard deviation. +- **Family:** 52 statistics take `{}`. For generated EDF/frequency statistics, + mean and unbiased variance are fitted on every call. Other tests use the + estimators stated on their individual pages. Calibrate by simulating N(0,1) + and repeating the complete computation; fitted CDF values are dependent. +- **Graph:** six statistics take `{'var': sigma_squared}` with unknown mean. + Their radius is translation invariant but not scale invariant. Simulate at + the specified variance; a standard-normal table cannot be reused arbitrarily. + +Lower-tail tests reject for small values, upper-tail tests for large values. +Two-tail statistics require both quantiles; they need not have a symmetric null +law. Directional KS deviations still have an upper-tail rejection rule. +None of these classes returns a p-value. Small samples, ties/rounding and +algorithm options must be reproduced in calibration. Default frequency bins +are equal-probability bins; user-specified boundaries can destroy scale invariance. + +## Catalog + +| Statistic page | Python class | Full code | Hypothesis | Rejection tail | +| --- | --- | --- | --- | --- | +| [BHS test for normality](bhs_normality_criterion.md) | `BHSNormalityGofStatistic` | `BHS_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Bonett-Seier test for normality](bonett_seier_normality_criterion.md) | `BonettSeierNormalityGofStatistic` | `BS_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Bontemps-Meddahi1 test for normality](bontemps_meddahi1_normality_criterion.md) | `BontempsMeddahi1NormalityGofStatistic` | `BM1_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Bontemps-Meddahi2 test for normality](bontemps_meddahi2_normality_criterion.md) | `BontempsMeddahi2NormalityGofStatistic` | `BM2_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Cabana-Cabana1 test for normality](cabana_cabana1_normality_criterion.md) | `CabanaCabana1NormalityGofStatistic` | `CC1_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Cabana-Cabana2 test for normality](cabana_cabana2_normality_criterion.md) | `CabanaCabana2NormalityGofStatistic` | `CC2_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Chen-Shapiro test for normality](chen_shapiro_normality_criterion.md) | `ChenShapiroNormalityGofStatistic` | `CS_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Coin test for normality](coin_normality_criterion.md) | `CoinNormalityGofStatistic` | `COIN_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [D’Agostino–Pearson omnibus test](dagostino_pearson_normality_criterion.md) | `DAPNormalityGofStatistic` | `DAP_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [D'Agostino test for normality](dagostino_normality_criterion.md) | `DagostinoNormalityGofStatistic` | `D_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Desgagne-Lafaye test for normality](desgagne_lafaye_normality_criterion.md) | `DesgagneLafayeNormalityGofStatistic` | `DLDMZEPD_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Doornik-Hansen test for normality](doornik_hansen_normality_criterion.md) | `DoornikHansenNormalityGofStatistic` | `DH_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Epps-Pulley test for normality](epps_pulley_normality_criterion.md) | `EppsPulleyNormalityGofStatistic` | `EP_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Filliben test for normality](filliben_normality_criterion.md) | `FilliNormalityGofStatistic` | `FILLI_NORMALITY_GOODNESS_OF_FIT` | Family | Lower | +| [GMG test for normality](gmg_normality_criterion.md) | `GMGNormalityGofStatistic` | `GMG_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Glen-Leemis-Barr test for normality](glen_leemis_barr_normality_criterion.md) | `GlenLeemisBarrNormalityGofStatistic` | `GLB_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Graph average degree test for normality](graph_average_degree_normality_criterion.md) | `GraphAverageDegreeNormalityGofStatistic` | `AVGDEGREE_GRAPH_NORMALITY_GOODNESS_OF_FIT` | Graph | Both | +| [Graph clique number test for normality](graph_clique_number_normality_criterion.md) | `GraphCliqueNumberNormalityGofStatistic` | `CLIQUENUMBER_GRAPH_NORMALITY_GOODNESS_OF_FIT` | Graph | Both | +| [Graph connected components test for normality](graph_connected_components_normality_criterion.md) | `GraphConnectedComponentsNormalityGofStatistic` | `CONNECTEDCOMPONENTS_GRAPH_NORMALITY_GOODNESS_OF_FIT` | Graph | Both | +| [Graph edges number test for normality](graph_edges_number_normality_criterion.md) | `GraphEdgesNumberNormalityGofStatistic` | `EDGESNUMBER_GRAPH_NORMALITY_GOODNESS_OF_FIT` | Graph | Both | +| [Graph independence number test for normality](graph_independence_number_normality_criterion.md) | `GraphIndependenceNumberNormalityGofStatistic` | `INDEPENDENCENUMBER_GRAPH_NORMALITY_GOODNESS_OF_FIT` | Graph | Both | +| [Graph max degree test for normality](graph_max_degree_normality_criterion.md) | `GraphMaxDegreeNormalityGofStatistic` | `MAXDEGREE_GRAPH_NORMALITY_GOODNESS_OF_FIT` | Graph | Both | +| [Hosking1 test for normality](hosking1_normality_criterion.md) | `Hosking1NormalityGofStatistic` | `HOSKING1_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Hosking2 test for normality](hosking2_normality_criterion.md) | `Hosking2NormalityGofStatistic` | `HOSKING2_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Hosking3 test for normality](hosking3_normality_criterion.md) | `Hosking3NormalityGofStatistic` | `HOSKING3_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Hosking4 test for normality](hosking4_normality_criterion.md) | `Hosking4NormalityGofStatistic` | `HOSKING4_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Jarque-Bera test for normality](jarque_bera_normality_criterion.md) | `JBNormalityGofStatistic` | `JB_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Kurtosis test for normality](kurtosis_normality_criterion.md) | `KurtosisNormalityGofStatistic` | `KURTOSIS_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Looney-Gulledge test for normality](looney_gulledge_normality_criterion.md) | `LooneyGulledgeNormalityGofStatistic` | `LG_NORMALITY_GOODNESS_OF_FIT` | Family | Lower | +| [Martinez-Iglewicz test for normality](martinez_iglewicz_normality_criterion.md) | `MartinezIglewiczNormalityGofStatistic` | `MI_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Robust Jarque-Bera test for normality](robust_jarque_bera_normality_criterion.md) | `RobustJarqueBeraNormalityGofStatistic` | `RJB_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Ryan-Joiner test for normality](ryan_joiner_normality_criterion.md) | `RyanJoinerNormalityGofStatistic` | `RJ_NORMALITY_GOODNESS_OF_FIT` | Family | Lower | +| [SF test for normality](sf_normality_criterion.md) | `SFNormalityGofStatistic` | `SF_NORMALITY_GOODNESS_OF_FIT` | Family | Lower | +| [SWRG test for normality](swrg_normality_criterion.md) | `SWRGNormalityGofStatistic` | `SWRG_NORMALITY_GOODNESS_OF_FIT` | Family | Lower | +| [Shapiro-Wilk test for normality](shapiro_wilk_normality_criterion.md) | `ShapiroWilkNormalityGofStatistic` | `SW_NORMALITY_GOODNESS_OF_FIT` | Family | Lower | +| [Skewness test for normality](skew_normality_criterion.md) | `SkewNormalityGofStatistic` | `SKEW_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Spiegelhalter test for normality](spiegelhalter_normality_criterion.md) | `SpiegelhalterNormalityGofStatistic` | `SH_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Zhang Q test for normality](zhang_q_normality_criterion.md) | `ZhangQNormalityGofStatistic` | `ZQ_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Zhang Q-star test for normality](zhang_q_star_normality_criterion.md) | `ZhangQStarNormalityGofStatistic` | `ZQS_NORMALITY_GOODNESS_OF_FIT` | Family | Both | +| [Zhang-Wu A test for normality](zhang_wu_a_normality_criterion.md) | `ZhangWuANormalityGofStatistic` | `ZWA_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Zhang-Wu C test for normality](zhang_wu_c_normality_criterion.md) | `ZhangWuCNormalityGofStatistic` | `ZWC_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Kolmogorov-Smirnov test for normality](kolmogorov_smirnov_normality_criterion.md) | `KolmogorovSmirnovNormalityGofStatistic` | `KS_NORMALITY_GOODNESS_OF_FIT` | Fixed | Upper | +| [Anderson-Darling test for normality](anderson_darling_normality_criterion.md) | `AndersonDarlingNormalityGofStatistic` | `AD_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Cramer-von Mises test for normality](cvm_normality_criterion.md) | `CramerVonMiseNormalityGofStatistic` | `CVM_GOODNESS_OF_FIT` | Fixed | Upper | +| [Lilliefors test for normality](lilliefors_normality_criterion.md) | `LillieforsNormalityGofStatistic` | `LILLIE_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Kolmogorov–Smirnov D+ for normality](kolmogorov_smirnov_d_plus_normality_criterion.md) | `KolmogorovSmirnovDPlusNormalityGofStatistic` | `KS_PLUS_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Kolmogorov–Smirnov D− for normality](kolmogorov_smirnov_d_minus_normality_criterion.md) | `KolmogorovSmirnovDMinusNormalityGofStatistic` | `KS_MINUS_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Liao–Shimokawa for normality](liao_shimokawa_normality_criterion.md) | `LiaoShimokawaNormalityGofStatistic` | `LIAO_SHIMOKAWA_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Watson for normality](watson_normality_criterion.md) | `WatsonNormalityGofStatistic` | `WATSON_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Kuiper for normality](kuiper_normality_criterion.md) | `KuiperNormalityGofStatistic` | `KUIPER_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Scaled Kuiper for normality](kuiper_scaled_normality_criterion.md) | `KuiperScaledNormalityGofStatistic` | `KUIPER_SCALED_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Corrected Kuiper for normality](kuiper_corrected_normality_criterion.md) | `KuiperCorrectedNormalityGofStatistic` | `KUIPER_CORRECTED_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Zhang K for normality](zhang_k_normality_criterion.md) | `ZhangKNormalityGofStatistic` | `ZHANG_ZK_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Zhang A for normality](zhang_a_normality_criterion.md) | `ZhangANormalityGofStatistic` | `ZHANG_ZA_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Zhang C for normality](zhang_c_normality_criterion.md) | `ZhangCNormalityGofStatistic` | `ZHANG_ZC_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Pearson chi-squared for normality](chi2_pearson_normality_criterion.md) | `Chi2PearsonNormalityGofStatistic` | `CHI2_PEARSON_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Freeman–Tukey for normality](freeman_tukey_normality_criterion.md) | `FreemanTukeyNormalityGofStatistic` | `FREEMAN_TUKEY_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Modified log likelihood for normality](modified_log_likelihood_normality_criterion.md) | `ModifiedLogLikelihoodNormalityGofStatistic` | `MODIFIED_LOG_LIKELIHOOD_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Neyman chi-squared for normality](neyman_chi2_normality_criterion.md) | `NeymanChi2NormalityGofStatistic` | `CHI2_NEYMAN_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | +| [Cressie–Read for normality](cressie_read_normality_criterion.md) | `CressieReadNormalityGofStatistic` | `CRESSIE_READ_NORMALITY_GOODNESS_OF_FIT` | Family | Upper | + +## Example + +```python +import numpy as np +from pysatl_criterion.distribution import NormalDistributionDescriptor as Normal +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + KolmogorovSmirnovNormalityGofStatistic, + ShapiroWilkNormalityGofStatistic, +) + +sample = np.random.default_rng(42).normal(size=24) +fixed = KolmogorovSmirnovNormalityGofStatistic(Normal.DEFAULT.parse({"mean": 0, "var": 1})) +family = ShapiroWilkNormalityGofStatistic(Normal.DEFAULT.parse({})) +assert np.isfinite(fixed.execute_statistic(sample)) +assert 0 <= family.execute_statistic(sample) <= 1 +``` + +## Scientific provenance + +The report distinguishes published formulas, finite-sample approximations and +local definitions. Hosking's L-moment theory does not establish the local +piecewise calibration constants; graph literature does not establish the exact +six graph normality tests; the exact fitted GLB attribution remains unconfirmed. +The pages link the relevant literature with these limits stated explicitly. diff --git a/docs/criteria/goodness-of-fit/normality/jarque_bera_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/jarque_bera_normality_criterion.md index 39d3176b..412e254d 100644 --- a/docs/criteria/goodness-of-fit/normality/jarque_bera_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/jarque_bera_normality_criterion.md @@ -1,55 +1,52 @@ # Jarque-Bera test for normality -## Description -Performs the Jarque-Bera goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `JBNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `JB_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on sample skewness and kurtosis departures from their normal-distribution values. +Jarque-Bera statistic based on sample skewness and excess kurtosis. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - JBNormalityGofStatistic, -) - - -test_statistic = JBNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Methods -## Arguments -`mean` - reference normal mean. Default value is `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`var` - reference normal variance. Default value is `1`. +## Notes -`rvs` - array-like sample data passed to `execute_statistic`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Details -The implementation evaluates the Jarque-Bera statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +JB = n*(g1**2/6 + (g2-3)**2/24), where +g1=m3/m2**1.5, g2=m4/m2**2, and mk=mean((x-mean(x))**k). ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Jarque, C. M. and Bera, A. K. (1987). A Test for Normality of + Observations and Regression Residuals. International Statistical + Review, 55(2), 163-172. https://doi.org/10.2307/1403192 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - JBNormalityGofStatistic, -) - -test_statistic = JBNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import JBNormalityGofStatistic + +statistic = JBNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_d_minus_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_d_minus_normality_criterion.md new file mode 100644 index 00000000..5992555c --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_d_minus_normality_criterion.md @@ -0,0 +1,52 @@ +# Kolmogorov–Smirnov D− for normality + +**Class:** `KolmogorovSmirnovDMinusNormalityGofStatistic` + +**Code:** `KS_MINUS_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`D− = max_i(u_i-(i-1)/n)`. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). The formula is an EDF functional; its application here refits normal parameters. + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + KolmogorovSmirnovDMinusNormalityGofStatistic, +) +import numpy as np + +statistic = KolmogorovSmirnovDMinusNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({}) +) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_d_plus_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_d_plus_normality_criterion.md new file mode 100644 index 00000000..3d40597d --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_d_plus_normality_criterion.md @@ -0,0 +1,52 @@ +# Kolmogorov–Smirnov D+ for normality + +**Class:** `KolmogorovSmirnovDPlusNormalityGofStatistic` + +**Code:** `KS_PLUS_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`D+ = max_i(i/n-u_i)`. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). The formula is an EDF functional; its application here refits normal parameters. + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + KolmogorovSmirnovDPlusNormalityGofStatistic, +) +import numpy as np + +statistic = KolmogorovSmirnovDPlusNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({}) +) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_normality_criterion.md index bc216ac2..e4ea9ab1 100644 --- a/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/kolmogorov_smirnov_normality_criterion.md @@ -1,59 +1,72 @@ # Kolmogorov-Smirnov test for normality -## Description -Performs the Kolmogorov-Smirnov goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `KolmogorovSmirnovNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `KS_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on empirical distribution function with the standard normal cumulative distribution function. +One-sample Kolmogorov-Smirnov statistic for a specified normal law. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KolmogorovSmirnovNormalityGofStatistic, -) +## Parameters - -test_statistic = KolmogorovSmirnovNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + Values with mean, var fixed; omitted parameters are unknown. +alternative_type : AlternativeType, optional + ``TWO_TAILED`` computes ``max(D_plus, D_minus)``; ``RIGHT`` computes + ``D_plus = sup(F_n - F_0)`` and ``LEFT`` computes + ``D_minus = sup(F_0 - F_n)``. Defaults to ``TWO_TAILED``. +mode : str, optional + Setting retained by the shared KS implementation. ``"auto"`` is + stored as ``"exact"``. It does not affect the statistic and this + class does not calculate a p-value. ``` -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Methods -`var` - reference normal variance. Default value is `1`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`alternative_type` - alternative hypothesis type used by the Kolmogorov-Smirnov statistic. +## Notes -`mode` - calculation mode passed to the Kolmogorov-Smirnov statistic. Default value is `auto`. +H0 is N(mean,var) with both parameters fixed; hypothesis() reports both. +Constant samples are valid. Simulate the specified normal law. +Large values of the statistic define rejection. Use at least 1 +finite real observations in one dimension. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Kolmogorov-Smirnov statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +D+ = max(i/n - F0(x_(i))) and D- = max(F0(x_(i)) - (i-1)/n). +Return D+, D-, or max(D+, D-) according to alternative_type. +F0 is the normal CDF with the fixed mean and variance. All three +distances use the upper critical tail; mode does not compute a p-value. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Smirnov, N. (1948). Table for Estimating the Goodness of Fit of + Empirical Distributions. The Annals of Mathematical Statistics, + 19(2), 279-281. https://doi.org/10.1214/aoms/1177730256 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( KolmogorovSmirnovNormalityGofStatistic, ) - -test_statistic = KolmogorovSmirnovNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] +statistic = KolmogorovSmirnovNormalityGofStatistic( + NormalDistributionDescriptor.DEFAULT.parse({"mean": 0, "var": 1}) ) -print(statistic_result) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kuiper_corrected_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kuiper_corrected_normality_criterion.md new file mode 100644 index 00000000..cae3cadc --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/kuiper_corrected_normality_criterion.md @@ -0,0 +1,50 @@ +# Corrected Kuiper for normality + +**Class:** `KuiperCorrectedNormalityGofStatistic` + +**Code:** `KUIPER_CORRECTED_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`(sqrt(n)+0.155+0.24/sqrt(n)) (D+ + D−)`. The correction is a normalization, not a proof that known-CDF critical values apply to fitted normals. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014), equations (1)–(3)](https://doi.org/10.3103/S875669901401004X). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + KuiperCorrectedNormalityGofStatistic, +) +import numpy as np + +statistic = KuiperCorrectedNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kuiper_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kuiper_normality_criterion.md new file mode 100644 index 00000000..6506bd7e --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/kuiper_normality_criterion.md @@ -0,0 +1,50 @@ +# Kuiper for normality + +**Class:** `KuiperNormalityGofStatistic` + +**Code:** `KUIPER_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`V = D+ + D−`, without scaling. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014), equations (1)–(3)](https://doi.org/10.3103/S875669901401004X). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + KuiperNormalityGofStatistic, +) +import numpy as np + +statistic = KuiperNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kuiper_scaled_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kuiper_scaled_normality_criterion.md new file mode 100644 index 00000000..7b925ba1 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/kuiper_scaled_normality_criterion.md @@ -0,0 +1,50 @@ +# Scaled Kuiper for normality + +**Class:** `KuiperScaledNormalityGofStatistic` + +**Code:** `KUIPER_SCALED_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`sqrt(n) (D+ + D−)`. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014), equations (1)–(3)](https://doi.org/10.3103/S875669901401004X). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + KuiperScaledNormalityGofStatistic, +) +import numpy as np + +statistic = KuiperScaledNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/kurtosis_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/kurtosis_normality_criterion.md index 2a107ccb..256640b6 100644 --- a/docs/criteria/goodness-of-fit/normality/kurtosis_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/kurtosis_normality_criterion.md @@ -1,55 +1,57 @@ # Kurtosis test for normality -## Description -Performs the Kurtosis goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `KurtosisNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `KURTOSIS_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a transformed sample kurtosis statistic. +Anscombe-Glynn transformed-kurtosis statistic for the normal family. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - KurtosisNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = KurtosisNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 5 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Kurtosis statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return the signed Anscombe-Glynn transform of g2=m4/m2**2, +using the finite-n expectation, variance and skewness of g2. A real +cube root is used. A zero transformation denominator is undefined. +Both light and heavy tails matter; the normal approximation is +particularly inaccurate for small samples. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Anscombe, F. J. and Glynn, W. J. (1983). Distribution of the + kurtosis statistic b2 for normal samples. Biometrika, 70(1), 227-234. + https://doi.org/10.1093/biomet/70.1.227 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( KurtosisNormalityGofStatistic, ) - -test_statistic = KurtosisNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = KurtosisNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/liao_shimokawa_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/liao_shimokawa_normality_criterion.md new file mode 100644 index 00000000..67fd5e36 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/liao_shimokawa_normality_criterion.md @@ -0,0 +1,50 @@ +# Liao–Shimokawa for normality + +**Class:** `LiaoShimokawaNormalityGofStatistic` + +**Code:** `LIAO_SHIMOKAWA_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`n^(-1/2) Σ max(i/n-u_i, u_i-(i-1)/n) / sqrt(u_i(1-u_i))`. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Liao and Shimokawa (1999), A new goodness-of-fit test for Type-I extreme-value and 2-parameter Weibull distributions](https://doi.org/10.1080/00949659908811965). This page applies the EDF functional to fitted normal scores; the paper’s original distribution-specific tables do not apply. + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + LiaoShimokawaNormalityGofStatistic, +) +import numpy as np + +statistic = LiaoShimokawaNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/lilliefors_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/lilliefors_normality_criterion.md index 85aa9182..a246a2a5 100644 --- a/docs/criteria/goodness-of-fit/normality/lilliefors_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/lilliefors_normality_criterion.md @@ -1,55 +1,56 @@ # Lilliefors test for normality -## Description -Performs the Lilliefors goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `LillieforsNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `LILLIE_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the Kolmogorov-Smirnov type discrepancy after standardizing the sample by its empirical mean and standard deviation. +Lilliefors statistic for normality with unknown mean and variance. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LillieforsNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = LillieforsNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 2 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Lilliefors statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +D = max_i(i/n-Phi(z_(i)), Phi(z_(i))-(i-1)/n), +where z=(x-mean(x))/s1. Both parameters are re-estimated on every call. +Ordinary fixed-CDF KS tables do not apply. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Lilliefors, H. W. (1967). On the Kolmogorov-Smirnov Test for + Normality with Mean and Variance Unknown. Journal of the American + Statistical Association, 62(318), 399-402. + https://doi.org/10.1080/01621459.1967.10482916 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( LillieforsNormalityGofStatistic, ) - -test_statistic = LillieforsNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = LillieforsNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/looney_gulledge_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/looney_gulledge_normality_criterion.md index eda2bd74..e821014c 100644 --- a/docs/criteria/goodness-of-fit/normality/looney_gulledge_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/looney_gulledge_normality_criterion.md @@ -1,55 +1,55 @@ # Looney-Gulledge test for normality -## Description -Performs the Looney-Gulledge goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `LooneyGulledgeNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `LG_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the correlation between ordered observations and expected normal order statistics. +Looney-Gulledge probability-plot correlation statistic for normality. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - LooneyGulledgeNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = LooneyGulledgeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Looney-Gulledge statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return corr(x_(i), Phi**-1((i-3/8)/(n+1/4))). +The Blom plotting-position version is used without averaging ties. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Looney, S. W. and Gulledge, T. R., Jr. (1985). Use of the + Correlation Coefficient with Normal Probability Plots. The American + Statistician, 39(1), 75-79. + https://doi.org/10.1080/00031305.1985.10479395 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( LooneyGulledgeNormalityGofStatistic, ) - -test_statistic = LooneyGulledgeNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = LooneyGulledgeNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/martinez_iglewicz_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/martinez_iglewicz_normality_criterion.md index 03b55a87..ce539108 100644 --- a/docs/criteria/goodness-of-fit/normality/martinez_iglewicz_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/martinez_iglewicz_normality_criterion.md @@ -1,55 +1,59 @@ # Martinez-Iglewicz test for normality -## Description -Performs the Martinez-Iglewicz goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `MartinezIglewiczNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `MI_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a robust scale estimate based on the median and median absolute deviation. +Martinez-Iglewicz statistic comparing two estimates of dispersion. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - MartinezIglewiczNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = MartinezIglewiczNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Martinez-Iglewicz statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Let M=median(x), A=median(abs(x-M)), u=(x-M)/(9*A), +and I={i: abs(u_i)<1}. Define B=n*sum_I((x_i-M)**2* +(1-u_i**2)**4)/(sum_I((1-u_i**2)*(1-5*u_i**2)))**2. +Return sum((x-M)**2)/((n-1)*B). Contributions with abs(u)>=1 +are zero in both biweight sums. Zero MAD or a zero biweight +denominator makes the estimator undefined and raises ValueError. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Martinez, J. and Iglewicz, B. (1981). + A test for departure from normality based on a biweight estimator of scale. + Biometrika, 68(1), 331-333. + https://doi.org/10.1093/biomet/68.1.331 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( MartinezIglewiczNormalityGofStatistic, ) - -test_statistic = MartinezIglewiczNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = MartinezIglewiczNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/mathematical-validation.md b/docs/criteria/goodness-of-fit/normality/mathematical-validation.md new file mode 100644 index 00000000..abd353d9 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/mathematical-validation.md @@ -0,0 +1,358 @@ +# Mathematical verification of normality statistics + +Audit date: 2026-10-17. Scope: all **60 concrete classes** exported by +`statistics.goodness_of_fit.continuous.normal`, including the generated EDF +and frequency classes. The [catalog](index.md) lists the exact Python names, +storage codes, hypotheses and rejection tails. + +The audit checks implemented mathematical functionals, numerical behavior, +hypothesis contracts and documentation. It does **not** certify exact +finite-sample p-values, universal power or every historical author attribution. +In particular, eleven legacy classes (four Hosking, six graph and GLB) have +qualifications described below. They remain available under their existing names. + +## Findings and changes + +- No discrepancy was found between the implemented formulas and the independent + numerical definitions on the tested cases. For some legacy classes the + independently checked definition is the library's documented functional, + rather than a fully verified reconstruction of the original publication. +- Masked observations were silently converted to ordinary arrays by most normal + statistics, exposing the hidden values to the calculation. `_normal_sample` + now rejects observations with an active mask, consistent with frequency tests. +- The D’Agostino–Pearson page incorrectly documented `SkewNormalityGofStatistic`, + a signed skewness test. It now documents `DAPNormalityGofStatistic`, the sum + of squared skewness and kurtosis transforms, and its upper rejection tail. +- Fifteen generated criteria had no page. They now have separate pages with + formulas, examples, sources and fitted-normal calibration instructions. +- Scientific context was missing for Hosking, GLB and graph pages. References + have been added without claiming that related theory establishes their exact + local normality tests. Broken links to `normal-statistics-review.md` were + replaced by links to this report and the catalog. +- Generated class docstrings now distinguish fixed and fitted hypotheses and + include executable examples. Existing finite-sample normalizations, including + `10*Z_A-32`, have been retained. +- Storage lookup tests were updated to expect the configuration already included + by the current `DistributionKey` implementation; no storage algorithm changed. + +## Hypothesis and scale conventions + +Write `m_r = mean((x-mean(x))**r)`, `s0=sqrt(m2)`, +`s1=sqrt(n*m2/(n-1))`, and `z0=(x-mean(x))/s0`, `z1=(x-mean(x))/s1`. +Changing `ddof` changes a finite-sample statistic, even if the difference +vanishes asymptotically. The tests explicitly retain these distinctions. + +Only KS and CVM test a fully specified normal law; their `mean` and `var` must +be supplied, and `var` means variance. The other generated EDF and all frequency +criteria estimate the mean and **unbiased** variance on each sample. Thus +D+ and D− generated classes have a fitted hypothesis, whereas legacy two-sided +KS has a fixed hypothesis. Lilliefors is the fitted two-sided KS statistic. + +Fifty-two classes have a family hypothesis `{}`. For location-scale-invariant +settings their null can be simulated with N(0,1), repeating all fits. This +representative distribution does not fix parameters in the hypothesis. +Six graph classes instead fix variance and leave mean unknown. User-supplied +frequency bin edges are in original units and can break scale invariance. + +For fitted normal EDF tests, independent uniform CDF values cannot replace +refitted normal samples. Neither the known-CDF EDF tables nor the familiar +multinomial chi-square law can be transferred automatically. In particular, +`chi-square(k-3)` is not asserted for raw-data estimates with adaptive bins. +For two-tail tests simulate both quantiles; a signed statistic's null need not +be symmetric. Directional KS deviations are nonnegative and reject in the +**upper** tail. + +## Sources and level of verification + +The following primary texts were inspected where accessible: + +- [Zhang (2002), §§2–3](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf): EDF + functionals, including half-rank and quarter-rank corrections. KS here is D, + not the squared distance printed in §2.1. +- [Doornik and Hansen, author manuscript, appendix p.7](https://doornik.com/research/normal2.pdf): + skewness and conditional-kurtosis transformations; rounded printed examples + provide an external numerical check. The journal version is + [Doornik–Hansen (2008)](https://doi.org/10.1111/j.1468-0084.2008.00537.x). +- [Bonett and Seier (2002), equations (5)–(6)](https://sci2s.ugr.es/keel/pdf/specific/articulo/Normalidad4.pdf): + `ddof=0`, the factor `sqrt(n+2)` and the two-sided rule. This is the individual + Geary-kurtosis transform, not the paper's further combined test. +- [Bontemps and Meddahi (2005), §§2–3](https://www.olsendata.com/data_products/client_papers/papers/200409-BontempsMedahi-TestNormGMMApproach.pdf): + orthonormal Hermite moments. This implementation uses iid weighting and + `s1`; it does not implement the paper's HAC extension to dependent data. +- [Brys, Hubert and Struyf, author manuscript, §3 and Table 1](https://wis.kuleuven.be/stat/robust/papers/2008/Bryshubertstruyf-comp.pdf): + the MC-LR quadratic form. The library uses more digits in the constants than + the table prints; exact agreement with those additional digits is not claimed. +- [Cabaña and Cabaña (2003), author-posted full text](https://www.researchgate.net/publication/263579544_Tests_of_Normality_Based_on_Transformed_Empirical_Processes): + truncated Hermite processes, fixed truncation five and continuous supremum. +- [Desgagné, Lafaye de Micheaux and Leblanc (2013), author copy](https://www.biostatisticien.eu/textes/desgagne2013.pdf): + fitted-score approach. Independent quadrature verifies the implemented + score means and covariance projection, within the precision of rounded constants. +- [Lemeshko et al. (2014), equations (1)–(3), (6)](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf): + Kuiper normalizations and Watson centering. These equations alone do not + validate calibration after normal parameter fitting. + +Direct scientific references for all 60 statistics appear in the coverage +table below; their individual pages provide further bibliographic detail. A bibliographic link alone is not evidence of a line-by-line formula +check. Original full texts for several older methods were inaccessible; +those methods were checked against independent mathematical constructions or +external software, with approximations stated explicitly below. + +External software checks use the official SciPy definitions of +[Shapiro–Wilk](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.shapiro.html), +[skewness](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skewtest.html), +[kurtosis](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosistest.html) +and [Filliben plotting positions](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.html). +Agreement with a numerical implementation complements, but does not replace, +scientific attribution. + +## Formula-by-formula coverage + +Each row names one concrete statistic by its unique short code. Follow the +page link for its full formula and input restrictions. The scientific-source +column links directly to articles or technical reports. Where attribution is +unresolved, the column identifies related literature and its limits explicitly. +“Local” means that the mathematical functional is checked but its exact +published test/calibration has not been established. “Approximation” identifies +a finite-sample or numerical approximation; it is not an exact distributional claim. + +| Code and page | Definition checked / independent evidence | Qualification | Scientific source | +| --- | --- | --- | --- | +| [`BHS`](bhs_normality_criterion.md) | n times the MC/LMC/RMC quadratic form; exact enumeration of medcouple kernels and strict median halves | Rounded asymptotic covariance; ties use an explicit convention | [Brys, Hubert & Struyf (2008)](https://doi.org/10.1007/s00180-007-0083-7) | +| [`BS`](bonett_seier_normality_criterion.md) | sqrt(n+2)*(13.29*log(s0/mean(abs(x-mean(x))))-3)/3.54; original eqs. (5)–(6) | Geary-kurtosis component; both tails | [Bonett & Seier (2002)](https://doi.org/10.1016/S0167-9473(02)00074-9) | +| [`BM1`](bontemps_meddahi1_normality_criterion.md) | Sum of squared normalized Hermite means for orders 3–4; scipy.special evaluation | s1 finite-sample convention; iid only | [Bontemps & Meddahi (2005)](https://doi.org/10.1016/j.jeconom.2004.02.014) | +| [`BM2`](bontemps_meddahi2_normality_criterion.md) | Same construction for orders 3–6; scipy.special evaluation | s1 finite-sample convention; iid only | [Bontemps & Meddahi (2005)](https://doi.org/10.1016/j.jeconom.2004.02.014) | +| [`CC1`](cabana_cabana1_normality_criterion.md) | Continuous supremum of the skewness-focused Hermite process; scalar optimization versus polynomial roots | Truncation five; no claim of consistency against every alternative | [Cabaña & Cabaña (2003)](https://doi.org/10.1023/A:1026235220018) | +| [`CC2`](cabana_cabana2_normality_criterion.md) | Continuous supremum of the kurtosis-focused Hermite process; scalar optimization | Truncation five | [Cabaña & Cabaña (2003)](https://doi.org/10.1023/A:1026235220018) | +| [`CS`](chen_shapiro_normality_criterion.md) | sqrt(n)*(1-mean(normalized adjacent spacings)/s1) | Approximate normal scores | [Chen & Shapiro (1995)](https://doi.org/10.1080/00949659508811711) | +| [`COIN`](coin_normality_criterion.md) | Squared cubic OLS coefficient on normal order scores; independent order-density quadrature and least squares | Approximation: nscor2, 4<=n<=2000; original finite-sample implementation not fully certified | [Coin (2008)](https://doi.org/10.1016/j.csda.2007.07.012) | +| [`DAP`](dagostino_pearson_normality_criterion.md) | Z_skew²+Z_kurtosis²; scipy.stats.normaltest | Upper tail, not signed skewness | [D’Agostino & Pearson (1973)](https://doi.org/10.1093/biomet/60.3.613) | +| [`D`](dagostino_normality_criterion.md) | Normalized rank-weighted contrast; independent pairwise absolute-distance representation | Rounded asymptotic centering/scaling; both tails | [D’Agostino (1971)](https://doi.org/10.1093/biomet/58.2.341) | +| [`DLDMZEPD`](desgagne_lafaye_normality_criterion.md) | n*r.T*A*r; quadrature of score means, covariance and scale-score projection | Ill-conditioned matrix and rounded coefficients; rel tolerance 2e-4 | [Desgagné, Lafaye de Micheaux & Leblanc (2013)](https://doi.org/10.1080/03610926.2011.577548) | +| [`DH`](doornik_hansen_normality_criterion.md) | Squared transformed skewness plus conditional kurtosis; published appendix numerical example | n>=8; finite-sample chi-square approximation is not exact | [Doornik & Hansen (2008)](https://doi.org/10.1111/j.1468-0084.2008.00537.x) | +| [`EP`](epps_pulley_normality_criterion.md) | Gaussian-weighted empirical-characteristic-function distance; numerical integration | z0 standardization | [Epps & Pulley (1983)](https://doi.org/10.1093/biomet/70.3.723) | +| [`FILLI`](filliben_normality_criterion.md) | Correlation with approximate normal order medians; scipy.stats.probplot | Approximate plotting positions | [Filliben (1975)](https://doi.org/10.1080/00401706.1975.10489279) | +| [`GMG`](gmg_normality_criterion.md) | s0 divided by sqrt(pi/2)*mean(abs(x-median(x))) | Directed heavy-tail test; upper tail | [Gel, Miao & Gastwirth (2007)](https://doi.org/10.1016/j.csda.2006.08.022) | +| [`GLB`](glen_leemis_barr_normality_criterion.md) | Beta order-CDF transformation and reversed-weight logarithmic sum; binomial-tail identity | Local fitted-normal functional; exact author attribution unconfirmed | [Glen, Leemis & Barr (2001)](https://doi.org/10.1109/24.963129); exact attribution unconfirmed | +| [`AVGDEGREE`](graph_average_degree_normality_criterion.md) | mean degree; exhaustive graph construction/subset enumeration | Local radius range/(10*m2); known variance; both tails | [Ebner, Nestmann & Schulte](https://arxiv.org/abs/1812.08638): related uniformity research only; exact source not established | +| [`CLIQUENUMBER`](graph_clique_number_normality_criterion.md) | maximum clique size; exhaustive graph construction/subset enumeration | Local radius range/(10*m2); known variance; both tails | [Ebner, Nestmann & Schulte](https://arxiv.org/abs/1812.08638): related uniformity research only; exact source not established | +| [`CONNECTEDCOMPONENTS`](graph_connected_components_normality_criterion.md) | number of components; exhaustive graph construction/subset enumeration | Local radius range/(10*m2); known variance; both tails | [Ebner, Nestmann & Schulte](https://arxiv.org/abs/1812.08638): related uniformity research only; exact source not established | +| [`EDGESNUMBER`](graph_edges_number_normality_criterion.md) | edge count; exhaustive graph construction/subset enumeration | Local radius range/(10*m2); known variance; both tails | [Ebner, Nestmann & Schulte](https://arxiv.org/abs/1812.08638): related uniformity research only; exact source not established | +| [`INDEPENDENCENUMBER`](graph_independence_number_normality_criterion.md) | maximum independent-set size; exhaustive graph construction/subset enumeration | Local radius range/(10*m2); known variance; both tails | [Ebner, Nestmann & Schulte](https://arxiv.org/abs/1812.08638): related uniformity research only; exact source not established | +| [`MAXDEGREE`](graph_max_degree_normality_criterion.md) | maximum degree; exhaustive graph construction/subset enumeration | Local radius range/(10*m2); known variance; both tails | [Ebner, Nestmann & Schulte](https://arxiv.org/abs/1812.08638): related uniformity research only; exact source not established | +| [`HOSKING1`](hosking1_normality_criterion.md) | Quadratic ratios of L-moments with trim 0; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`HOSKING2`](hosking2_normality_criterion.md) | Quadratic ratios of L-moments with trim 1; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`HOSKING3`](hosking3_normality_criterion.md) | Quadratic ratios of L-moments with trim 2; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`HOSKING4`](hosking4_normality_criterion.md) | Quadratic ratios of L-moments with trim 3; exhaustive subsample order-statistic averaging | Local piecewise constants; no universal chi-square calibration | [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x); [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002): moment construction, not local calibration constants | +| [`JB`](jarque_bera_normality_criterion.md) | n*(skew²/6+excess_kurtosis²/24); scipy.stats.jarque_bera | Asymptotic calibration requires care at small n | [Jarque & Bera (1987)](https://doi.org/10.2307/1403192) | +| [`KURTOSIS`](kurtosis_normality_criterion.md) | Signed Anscombe–Glynn cube-root transform; scipy.stats.kurtosistest | n>=5; approximate calibration, especially below 20 | [Anscombe & Glynn (1983)](https://doi.org/10.1093/biomet/70.1.227) | +| [`LG`](looney_gulledge_normality_criterion.md) | Correlation with Blom normal scores; independent correlation matrix | Approximate plotting positions | [Looney & Gulledge (1985)](https://doi.org/10.1080/00031305.1985.10479395) | +| [`MI`](martinez_iglewicz_normality_criterion.md) | Classical median-centered scale divided by truncated biweight scale; direct outlier calculation | Positive MAD and nonzero biweight denominator required | [Martinez & Iglewicz (1981)](https://doi.org/10.1093/biomet/68.1.331) | +| [`RJB`](robust_jarque_bera_normality_criterion.md) | n*m3²/(6*J^6)+n*(m4/J^4-3)²/64; direct moments and median absolute deviations | Upper tail; J uses the median | [Gel & Gastwirth (2008)](https://doi.org/10.1016/j.econlet.2007.05.022) | +| [`RJ`](ryan_joiner_normality_criterion.md) | Normal-score correlation; independent plotting positions for every alpha and averaged tied ranks | Weighted/alpha options change calibration | [Ryan & Joiner (1976), technical report](https://www.additive-net.de/en/component/jdownloads/send/70-support/236-normal-probability-plots-and-tests-for-normality-thomas-a-ryan-jr-bryan-l-joiner) | +| [`SF`](sf_normality_criterion.md) | Squared Blom-score correlation | Approximation to expected normal order statistics | [Shapiro & Francia (1972)](https://doi.org/10.1080/01621459.1972.10481232); [Weisberg & Bingham (1975)](https://doi.org/10.1080/00401706.1975.10489283) | +| [`SWRG`](swrg_normality_criterion.md) | Normalized score contrast squared; inverse Brownian-bridge quantile covariance calculation | Approximate order-score covariance; lower tail | [Rahman & Govindarajulu (1997)](https://doi.org/10.1080/02664769723828) | +| [`SW`](shapiro_wilk_normality_criterion.md) | Royston approximation to Shapiro–Wilk W; SciPy at n=3,4,5,6,8,20,100,1000 | Coefficient approximation, not exact covariance inversion | [Shapiro & Wilk (1965)](https://doi.org/10.1093/biomet/52.3-4.591); [Royston (1995)](https://doi.org/10.2307/2986146) | +| [`SKEW`](skew_normality_criterion.md) | Signed D’Agostino transform; scipy.stats.skewtest and exact zero-skew regression | n>=8; both tails | [D’Agostino (1970)](https://doi.org/10.1093/biomet/57.3.679) | +| [`SH`](spiegelhalter_normality_criterion.md) | Power combination of standardized range and absolute deviations; direct powers versus log-space code | Documented symmetric-alternative functional; original full text not inspected | [Spiegelhalter (1977)](https://doi.org/10.1093/biomet/64.2.415) | +| [`ZQ`](zhang_q_normality_criterion.md) | log of mean endpoint spacings divided by mean lag-four spacings | n>=8; both tails; exact original text not inspected | [Zhang (1999)](https://doi.org/10.1080/02664769922395) | +| [`ZQS`](zhang_q_star_normality_criterion.md) | ZQ applied to the reflected sample; independent spacing expression | n>=8; both tails | [Zhang (1999)](https://doi.org/10.1080/02664769922395) | +| [`ZWA`](zhang_wu_a_normality_criterion.md) | 10*Zhang_A-32; density-quadrature CDF and independent rank sum | Historical affine normalization, n>=4 | [Zhang & Wu (2005)](https://doi.org/10.1016/j.csda.2004.05.034) | +| [`ZWC`](zhang_wu_c_normality_criterion.md) | Zhang_C log-odds discrepancy; independent rank sum | Same functional as generated Zhang C, n>=4 | [Zhang & Wu (2005)](https://doi.org/10.1016/j.csda.2004.05.034) | +| [`KS`](kolmogorov_smirnov_normality_criterion.md) | max(D+,D−) against specified normal CDF; scipy.stats.kstest in all directions | Fixed mean/variance, n>=1 | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256) | +| [`AD`](anderson_darling_normality_criterion.md) | Weighted EDF integral; density and EDF quadrature, using z1 | Fitted normal, no finite-sample multiplier | [Anderson & Darling (1954)](https://doi.org/10.1080/01621459.1954.10501232); [Stephens (1976)](https://doi.org/10.1214/aos/1176343411) | +| [`CVM`](cvm_normality_criterion.md) | Integral of squared EDF discrepancy; independent quadrature and scipy.stats.cramervonmises | Fixed normal; legacy full code CVM_GOODNESS_OF_FIT | [Cramér (1928)](https://doi.org/10.1080/03461238.1928.10416872) | +| [`LILLIE`](lilliefors_normality_criterion.md) | max(D+,D−) after mean/s1 fitting; independently refitted KS | Fitted-normal tables, not known-CDF KS tables | [Lilliefors (1967)](https://doi.org/10.1080/01621459.1967.10482916) | +| [`KS_PLUS`](kolmogorov_smirnov_d_plus_normality_criterion.md) | max(i/n-u_i); independent density quadrature | Fitted normal; upper rejection tail | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256); [Lilliefors (1967)](https://doi.org/10.1080/01621459.1967.10482916) (parameter-fitting context) | +| [`KS_MINUS`](kolmogorov_smirnov_d_minus_normality_criterion.md) | max(u_i-(i-1)/n); independent density quadrature | Fitted normal; upper rejection tail | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256); [Lilliefors (1967)](https://doi.org/10.1080/01621459.1967.10482916) (parameter-fitting context) | +| [`LIAO_SHIMOKAWA`](liao_shimokawa_normality_criterion.md) | Sum of local EDF maxima weighted by 1/sqrt(u*(1-u)*n) | Normal-family application of a general functional; original paper concerns other families | [Liao & Shimokawa (1999)](https://doi.org/10.1080/00949659908811965) | +| [`WATSON`](watson_normality_criterion.md) | Centered EDF squared integral | Fitted normal | [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109) | +| [`KUIPER`](kuiper_normality_criterion.md) | D++D− | Fitted normal, unscaled | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0) | +| [`KUIPER_SCALED`](kuiper_scaled_normality_criterion.md) | sqrt(n)*(D++D−) | Fitted normal | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014)](https://doi.org/10.3103/S875669901401004X) | +| [`KUIPER_CORRECTED`](kuiper_corrected_normality_criterion.md) | (sqrt(n)+0.155+0.24/sqrt(n))*(D++D−) | Normalization does not justify known-CDF calibration | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); [Lemeshko et al. (2014)](https://doi.org/10.3103/S875669901401004X) | +| [`ZHANG_ZK`](zhang_k_normality_criterion.md) | Maximum rank-weighted binary log-likelihood discrepancy | Fitted normal | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [`ZHANG_ZA`](zhang_a_normality_criterion.md) | Reciprocal-rank weighted logarithmic tails | Fitted normal; no 10*A-32 scaling | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [`ZHANG_ZC`](zhang_c_normality_criterion.md) | Squared log-odds discrepancies with quarter-rank correction | Fitted normal, n>=2 | [Zhang (2002)](https://doi.org/10.1111/1467-9868.00337) | +| [`CHI2_PEARSON`](chi2_pearson_normality_criterion.md) | Power divergence lambda=1; independent scipy.stats.power_divergence | Fitted mean/s1 and custom bins | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`FREEMAN_TUKEY`](freeman_tukey_normality_criterion.md) | Power divergence lambda=-1/2, including factor 4 | Fitted mean/s1 and custom bins | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`MODIFIED_LOG_LIKELIHOOD`](modified_log_likelihood_normality_criterion.md) | Power divergence lambda=-1; explicit empty-cell limit | Positive infinity at zero observed count | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`CHI2_NEYMAN`](neyman_chi2_normality_criterion.md) | Power divergence lambda=-2; explicit empty-cell limit | Positive infinity at zero observed count | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | +| [`CRESSIE_READ`](cressie_read_normality_criterion.md) | Power divergence lambda=2/3, including factor 9/5 | Zero counts contribute zero | [Cressie & Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x) | + +## Legacy definitions and unresolved scientific attribution + +**Hosking 1–4.** The L-moment and trimmed L-moment calculations agree with +exhaustive averaging of order-statistic combinations. The three historical +rows `(mu4,v3,v4)` for `n<=25`, `2550` are not an asymptotically +shrinking covariance sequence. Neither [Hosking (1990)](https://doi.org/10.1111/j.2517-6161.1990.tb01775.x) +nor [Hosking (2007)](https://doi.org/10.1016/j.jspi.2006.12.002) is claimed to +justify these exact rows. These are local discrepancies: simulate at the actual +sample size. No unsupported replacement constants were introduced. + +**Graph statistics.** Exhaustive small-graph checks establish their combinatorial +values. The sample-dependent radius `range/(10*m2)` changes as inverse scale, +while interpoint distances change as scale. Hence location invariance holds, +but scale invariance does not. Mean can be set to zero for simulation; variance +must match the hypothesis. No paper establishing this exact normality procedure +was located. [Ebner, Nestmann and Schulte](https://arxiv.org/abs/1812.08638) +is explicitly cited as related graph-testing research about **uniformity**, not +as provenance for these six normality tests. + +**GLB.** The fitted beta transformation and reversed logarithmic weights are +reproduced using binomial probabilities. This does not make the expression the +ordinary Anderson–Darling statistic. The [Glen–Leemis–Barr paper](https://doi.org/10.1109/24.963129) +was identified, but the primary full text was inaccessible. Its exact equality +to this fitted-normal implementation remains unconfirmed. Use simulation of the +implemented functional, not an assumed GLB table. + +**Approximations and directed tests.** Coin's regression is checked against +quadrature of expected normal order statistics, with tolerance reflecting its +`nscor2` approximation. Bonett–Seier is a kurtosis component; GMG is directed +against heavy tails. Fixed-order Hermite and moment tests are not proved +consistent against every nonnormal alternative by this audit. A finite value +or Monte Carlo calibration alone does not establish omnibus power. + +## Numerical verification and reproducibility + +Result: **1495 tests passed** in the isolated focused run. Ruff checks passed. +`mkdocs build --site-dir /tmp/pysatl-normal-docs-audit` succeeded; its warnings +concern existing broken links outside the normality section. All normality +pages, examples, catalog entries and local links passed the dedicated checks. + +The focused suite consists of: + +- `tests/distributions/test_normal.py` +- `tests/distributions/test_normal_parameters.py` +- `tests/distributions/test_normal_hypotheses.py` +- `tests/distributions/test_normal_correctness.py` +- `tests/distributions/test_normal_mathematical_validation.py` +- `tests/distributions/test_normal_documentation.py` +- `tests/statistics/test_normal_dynamic.py` +- `tests/statistics/test_normal_numba.py` +- `tests/statistics/test_normal_stub.py` + +The new numerical references do not call the production EDF/frequency kernels. +They integrate the normal density and EDF discrepancies, use SciPy multinomial +power divergences, calculate score correlations and robust scales, invert a +quantile covariance matrix, and integrate order-statistic densities. Existing +checks independently optimize the Cabaña supremum, enumerate trimmed L-moments, +check all six graph functionals and integrate the fitted-score covariance. + +Cases include normal and skewed samples, repeated values, symmetric samples, +small-size boundaries, refitting across calls, nonmutation, invalid and masked +data, signed tails, and positive affine transformations. Location-scale-invariant +family cases are tested at scales `1e-250` and `1e250`; graph statistics and +fixed-boundary binning are not incorrectly required to have this invariance. +Neyman and modified likelihood legitimately return infinity at empty observed +cells with positive expected probability. Extremely small probabilities may +still be limited by floating-point representability. + +EDF comparisons use `rel=2e-9, abs=2e-10`; SciPy Shapiro comparisons use +`abs=2e-8`; the Coin approximation uses `rel=3e-3, abs=1e-6`; the rounded +Desgagné covariance comparison uses `rel=2e-4`. These are bounds for the checked +cases, not global error guarantees. + +Ordinary pytest collection is currently blocked by the pre-existing import of +`AbstractChi2Statistic` from `edf.py` in `inverse_gamma.py`. Focused verification +loads the real normal, EDF, frequency, distribution and binning modules while +bypassing only the unrelated `continuous/__init__.py` import aggregator. This +is not evidence that package initialization is healthy. To reproduce that run +from the repository root: + +```sh +.venv/bin/python - <<'PY' +import sys +import types +from pathlib import Path +import pytest + +name = "pysatl_criterion.statistics.goodness_of_fit.continuous" +package = types.ModuleType(name) +package.__path__ = [str(Path("src/pysatl_criterion/statistics/goodness_of_fit/continuous").resolve())] +sys.modules[name] = package +raise SystemExit(pytest.main([ + "tests/distributions/test_normal.py", + "tests/distributions/test_normal_parameters.py", + "tests/distributions/test_normal_hypotheses.py", + "tests/distributions/test_normal_correctness.py", + "tests/distributions/test_normal_mathematical_validation.py", + "tests/distributions/test_normal_documentation.py", + "tests/statistics/test_normal_dynamic.py", + "tests/statistics/test_normal_numba.py", + "tests/statistics/test_normal_stub.py", "-q", +])) +PY +``` + +## Numba optimization verification + +Numerical kernels use static class methods decorated with +`@jit(nopython=True, cache=True)`, without fast-math reassociation. The public +entry points retain input validation and stable rescaling. All 60 criteria +reach compiled kernels; generated EDF and frequency criteria reuse their +existing common kernels. Normal quantiles and beta/log-tail functions remain +in SciPy, and Cabaña polynomial root finding remains in NumPy. Compiling a +reduction does not mean the entire public call is compiled. + +The 128 additional checks in `test_normal_numba.py` exercise every public path +on continuous and tied data, require actual nopython signatures and disk-cache +configuration, and compare compiled results with the Python kernel bodies. +They also check large Hosking combination weights and strict graph-radius +boundaries against explicit graph calculations. Independent formula checks +listed above remain the mathematical reference. Baseline comparisons before +and after optimization also passed on normal samples of sizes 12, 100 and 1000 +for all 39 explicitly implemented statistics (`rtol=2e-8`, `atol=2e-9`). + +Graph statistics now use sorted scans instead of constructing adjacency lists; +the strict edge condition remains `abs(x_i-x_j) < radius`. BHS uses one flat +medcouple-kernel array instead of multiple broadcast matrices, preserving its +tie convention. Hosking uses floating-point low-order combination products to +avoid fixed-width integer overflow. Coin and Shapiro–Wilk evaluate quantiles +in batches, and Cabaña reuses its fixed polynomial basis. + +A local warmed benchmark used the public API, `n=200`, seed 123 and the minimum +of three batches of ten calls, comparing against the pre-optimization source. +Observed speedups were approximately 9× for Epps–Pulley, 13–15× for Hosking +2–4, 15× for Jarque–Bera, 41× for Coin and 89× for Shapiro–Wilk. The four graph +statistics that previously built adjacency lists improved by about 186–222×. +GLB was essentially unchanged (0.98×), since SciPy beta tails dominate it. +These are local measurements, not performance guarantees; compilation/cache +loading is excluded from these speedup ratios. + +To measure first-call and warmed execution separately for all 60 criteria: + +```sh +PYTHONPATH=src .venv/bin/python benchmarks/benchmark_normal_pipeline.py --isolated-imports +``` + +The explicit isolation flag bypasses the unrelated package-import failure +described above. Once that failure is fixed, omit the flag. First-call timings +include compilation or disk-cache loading, depending on the cache state. + +## Package layout and compatibility + +Like `continuous/uniform`, the normality implementation is a package: + +- `continuous/normal/normal_statistics.py` contains the statistics and factories. +- `continuous/normal/__init__.py` explicitly re-exports the 60 concrete classes + and two abstract bases, retaining their public `continuous.normal` identities. +- `continuous/normal/__init__.pyi` describes the complete public interface. + +Existing `from ...continuous.normal import ...` imports and pickle references +retain their paths. The 65 stub/package checks cover exports, method signatures, +class identity, old pickle references and unique criterion discovery. Generate +and verify the package stub with `scripts/generate_normal_stub.py` and its +`--check` option; generation reads the source without importing the package. +Mypy checking of the stub passed with `--follow-imports=silent`. + +## Documentation coverage + +The catalog and navigation contain all 60 classes, with exactly one individual +page per class, plus the catalog and this report. Tests compare class names, +codes and exports with documentation, require examples and scientific links, +execute every Python example and check local Markdown links. This catches a +page accidentally documenting a different criterion, as happened with DAP. +All concrete class docstrings include references and executable examples. + +An available related scientific link is explicitly distinguished from a source +that validates the exact implementation. The unresolved attribution of the +legacy methods above is part of the result, not concealed by coverage checks. diff --git a/docs/criteria/goodness-of-fit/normality/modified_log_likelihood_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/modified_log_likelihood_normality_criterion.md new file mode 100644 index 00000000..a9f59138 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/modified_log_likelihood_normality_criterion.md @@ -0,0 +1,54 @@ +# Modified log likelihood for normality + +**Class:** `ModifiedLogLikelihoodNormalityGofStatistic` + +**Code:** `MODIFIED_LOG_LIKELIHOOD_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +Let `O_j` be the observed count and `E_j=n*p_j>0` the fitted expected count. + +`2 Σ E_j log(E_j/O_j)`. If `O_j=00` the fitted expected count. + +`Σ (O_j-E_j)²/O_j`. If `O_j=00; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Robust Jarque-Bera statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Let J=sqrt(pi/2)*mean(abs(x-median(x))). Return +n*(m3/J**3)**2/6 + n*(m4/J**4-3)**2/64. +Moments are centered at the sample mean, whereas J uses the median. +The reference identifies this robust-scale modification; small-sample +chi-square calibration is not justified. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Gel, Y. R. and Gastwirth, J. L. (2008). + A robust modification of the Jarque-Bera test of normality. + Economics Letters, 99(1), 30-32. + https://doi.org/10.1016/j.econlet.2007.05.022 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( RobustJarqueBeraNormalityGofStatistic, ) - -test_statistic = RobustJarqueBeraNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = RobustJarqueBeraNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/ryan_joiner_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/ryan_joiner_normality_criterion.md index 31edf83c..6c8fb763 100644 --- a/docs/criteria/goodness-of-fit/normality/ryan_joiner_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/ryan_joiner_normality_criterion.md @@ -1,55 +1,73 @@ # Ryan-Joiner test for normality -## Description -Performs the Ryan-Joiner goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `RyanJoinerNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `RJ_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on the correlation between ordered observations and expected normal scores. +Ryan-Joiner probability-plot correlation statistic for normality. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - RyanJoinerNormalityGofStatistic, -) +## Parameters - -test_statistic = RyanJoinerNormalityGofStatistic(weighted=False, cte_alpha="3/8") -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```text +parameters : ParameterValues + An empty distribution schema; all distribution parameters are unknown. +weighted : bool, optional + If True, average the plotting probabilities within each group of + tied observations before applying the normal quantile function. + Default is False. +cte_alpha : {'3/8', '1/2', '0'}, optional + Plotting-position constant ``a`` in ``(i-a)/(n-2*a+1)`` for one-based + ranks. Default is ``'3/8'``. Unrecognized values currently fall back + to ``3/8``. ``` -## Arguments -`weighted` - whether tied observations use grouped plotting positions. Default value is `False`. +## Methods -`cte_alpha` - plotting-position constant. Supported values include `3/8`, `1/2`, and `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`rvs` - array-like sample data passed to `execute_statistic`. +## Notes -## Details -The implementation evaluates the Ryan-Joiner statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. + +Return corr(x_(i), Phi**-1(p_i)), p_i=(i-alpha)/(n+1-2*alpha). +cte_alpha selects alpha=0, 3/8, or 1/2. If weighted=True, replace +positions of tied observations by their group mean before taking +normal quantiles. This tie convention and nondefault positions need +separate calibration; they are not fixed distribution parameters. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Ryan, T. A., Jr. and Joiner, B. L. (1976). Normal Probability + Plots and Tests for Normality. Technical report, Statistics + Department, The Pennsylvania State University. Original report: + https://www.additive-net.de/en/component/jdownloads/send/70-support/236-normal-probability-plots-and-tests-for-normality-thomas-a-ryan-jr-bryan-l-joiner ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( RyanJoinerNormalityGofStatistic, ) - -test_statistic = RyanJoinerNormalityGofStatistic(weighted=False, cte_alpha="3/8") -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = RyanJoinerNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/sf_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/sf_normality_criterion.md index 243500ee..3a97c792 100644 --- a/docs/criteria/goodness-of-fit/normality/sf_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/sf_normality_criterion.md @@ -1,55 +1,58 @@ # SF test for normality -## Description -Performs the SF goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `SFNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `SF_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a Shapiro-Francia-style statistic based on expected normal scores. +Shapiro-Francia ``W_prime`` statistic for the normal family. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SFNormalityGofStatistic, -) - - -test_statistic = SFNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Methods -## Arguments -`mean` - reference normal mean. Default value is `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`var` - reference normal variance. Default value is `1`. +## Notes -`rvs` - array-like sample data passed to `execute_statistic`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Details -The implementation evaluates the SF statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return corr(x_(i), Phi**-1((i-3/8)/(n+1/4)))**2. +This Shapiro-Francia approximation uses Blom scores in place of +exact expected normal order statistics. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Shapiro, S. S. and Francia, R. S. (1972). An Approximate + Analysis of Variance Test for Normality. Journal of the American + Statistical Association, 67(337), 215-216. + https://doi.org/10.1080/01621459.1972.10481232 +[2] Weisberg, S. and Bingham, C. (1975). An Approximate Analysis of + Variance Test for Non-Normality Suitable for Machine Calculation. + Technometrics, 17(1), 133-134. + https://doi.org/10.1080/00401706.1975.10489283 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SFNormalityGofStatistic, -) - -test_statistic = SFNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import SFNormalityGofStatistic + +statistic = SFNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/shapiro_wilk_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/shapiro_wilk_normality_criterion.md index dca4716f..7624b372 100644 --- a/docs/criteria/goodness-of-fit/normality/shapiro_wilk_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/shapiro_wilk_normality_criterion.md @@ -1,55 +1,59 @@ # Shapiro-Wilk test for normality -## Description -Performs the Shapiro-Wilk goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `ShapiroWilkNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `SW_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a squared correlation-like statistic based on ordered observations and normal order statistic weights. +Shapiro-Wilk ``W`` statistic for the normal location-scale family. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ShapiroWilkNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = ShapiroWilkNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 3 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Shapiro-Wilk statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +W = (sum(a_i*x_(i)))**2 / sum((x-mean(x))**2). +The normalized symmetric weights use the Royston polynomial +approximation, with the exact three-observation weights. This is a +weight approximation to Shapiro-Wilk, not exact covariance inversion. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Shapiro, S. S. and Wilk, M. B. (1965). An analysis of variance + test for normality (complete samples). Biometrika, 52(3-4), 591-611. + https://doi.org/10.1093/biomet/52.3-4.591 +[2] Royston, P. (1995). Remark AS R94: A Remark on Algorithm AS 181: + The W-test for Normality. Applied Statistics, 44(4), 547-551. + https://doi.org/10.2307/2986146 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( ShapiroWilkNormalityGofStatistic, ) - -test_statistic = ShapiroWilkNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = ShapiroWilkNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/skew_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/skew_normality_criterion.md index 2177a1f8..ee68c5c9 100644 --- a/docs/criteria/goodness-of-fit/normality/skew_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/skew_normality_criterion.md @@ -1,55 +1,54 @@ # Skewness test for normality -## Description -Performs the Skewness goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `SkewNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `SKEW_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on a transformed sample skewness statistic. +D'Agostino transformed-skewness statistic for the normal family. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SkewNormalityGofStatistic, -) - - -test_statistic = SkewNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Methods -## Arguments -`mean` - reference normal mean. Default value is `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`var` - reference normal variance. Default value is `1`. +## Notes -`rvs` - array-like sample data passed to `execute_statistic`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Details -The implementation evaluates the Skewness statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return the signed D'Agostino transform delta*asinh(y/alpha) of +g1=m3/m2**1.5, with the sample-size coefficients in skew_test. +In particular, exactly zero sample skewness maps to zero. This tests +skewness departures in either direction; it is not an omnibus test. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] D'Agostino, R. B. (1970). Transformation to normality of the null + distribution of g1. Biometrika, 57(3), 679-681. + https://doi.org/10.1093/biomet/57.3.679 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SkewNormalityGofStatistic, -) - -test_statistic = SkewNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import SkewNormalityGofStatistic + +statistic = SkewNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/spiegelhalter_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/spiegelhalter_normality_criterion.md index 9f392e5f..2e5fdc8f 100644 --- a/docs/criteria/goodness-of-fit/normality/spiegelhalter_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/spiegelhalter_normality_criterion.md @@ -1,55 +1,61 @@ # Spiegelhalter test for normality -## Description -Performs the Spiegelhalter goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `SpiegelhalterNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `SH_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on sample range, mean absolute deviation, and sample variance. +Spiegelhalter statistic for the normal family. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SpiegelhalterNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = SpiegelhalterNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Details -The implementation evaluates the Spiegelhalter statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Let U=(max(x)-min(x))/s1, G=sum(abs(x-mean(x)))/ +(s1*sqrt(n*(n-1))), and c_n=Gamma(n+1)**(1/(n-1))/(2*n). +Return ((c_n*U)**(-(n-1))+G**(-(n-1)))**(1/(n-1)). +Log-gamma and logaddexp evaluate this expression without overflowing. +Both critical tails are retained; the full primary formula and +its tail convention could not be independently checked in this review. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Spiegelhalter, D. J. (1977). "A test for normality against + symmetric alternatives." Biometrika, 64(2), 415-418. + https://doi.org/10.1093/biomet/64.2.415 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( SpiegelhalterNormalityGofStatistic, ) - -test_statistic = SpiegelhalterNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = SpiegelhalterNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/swrg_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/swrg_normality_criterion.md index 69ae13ff..940701e2 100644 --- a/docs/criteria/goodness-of-fit/normality/swrg_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/swrg_normality_criterion.md @@ -1,55 +1,56 @@ # SWRG test for normality -## Description -Performs the SWRG goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `SWRGNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `SWRG_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on weights derived from normal quantiles and density values. +Rahman-Govindarajulu modification of the Shapiro-Wilk statistic. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SWRGNormalityGofStatistic, -) - - -test_statistic = SWRGNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` +## Methods -## Arguments -`mean` - reference normal mean. Default value is `0`. +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -`var` - reference normal variance. Default value is `1`. +## Notes -`rvs` - array-like sample data passed to `execute_statistic`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +The lower tail of the statistic defines rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -## Details -The implementation evaluates the SWRG statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +For m_i=Phi**-1(i/(n+1)), f_i=phi(m_i), form weights +a*_i=-(n+1)*(n+2)*f_i*(m_(i-1)*f_(i-1)-2*m_i*f_i ++m_(i+1)*f_(i+1)), taking missing endpoint terms as zero. +Normalize a=a*/sqrt(sum(a* **2)); return +(sum(a_i*x_(i)))**2/sum((x-mean(x))**2). Small W_RG rejects. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Rahman, M. M. and Govindarajulu, Z. (1997). + A modification of the test of Shapiro and Wilk for normality. + Journal of Applied Statistics, 24(2), 219-236. + https://doi.org/10.1080/02664769723828 ## Examples -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - SWRGNormalityGofStatistic, -) - -test_statistic = SWRGNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import SWRGNormalityGofStatistic + +statistic = SWRGNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/watson_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/watson_normality_criterion.md new file mode 100644 index 00000000..f16dfbde --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/watson_normality_criterion.md @@ -0,0 +1,50 @@ +# Watson for normality + +**Class:** `WatsonNormalityGofStatistic` + +**Code:** `WATSON_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`U² = 1/(12n) + Σ(d_i-mean(d))²`, where `d_i=u_i-(i-1/2)/n`. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Watson (1961), Goodness-of-fit tests on a circle](https://doi.org/10.1093/biomet/48.1-2.109). + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + WatsonNormalityGofStatistic, +) +import numpy as np + +statistic = WatsonNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_a_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_a_normality_criterion.md new file mode 100644 index 00000000..6516a07f --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/zhang_a_normality_criterion.md @@ -0,0 +1,50 @@ +# Zhang A for normality + +**Class:** `ZhangANormalityGofStatistic` + +**Code:** `ZHANG_ZA_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`-Σ[log(u_i)/(n-i+1/2) + log(1-u_i)/(i-1/2)]`. The historical Zhang–Wu A class returns `10*A-32`; these are different numerical normalizations. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). The formula is an EDF functional; its application here refits normal parameters. + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + ZhangANormalityGofStatistic, +) +import numpy as np + +statistic = ZhangANormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_c_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_c_normality_criterion.md new file mode 100644 index 00000000..ed29ae7f --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/zhang_c_normality_criterion.md @@ -0,0 +1,50 @@ +# Zhang C for normality + +**Class:** `ZhangCNormalityGofStatistic` + +**Code:** `ZHANG_ZC_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`Σ[log((1-u_i)/u_i) - log((n-i+1/4)/(i-3/4))]²`. Zhang–Wu C uses the same expression with a stricter minimum sample size. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). The formula is an EDF functional; its application here refits normal parameters. + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + ZhangCNormalityGofStatistic, +) +import numpy as np + +statistic = ZhangCNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_k_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_k_normality_criterion.md new file mode 100644 index 00000000..a5595906 --- /dev/null +++ b/docs/criteria/goodness-of-fit/normality/zhang_k_normality_criterion.md @@ -0,0 +1,50 @@ +# Zhang K for normality + +**Class:** `ZhangKNormalityGofStatistic` + +**Code:** `ZHANG_ZK_NORMALITY_GOODNESS_OF_FIT` + +## Hypothesis and input + +H0 is the normal family with unknown mean and positive variance. Pass +`NormalDistributionDescriptor.DEFAULT.parse({})`. Both parameters are fitted on +every sample; the variance estimator uses `ddof=1`. At least two real, finite, +unmasked, one-dimensional observations with nonzero dispersion are required. +Ties are accepted. The sample is not modified and no fit is retained. +Large values reject H0. Calibration repeats fitting on each simulated sample. + +## Formula + +For ordered data, let `z_i=(x_(i)-mean(x))/s1`, `s1=std(x, ddof=1)`, +`u_i=Phi(z_i)`, `D+=max(i/n-u_i)`, and `D−=max(u_i-(i-1)/n)`. + +`max_i [(i-1/2) log((i-1/2)/(n*u_i)) + (n-i+1/2) log((n-i+1/2)/(n*(1-u_i)))]`. + +## Numerical details + +Inputs are sorted without mutation. Logarithmic kernels use direct normal +log-CDF and log-SF; no clipping of tail probabilities is used. A fitted EDF +statistic needs its own simulation calibration. Knowing the algebraic formula +does not justify using fully specified-distribution tables. + +## References + +[Zhang (2002), Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337). The formula is an EDF functional; its application here refits normal parameters. + +## Examples + +```python +from pysatl_criterion.distribution import NormalDistributionDescriptor +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( + ZhangKNormalityGofStatistic, +) +import numpy as np + +statistic = ZhangKNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) +assert statistic.hypothesis().parameters() == {} +``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_q_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_q_normality_criterion.md index 2c08e9a7..06817330 100644 --- a/docs/criteria/goodness-of-fit/normality/zhang_q_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/zhang_q_normality_criterion.md @@ -1,55 +1,63 @@ # Zhang Q test for normality -## Description -Performs the Zhang Q goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `ZhangQNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `ZQ_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on linear combinations of ordered observations with normal-score weights. +Zhang normality statistic based on a ratio of ordered-sample contrasts. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangQNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = ZhangQNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Details -The implementation evaluates the Zhang Q statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +For u_i=Phi**-1((i-3/8)/(n+1/4)), set +q1=mean_{i=2..n}((x_(i)-x_(1))/(u_i-u_1)), +q2=mean_{i=1..n-4}((x_(i+4)-x_(i))/(u_(i+4)-u_i)). +Return log(q1)-log(q2). The four-spacing construction and Blom +approximation are explicit implementation choices. Both contrasts +must be positive. Both critical tails are used for the signed log ratio; +this is the Q component, not a combined Q/Q* p-value procedure. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Zhang, P. (1999). + Omnibus test of normality using the Q statistic. + Journal of Applied Statistics, 26(4), 519-528. + https://doi.org/10.1080/02664769922395 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( ZhangQNormalityGofStatistic, ) - -test_statistic = ZhangQNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = ZhangQNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_q_star_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_q_star_normality_criterion.md index 84533859..152f0fe2 100644 --- a/docs/criteria/goodness-of-fit/normality/zhang_q_star_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/zhang_q_star_normality_criterion.md @@ -1,55 +1,61 @@ # Zhang Q-star test for normality -## Description -Performs the Zhang Q-star goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `ZhangQStarNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `ZQS_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on reversed ordered observations and normal-score weight vectors. +Reflected Zhang ``Q*`` normality statistic. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangQStarNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = ZhangQStarNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Both tails of the statistic define rejection. Use at least 8 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. +The publication was identified, but the exact finite-sample +implementation is not fully certified against its primary text. -## Details -The implementation evaluates the Zhang Q-star statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +Return Zhang Q evaluated on the reflected sample -x, using +u_i=Phi**-1((i-3/8)/(n+1/4)), the mean spacing from the minimum +for q1 and mean four-spacing for q2; return log(q1)-log(q2). +Both contrasts must be positive. Both tails of the signed log ratio +are used. This is a reflected component, not combined Q/Q* inference. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Zhang, P. (1999). + Omnibus test of normality using the Q statistic. + Journal of Applied Statistics, 26(4), 519-528. + https://doi.org/10.1080/02664769922395 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( ZhangQStarNormalityGofStatistic, ) - -test_statistic = ZhangQStarNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = ZhangQStarNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_wu_a_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_wu_a_normality_criterion.md index 694129b9..ea8b9e3b 100644 --- a/docs/criteria/goodness-of-fit/normality/zhang_wu_a_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/zhang_wu_a_normality_criterion.md @@ -1,55 +1,57 @@ # Zhang-Wu A test for normality -## Description -Performs the Zhang-Wu A goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `ZhangWuANormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `ZWA_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on weighted logarithms of fitted normal distribution values and survival values. +Zhang-Wu likelihood-ratio normality statistic ``Z_A``. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangWuANormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = ZhangWuANormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Zhang-Wu A statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +For z=(x-mean(x))/s1, let A=-sum_i(log(Phi(z_(i)))/ +(n-i+1/2) + log(1-Phi(z_(i)))/(i-1/2)). Return 10*A-32. +The historical affine scaling is retained and must also be used in +calibration. Logs are evaluated without first rounding normal CDFs. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Zhang, J. and Wu, Y. (2005). + Likelihood-ratio tests for normality. + Computational Statistics & Data Analysis, 49(3), 709-721. + https://doi.org/10.1016/j.csda.2004.05.034 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( ZhangWuANormalityGofStatistic, ) - -test_statistic = ZhangWuANormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = ZhangWuANormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/normality/zhang_wu_c_normality_criterion.md b/docs/criteria/goodness-of-fit/normality/zhang_wu_c_normality_criterion.md index ee794c46..162c7bb8 100644 --- a/docs/criteria/goodness-of-fit/normality/zhang_wu_c_normality_criterion.md +++ b/docs/criteria/goodness-of-fit/normality/zhang_wu_c_normality_criterion.md @@ -1,55 +1,56 @@ # Zhang-Wu C test for normality -## Description -Performs the Zhang-Wu C goodness-of-fit test for the hypothesis of normality. -The null hypothesis is that the sample comes from a normal distribution. +**Class:** `ZhangWuCNormalityGofStatistic` -Hypothesis of Normality -The hypothesis of normality refers to the null hypothesis that the data comes from a normal distribution. In the implementation, the statistic is computed from the sample passed to `execute_statistic`. +**Code:** `ZWC_NORMALITY_GOODNESS_OF_FIT` -Test Statistic -The statistic is based on log-ratio transformations of fitted normal distribution values. +Zhang-Wu likelihood-ratio normality statistic ``Z_C``. -## Usage -```python -from pysatl_criterion.statistics.goodness_of_fit import ( - ZhangWuCNormalityGofStatistic, -) +## Methods +execute_statistic(rvs, **kwargs) + Return one scalar statistic. +hypothesis() + Report fixed null parameters only. +alternative() + Report the critical tail. -test_statistic = ZhangWuCNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) -``` - -## Arguments -`mean` - reference normal mean. Default value is `0`. +## Notes -`var` - reference normal variance. Default value is `1`. +H0 is N(mu,sigma**2), with unknown real mu and sigma>0; hypothesis() reports {}. +Location and positive scale cancel, allowing N(0,1) null simulation. +Every simulated sample must go through execute_statistic again. +Large values of the statistic define rejection. Use at least 4 +finite real observations in one dimension. Nonzero dispersion is required. +Ties are accepted unless a scale or contrast becomes undefined. +Write x_(i) for ascending observations (i=1,...,n), Phi and phi for +the standard normal CDF and density, s0=std(x,ddof=0), and +s1=std(x,ddof=1). Calculations do not modify the sample or retain fits. -`rvs` - array-like sample data passed to `execute_statistic`. - -## Details -The implementation evaluates the Zhang-Wu C statistic for the supplied observations. Large or small values should be interpreted according to the statistic alternative used by the class implementation. +For z=(x-mean(x))/s1, return sum_i((log((1-Phi(z_(i)))/ +Phi(z_(i))) - log((n-i+1/4)/(i-3/4)))**2). +Normal log-CDF/log-survival evaluations retain extreme tail information. ## References -The statistic follows the implementation in `pysatl_criterion.statistics.goodness_of_fit.normal`. -## Author(s) -Alexey Mironov +[1] Zhang, J. and Wu, Y. (2005). + Likelihood-ratio tests for normality. + Computational Statistics & Data Analysis, 49(3), 709-721. + https://doi.org/10.1016/j.csda.2004.05.034 ## Examples + ```python -from pysatl_criterion.statistics.goodness_of_fit import ( +from pysatl_criterion.distribution import NormalDistributionDescriptor +import numpy as np +from pysatl_criterion.statistics.goodness_of_fit.continuous.normal import ( ZhangWuCNormalityGofStatistic, ) - -test_statistic = ZhangWuCNormalityGofStatistic() -statistic_result = test_statistic.execute_statistic( - [-1.21, -0.83, -0.52, -0.31, -0.08, 0.14, 0.29, 0.47, 0.68, 0.91, 1.16, 1.43] -) -print(statistic_result) +statistic = ZhangWuCNormalityGofStatistic(NormalDistributionDescriptor.DEFAULT.parse({})) +sample = [-1.7, -1.2, -0.9, -0.6, -0.3, -0.1, 0.2, 0.4, 0.7, 1.0, 1.4, 2.1] +value = statistic.execute_statistic(sample) +assert np.isfinite(value) ``` + +See the [complete catalog](index.md) and [mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/anderson_darling_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/anderson_darling_pareto_criterion.md new file mode 100644 index 00000000..ac02045e --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/anderson_darling_pareto_criterion.md @@ -0,0 +1,50 @@ +# Anderson–Darling for Pareto I + +Public class: `AndersonDarlingParetoGofStatistic`. Full code: `AD_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +A^2=-n-\frac1n\sum_{i=1}^n(2i-1)[\log u_i+\log(1-u_{n+1-i})]. +$$ + +No finite-sample correction is applied. An observation at the lower endpoint gives positive infinity. Log probabilities preserve finite upper-tail contributions when the CDF rounds to one. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + AndersonDarlingParetoGofStatistic, +) + +statistic = AndersonDarlingParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Anderson and Darling (1952), Asymptotic Theory of Certain Goodness of Fit Criteria Based on Stochastic Processes](https://doi.org/10.1214/aoms/1177729437). Computational form: [Zhang (2002), §§2–3, Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337); [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/chi2_pearson_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/chi2_pearson_pareto_criterion.md new file mode 100644 index 00000000..2a983c32 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/chi2_pearson_pareto_criterion.md @@ -0,0 +1,58 @@ +# Pearson chi-square for Pareto I + +Public class: `Chi2PearsonParetoGofStatistic`. Full code: `CHI2_PEARSON_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For full-support edges $b_0,\ldots,b_k$, let $O_j$ be the observed counts and +$E_j=n[F(b_j)-F(b_{j-1})]$. Expected counts must be positive and totals must agree. + +$$ +X^2=\sum_j\frac{(O_j-E_j)^2}{E_j}. +$$ + +Power-divergence parameter $\lambda=1$. A zero observed count contributes $E_j$. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Binning and calibration + +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`. +It counts transformed values in equal-probability cells and sets $E_j=n/k$. +There must be at least two retained cells. See [binning](../binning/index.md). +For fixed cells and large expected counts, the usual asymptotic reference is +$\chi^2_{k-1}$; this is not an exact small-sample calibration. Sparse cells, +merging and adaptive rules require calibration reproducing the same policy. +Binning settings are included in `configuration()`. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + Chi2PearsonParetoGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import ExplicitBins + +statistic = Chi2PearsonParetoGofStatistic( + Pareto.DEFAULT.parse({"shape": 2, "scale": 1}), + binning=ExplicitBins((1, 1.5, 3, float("inf"))), +) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Pearson (1900), On the criterion that a given system of deviations from the probable ...](https://doi.org/10.1080/14786440009463897). [Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). The formula is the corresponding member of their power-divergence family. + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/cramer_von_mises_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/cramer_von_mises_pareto_criterion.md new file mode 100644 index 00000000..7841639e --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/cramer_von_mises_pareto_criterion.md @@ -0,0 +1,50 @@ +# Cramér–von Mises for Pareto I + +Public class: `CramerVonMisesParetoGofStatistic`. Full code: `CVM_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +W^2=\frac{1}{12n}+\sum_{i=1}^n\left(u_i-\frac{i-1/2}{n}\right)^2. +$$ + +No parameter fitting or finite-sample correction is applied. Values at the lower endpoint are permitted and give finite statistics. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + CramerVonMisesParetoGofStatistic, +) + +statistic = CramerVonMisesParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Zhang (2002), §§2–3, Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337); [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/cressie_read_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/cressie_read_pareto_criterion.md new file mode 100644 index 00000000..c5d2526d --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/cressie_read_pareto_criterion.md @@ -0,0 +1,58 @@ +# Cressie–Read for Pareto I + +Public class: `CressieReadParetoGofStatistic`. Full code: `CRESSIE_READ_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For full-support edges $b_0,\ldots,b_k$, let $O_j$ be the observed counts and +$E_j=n[F(b_j)-F(b_{j-1})]$. Expected counts must be positive and totals must agree. + +$$ +T=\frac95\sum_j O_j\left[(O_j/E_j)^{2/3}-1\right]. +$$ + +Power-divergence parameter $\lambda=2/3$. A zero observed count contributes zero by continuity. The factor $9/5$ follows from $2/[\lambda(\lambda+1)]$. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Binning and calibration + +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`. +It counts transformed values in equal-probability cells and sets $E_j=n/k$. +There must be at least two retained cells. See [binning](../binning/index.md). +For fixed cells and large expected counts, the usual asymptotic reference is +$\chi^2_{k-1}$; this is not an exact small-sample calibration. Sparse cells, +merging and adaptive rules require calibration reproducing the same policy. +Binning settings are included in `configuration()`. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + CressieReadParetoGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import ExplicitBins + +statistic = CressieReadParetoGofStatistic( + Pareto.DEFAULT.parse({"shape": 2, "scale": 1}), + binning=ExplicitBins((1, 1.5, 3, float("inf"))), +) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). The formula is the corresponding member of their power-divergence family. + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/freeman_tukey_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/freeman_tukey_pareto_criterion.md new file mode 100644 index 00000000..04d029ae --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/freeman_tukey_pareto_criterion.md @@ -0,0 +1,58 @@ +# Freeman–Tukey for Pareto I + +Public class: `FreemanTukeyParetoGofStatistic`. Full code: `FREEMAN_TUKEY_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For full-support edges $b_0,\ldots,b_k$, let $O_j$ be the observed counts and +$E_j=n[F(b_j)-F(b_{j-1})]$. Expected counts must be positive and totals must agree. + +$$ +T=4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2. +$$ + +Power-divergence parameter $\lambda=-1/2$. A zero observed count contributes $4E_j$. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Binning and calibration + +The constructor accepts keyword-only `binning`. The default is +`EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`. +It counts transformed values in equal-probability cells and sets $E_j=n/k$. +There must be at least two retained cells. See [binning](../binning/index.md). +For fixed cells and large expected counts, the usual asymptotic reference is +$\chi^2_{k-1}$; this is not an exact small-sample calibration. Sparse cells, +merging and adaptive rules require calibration reproducing the same policy. +Binning settings are included in `configuration()`. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + FreemanTukeyParetoGofStatistic, +) +from pysatl_criterion.statistics.goodness_of_fit.binning import ExplicitBins + +statistic = FreemanTukeyParetoGofStatistic( + Pareto.DEFAULT.parse({"shape": 2, "scale": 1}), + binning=ExplicitBins((1, 1.5, 3, float("inf"))), +) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Cressie and Read (1984), Multinomial Goodness-of-Fit Tests](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x). The formula is the corresponding member of their power-divergence family. + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/greenwood_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/greenwood_pareto_criterion.md new file mode 100644 index 00000000..b64f29f3 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/greenwood_pareto_criterion.md @@ -0,0 +1,60 @@ +# Greenwood logarithmic residual ratio for Pareto I + +Public class: `GreenwoodParetoGofStatistic`. Full code: `Greenwood_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both shape and scale are unknown. For positive observations define + +$$ +y_i=\log(x_i/x_{(1)}),\qquad +G=\frac{\sum_i y_i^2}{(\sum_i y_i)^2}. +$$ + +The sample must be finite, real, unmasked, one-dimensional, nonconstant and have +$n\ge3$ observations. At $n=2$ the ratio is identically one, so this case is +rejected. Ties are accepted if the sample remains nonconstant. Small **and** large +values reject; the method returns the statistic, not a p-value. + +## Derivation and calibration + +Under Pareto I, $\log(X/s)$ is exponential with rate $a$. After subtracting the +minimum, one residual is zero and the other $n-1$ residuals, before ordering, +have the exponential memoryless law. Their normalized proportions follow +$\operatorname{Dirichlet}(1,\ldots,1)$ with $n-1$ components. Thus, by direct derivation, + +$$ +\frac1{n-1}\le G\le1,\qquad +\mathbb E G=\frac2n,\qquad +\operatorname{Var}(G)=\frac{4(n-2)}{n^2(n+1)(n+2)}. +$$ + +Scale cancels in the logarithmic ratios and shape cancels when normalizing. +The continuous IID null law is parameter-free. Calibrate both tails using this +$n-1$-component law or externally simulated Pareto samples. Ordinary Greenwood +CDF spacings from $n$ observations have $n+1$ components and different calibration. +Rounding and ties change the continuous-null law. Built-in Pareto simulation is unavailable. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + GreenwoodParetoGofStatistic, +) + +statistic = GreenwoodParetoGofStatistic(Pareto.DEFAULT.parse({})) +value = statistic.execute_statistic([1, 2, 4, 8]) +assert abs(value - 14 / 36) < 1e-12 +``` + +## Scientific source and attribution + +[Does, Helmers and Klaassen (1988), Approximating the distribution of Greenwood's +statistic, eqs. (1)–(2)](https://ir.cwi.nl/pub/1694/1694D.pdf) describes the squared +spacing concentration functional. The logarithmic residual construction above +is a library adaptation with the direct derivation given here. An original paper +establishing this exact fitted-Pareto implementation was not located; the source +is not presented as such a claim. + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/index.md b/docs/criteria/goodness-of-fit/pareto/index.md new file mode 100644 index 00000000..ed03ead4 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/index.md @@ -0,0 +1,100 @@ +# Pareto I goodness-of-fit criteria + +All **21 criteria** use the zero-location Pareto I model + +$$ +F_{a,s}(x)=1-(s/x)^a,\qquad x\ge s>0,\quad a>0. +$$ + +`execute_statistic` returns a statistic, not a p-value. Every sample must be +finite, real, one-dimensional and unmasked. The table distinguishes fixed and +unknown parameters; omitted parameters are unknown and are never filled with defaults. +See [mathematical verification](mathematical-validation.md) for formulas, +scientific sources, independent checks and limitations. + +## Fully specified EDF criteria + +Specify both `shape` and `scale`. These 13 criteria do not fit parameters. +All use the right critical tail, including D+ and D−. Values must be at least +scale. Minimum computational size is one; Watson and Kuiper are constant at +that size and cannot provide useful discrimination. + +| Criterion | Public class | Short code | +|---|---|---| +| [Kolmogorov–Smirnov](kolmogorov_smirnov_pareto_criterion.md) | `KolmogorovSmirnovParetoGofStatistic` | `KS` | +| [Kolmogorov–Smirnov D+](kolmogorov_smirnov_d_plus_pareto_criterion.md) | `KolmogorovSmirnovDPlusParetoGofStatistic` | `KS_PLUS` | +| [Kolmogorov–Smirnov D−](kolmogorov_smirnov_d_minus_pareto_criterion.md) | `KolmogorovSmirnovDMinusParetoGofStatistic` | `KS_MINUS` | +| [Anderson–Darling](anderson_darling_pareto_criterion.md) | `AndersonDarlingParetoGofStatistic` | `AD` | +| [Cramér–von Mises](cramer_von_mises_pareto_criterion.md) | `CramerVonMisesParetoGofStatistic` | `CVM` | +| [Liao–Shimokawa](liao_shimokawa_pareto_criterion.md) | `LiaoShimokawaParetoGofStatistic` | `LS` | +| [Watson](watson_pareto_criterion.md) | `WatsonParetoGofStatistic` | `WATSON` | +| [Kuiper](kuiper_pareto_criterion.md) | `KuiperParetoGofStatistic` | `KUIPER` | +| [Scaled Kuiper](kuiper_scaled_pareto_criterion.md) | `KuiperScaledParetoGofStatistic` | `KUIPER_SCALED` | +| [Corrected Kuiper](kuiper_corrected_pareto_criterion.md) | `KuiperCorrectedParetoGofStatistic` | `KUIPER_CORRECTED` | +| [Zhang Z_K](zhang_k_pareto_criterion.md) | `ZhangKParetoGofStatistic` | `ZHANG_ZK` | +| [Zhang Z_A](zhang_a_pareto_criterion.md) | `ZhangAParetoGofStatistic` | `ZHANG_ZA` | +| [Zhang Z_C](zhang_c_pareto_criterion.md) | `ZhangCParetoGofStatistic` | `ZHANG_ZC` | + +## Fully specified frequency criteria + +Specify both parameters. Each class accepts keyword-only `binning`; +the default is `EqualProbabilityBins(PowerCount(2.0, 0.4), min_expected=None, max_bins=1000)`. +See [binning policies](../binning/index.md) and +[calibration storage](../binning/calibration.md). Empty observed cells can produce +positive infinity for modified log-likelihood and Neyman; that is their mathematical limit. + +| Criterion | Public class | Short code | +|---|---|---| +| [Pearson chi-square](chi2_pearson_pareto_criterion.md) | `Chi2PearsonParetoGofStatistic` | `CHI2_PEARSON` | +| [Freeman–Tukey](freeman_tukey_pareto_criterion.md) | `FreemanTukeyParetoGofStatistic` | `FREEMAN_TUKEY` | +| [Modified log-likelihood](modified_log_likelihood_pareto_criterion.md) | `ModifiedLogLikelihoodParetoGofStatistic` | `MODIFIED_LOG_LIKELIHOOD` | +| [Neyman modified chi-square](neyman_chi2_pareto_criterion.md) | `NeymanChi2ParetoGofStatistic` | `CHI2_NEYMAN` | +| [Cressie–Read](cressie_read_pareto_criterion.md) | `CressieReadParetoGofStatistic` | `CRESSIE_READ` | + +## Composite hypotheses + +| Criterion | Public class | Short code | Hypothesis | +|---|---|---|---| +| [Obradović–Jovanović–Milošević](obradovic_pareto_criterion.md) | `ObradovicParetoGofStatistic` | `OJM_Integral` | Known scale; unknown shape | +| [Greenwood logarithmic residual ratio](greenwood_pareto_criterion.md) | `GreenwoodParetoGofStatistic` | `Greenwood` | Unknown shape and scale | +| [Vasicek–Song fixed-window KL](lequesne_kl_pareto_criterion.md) | `LequesneKlParetoGofStatistic` | `Lequesne_KL` | Unknown shape and scale | + +Obradović uses the upper tail and needs at least two observations above or at the +known scale. Greenwood uses both tails and needs at least three positive, +nonconstant observations. KL uses the upper tail and needs at least four positive, +nonconstant observations and an integer window `1 <= m < n/2`. + +## Examples + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + AndersonDarlingParetoGofStatistic, + GreenwoodParetoGofStatistic, + LequesneKlParetoGofStatistic, + ObradovicParetoGofStatistic, +) + +x = [1.1, 1.4, 1.9, 2.7, 4.2, 8.0] +fixed = AndersonDarlingParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +known_scale = ObradovicParetoGofStatistic(Pareto.DEFAULT.parse({"scale": 1})) +greenwood = GreenwoodParetoGofStatistic(Pareto.DEFAULT.parse({})) +kl = LequesneKlParetoGofStatistic(Pareto.DEFAULT.parse({})) +print(fixed.execute_statistic(x), known_scale.execute_statistic(x)) +print(greenwood.execute_statistic(x), kl.execute_statistic(x, m=2)) +``` + +## Calibration and interpretation + +The full code appends `_PARETO_GOODNESS_OF_FIT` to each short code. +Built-in Pareto simulation is unavailable. Fixed-null EDF statistics can be +calibrated through independent uniforms; frequency calibration must preserve +bin probabilities and binning policy. Composite criteria have different null laws. +Greenwood and Obradović eliminate the nuisance shape under continuous IID sampling; +KL retains finite-sample shape dependence and requires refitting with the same window +on each replicate. Plug-in parametric bootstrap is approximate. + +The Greenwood Pareto formula is a library adaptation of the Greenwood concentration +functional. Liao–Shimokawa uses the shared EDF functional on a fixed CDF. Neither is asserted to reproduce a published fitted-Pareto test +with supplied critical values. KL implements the raw fixed-window estimate, +not the adaptive, bias-corrected procedure of `vsgoftest`. diff --git a/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_d_minus_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_d_minus_pareto_criterion.md new file mode 100644 index 00000000..10ff5bf5 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_d_minus_pareto_criterion.md @@ -0,0 +1,52 @@ +# Kolmogorov–Smirnov D− for Pareto I + +Public class: `KolmogorovSmirnovDMinusParetoGofStatistic`. Full code: `KS_MINUS_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D^-=\max_i(u_i-(i-1)/n). +$$ + +Large values indicate an empirical CDF below the specified CDF. This directional discrepancy still has a right critical tail. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + KolmogorovSmirnovDMinusParetoGofStatistic, +) + +statistic = KolmogorovSmirnovDMinusParetoGofStatistic( + Pareto.DEFAULT.parse({"shape": 2, "scale": 1}) +) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Smirnov (1948), Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_d_plus_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_d_plus_pareto_criterion.md new file mode 100644 index 00000000..e6035ecc --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_d_plus_pareto_criterion.md @@ -0,0 +1,50 @@ +# Kolmogorov–Smirnov D+ for Pareto I + +Public class: `KolmogorovSmirnovDPlusParetoGofStatistic`. Full code: `KS_PLUS_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D^+=\max_i(i/n-u_i). +$$ + +Large values indicate an empirical CDF above the specified CDF. This directional discrepancy still has a right critical tail. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + KolmogorovSmirnovDPlusParetoGofStatistic, +) + +statistic = KolmogorovSmirnovDPlusParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Smirnov (1948), Table for Estimating the Goodness of Fit of Empirical Distributions](https://doi.org/10.1214/aoms/1177730256). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_pareto_criterion.md new file mode 100644 index 00000000..e81e0f3b --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/kolmogorov_smirnov_pareto_criterion.md @@ -0,0 +1,50 @@ +# Kolmogorov–Smirnov for Pareto I + +Public class: `KolmogorovSmirnovParetoGofStatistic`. Full code: `KS_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +D=\max(D^+,D^-). +$$ + +The result is unscaled and unsquared. The constructor accepts neither `alternative_type` nor `mode`; select a directional class for a one-sided CDF discrepancy. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + KolmogorovSmirnovParetoGofStatistic, +) + +statistic = KolmogorovSmirnovParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Zhang (2002), §§2–3, Powerful goodness-of-fit tests based on the likelihood ratio](https://doi.org/10.1111/1467-9868.00337); [full text](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/kuiper_corrected_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/kuiper_corrected_pareto_criterion.md new file mode 100644 index 00000000..0874fa6c --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/kuiper_corrected_pareto_criterion.md @@ -0,0 +1,50 @@ +# Corrected Kuiper for Pareto I + +Public class: `KuiperCorrectedParetoGofStatistic`. Full code: `KUIPER_CORRECTED_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V_c=(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-). +$$ + +The correction is an approximation intended to reduce sample-size dependence; it does not make asymptotic critical values exact. At $n=1$ the value is identically 1.395. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + KuiperCorrectedParetoGofStatistic, +) + +statistic = KuiperCorrectedParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests, eqs. (1), (3), (6)](https://doi.org/10.3103/S875669901401004X); [author-hosted full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/kuiper_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/kuiper_pareto_criterion.md new file mode 100644 index 00000000..938f01cc --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/kuiper_pareto_criterion.md @@ -0,0 +1,48 @@ +# Kuiper for Pareto I + +Public class: `KuiperParetoGofStatistic`. Full code: `KUIPER_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V=D^++D^-. +$$ + +This class returns the unscaled sum. At $n=1$ it is identically one. The three Kuiper classes differ only by a positive sample-size-dependent multiplier. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import KuiperParetoGofStatistic + +statistic = KuiperParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Kuiper (1960), Tests concerning random points on a circle](https://doi.org/10.1016/S1385-7258(60)50006-0). Computational form: [Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests, eqs. (1), (3), (6)](https://doi.org/10.3103/S875669901401004X); [author-hosted full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/kuiper_scaled_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/kuiper_scaled_pareto_criterion.md new file mode 100644 index 00000000..dc4859d2 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/kuiper_scaled_pareto_criterion.md @@ -0,0 +1,50 @@ +# Scaled Kuiper for Pareto I + +Public class: `KuiperScaledParetoGofStatistic`. Full code: `KUIPER_SCALED_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both $a=\mathrm{shape}>0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +V_s=\sqrt n(D^++D^-). +$$ + +Use critical values for this normalization. At $n=1$ the value is identically one; small samples need finite-sample calibration. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + KuiperScaledParetoGofStatistic, +) + +statistic = KuiperScaledParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Lemeshko et al. (2014), Solving Problems of Using Some Nonparametric Goodness-of-Fit Tests, eqs. (1), (3), (6)](https://doi.org/10.3103/S875669901401004X); [author-hosted full text](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf). + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/lequesne_kl_pareto_criterion.md b/docs/criteria/goodness-of-fit/pareto/lequesne_kl_pareto_criterion.md new file mode 100644 index 00000000..f7bdeda1 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/lequesne_kl_pareto_criterion.md @@ -0,0 +1,68 @@ +# Vasicek–Song fixed-window KL statistic for Pareto I + +Public class: `LequesneKlParetoGofStatistic`. Full code: `Lequesne_KL_PARETO_GOODNESS_OF_FIT`. + +## Hypothesis and statistic + +Both shape and scale are unknown. Each call fits + +$$ +\widehat s=x_{(1)},\qquad +\widehat a=\left[\frac1n\sum_i\log(x_i/\widehat s)\right]^{-1}. +$$ + +For ordered data, extend indices outside $1,\ldots,n$ by the corresponding endpoint. +With integer window $1\le m0$ and $s=\mathrm{scale}>0$ are fixed before observing the sample. +Location is zero; $F(x)=1-(s/x)^a$ for $x\ge s$. No parameters are estimated. + +For sorted data set $u_i=F(x_{(i)})$, +$D^+=\max_i(i/n-u_i)$ and $D^-=\max_i(u_i-(i-1)/n)$. + +$$ +L_n=\frac1{\sqrt n}\sum_{i=1}^n\frac{\max(i/n-u_i,u_i-(i-1)/n)}{\sqrt{u_i(1-u_i)}}. +$$ + +The criterion is generated by the shared EDF factory using the Liao–Shimokawa kernel. Here it is applied to a fully specified Pareto CDF; the fitted Weibull/extreme-value critical values in the original paper do not apply. At the lower endpoint the value is positive infinity. Extreme finite penalties can overflow float64. + +Input is a finite real one-dimensional sample with $n\ge1$ and $x_i\ge s$. +Masked observations and data below scale are rejected. The method returns one +scalar statistic; large values reject. Ties are accepted computationally, but +continuous-null calibration does not account for rounding or discrete data. + +## Calibration + +The probability integral transform gives the same finite-sample statistic law +as independent uniform observations when both Pareto parameters are truly fixed. +Do not substitute estimates from this sample and then use the fixed-null tables. +Use critical values for this precise normalization and sample size. + +Built-in Pareto Monte Carlo generation is unavailable; calibration is external. + +## Example + +```python +from pysatl_criterion.distribution import ParetoDistributionDescriptor as Pareto +from pysatl_criterion.statistics.goodness_of_fit.continuous.pareto import ( + LiaoShimokawaParetoGofStatistic, +) + +statistic = LiaoShimokawaParetoGofStatistic(Pareto.DEFAULT.parse({"shape": 2, "scale": 1})) +value = statistic.execute_statistic([1.1, 1.4, 1.9, 2.7, 4.2, 8.0]) +print(value) +``` + +## Scientific sources + +[Liao and Shimokawa (1999), A new goodness-of-fit test for Type-I extreme-value and 2-parameter Weibull distributions with estimated parameters](https://doi.org/10.1080/00949659908811965). The expression was also checked in [Al-Zahrani (2012), Goodness-of-Fit for the Topp-Leone Distribution with Unknown Parameters, eq. (13)](https://www.m-hikari.com/ams/ams-2012/ams-125-128-2012/alzahraniAMS125-128-2012.pdf). These sources do not supply Pareto-specific fitted-model calibration. + +[All Pareto criteria](index.md) · [Mathematical verification](mathematical-validation.md). diff --git a/docs/criteria/goodness-of-fit/pareto/mathematical-validation.md b/docs/criteria/goodness-of-fit/pareto/mathematical-validation.md new file mode 100644 index 00000000..b7f8fbb0 --- /dev/null +++ b/docs/criteria/goodness-of-fit/pareto/mathematical-validation.md @@ -0,0 +1,254 @@ +# Mathematical verification of Pareto I statistics + +Audit scope: **21 concrete criteria** exported by the `pareto` package (`pareto/pareto_statistics.py`): 13 generated EDF +criteria, five generated frequency criteria and three composite-hypothesis +criteria. The [catalog](index.md) links every public class to its own page, +formula, executable example and scientific source. + +## Null hypotheses and transformations + +The model has zero location and CDF $F_{a,s}(x)=1-(s/x)^a$, $x\ge s>0$, $a>0$. +The generated criteria require **both parameters fixed**; Obradović requires +only scale fixed; Greenwood and KL require neither fixed. These are distinct +hypotheses, declared by the concrete classes rather than the family base. + +For the specified model, the probability integral transform gives IID +$u_i=F_{a,s}(x_i)\sim U(0,1)$. Applying a fixed-CDF EDF functional is therefore +mathematically valid for Pareto without a separate Pareto-specific formula. +This argument does not permit estimating parameters and using the same tables. +For sorted values define $D^+=\max_i(i/n-u_i)$, $D^-=\max_i(u_i-(i-1)/n)$, +$r_i=i-1/2$, and $W^2=1/(12n)+\sum_i(u_i-r_i/n)^2$. + +## Formula checks + +All formulas below agree with the implementations on the checked domain. +The source column distinguishes original formulas from adaptations. + +| Criterion | Checked returned value | Scientific source | +|---|---|---| +| Kolmogorov–Smirnov D+ | $D^+$, no scaling | [Smirnov (1948)](https://doi.org/10.1214/aoms/1177730256); [Zhang (2002), §2.1](https://anakena.dcc.uchile.cl/~mnmonsal/eso.pdf) | +| Kolmogorov–Smirnov D− | $D^-$, no scaling | Same sources | +| Kolmogorov–Smirnov | $\max(D^+,D^-)$, not squared | [Zhang (2002), §2.1](https://doi.org/10.1111/1467-9868.00337) | +| Anderson–Darling | $-n-n^{-1}\sum_i(2i-1)[\log u_i+\log(1-u_{n+1-i})]$ | [Anderson and Darling (1952)](https://doi.org/10.1214/aoms/1177729437); Zhang §2.2 | +| Cramér–von Mises | $W^2$ | Zhang §2.3 | +| Liao–Shimokawa | $n^{-1/2}\sum_i\max(i/n-u_i,u_i-(i-1)/n)/\sqrt{u_i(1-u_i)}$ | [Liao and Shimokawa (1999)](https://doi.org/10.1080/00949659908811965); fixed-CDF adaptation, see qualifications below | +| Watson | $W^2-n(\bar u-1/2)^2$ | [Watson (1961)](https://doi.org/10.1093/biomet/48.1-2.109); [Lemeshko et al. (2014), eq. (6)](https://ami.nstu.ru/~headrd/seminar/publik_html/Awt_1_2014_eng.pdf) | +| Kuiper | $D^++D^-$ | [Kuiper (1960)](https://doi.org/10.1016/S1385-7258(60)50006-0); Lemeshko eq. (1) | +| Scaled Kuiper | $\sqrt n(D^++D^-)$ | Lemeshko, discussion before eq. (2) | +| Corrected Kuiper | $(\sqrt n+0.155+0.24/\sqrt n)(D^++D^-)$ | Lemeshko eq. (3); the multiplier approximates finite-sample stabilization | +| Zhang K | $\max_i[r_i\log(r_i/(nu_i))+(n-r_i)\log((n-r_i)/(n(1-u_i)))]$ | Zhang eq. (3.1) | +| Zhang A | $-\sum_i[\log u_i/(n-r_i)+\log(1-u_i)/r_i]$ | Zhang eq. (3.2) | +| Zhang C | $\sum_i[\log((1-u_i)/u_i)-\log((n-i+1/4)/(i-3/4))]^2$ | Zhang eq. (3.3) | +| Pearson chi-square | $\sum_j(O_j-E_j)^2/E_j$ | [Pearson (1900)](https://doi.org/10.1080/14786440009463897); [Cressie and Read (1984)](https://doi.org/10.1111/j.2517-6161.1984.tb01318.x), $\lambda=1$ | +| Freeman–Tukey | $4\sum_j(\sqrt{O_j}-\sqrt{E_j})^2$ | Cressie–Read, $\lambda=-1/2$ | +| Modified log-likelihood | $2\sum_jE_j\log(E_j/O_j)$ | Cressie–Read, $\lambda=-1$ | +| Neyman modified chi-square | $\sum_j(O_j-E_j)^2/O_j$ | Cressie–Read, $\lambda=-2$ | +| Cressie–Read | $(9/5)\sum_jO_j[(O_j/E_j)^{2/3}-1]$ | Cressie–Read, $\lambda=2/3$ | +| Obradović | $n^{-1}\sum_i[M_n(z_i)-F_n(z_i)]$, $z_i=x_i/s$ | [Obradović et al. (2014), §2](https://arxiv.org/html/1310.5510), signed integral $T_n$ | +| Greenwood | $\sum_i\log^2(x_i/x_{(1)})/[\sum_i\log(x_i/x_{(1)})]^2$ | Library log-residual adaptation of the concentration functional in [Does et al. (1988)](https://ir.cwi.nl/pub/1694/1694D.pdf); derivation below | +| Lequesne KL | $-V_{mn}-n^{-1}\sum_i\log f_{\widehat a,\widehat s}(x_i)$ | [Lequesne and Regnault (2020)](https://doi.org/10.18637/jss.v096.c01); [preprint eqs. (5), (8)](https://arxiv.org/html/1806.07244), fixed-window specialization | + +The frequency kernels require exhaustive cells with positive expected counts +and matching totals. With equal-probability binning, $E_j=n/k$; explicit edges +use their null probability differences. The coefficients and zero-count limits +were checked independently. For $O_j=0