---
title: "Feasible sample sizes from incomplete planning information"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Feasible sample sizes from incomplete planning information}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse=TRUE, comment="#>")
library(feasiblesize)
```

## The planning question

When the supplied information permits several future data distributions,
which sample sizes meet the error requirements under all of them? An inner
bound contains sizes feasible in every compatible state. An outer bound
contains sizes feasible in at least one state. These are set bounds, not
synonyms for a numerical lower and upper sample size.

The package implements Nakamura (2026), *Identifying Feasible Sample Sizes
from Incomplete Design Information*, Stats 9(5), 105,
<https://doi.org/10.3390/stats9050105>.

Before calculation specify the observational unit, null and alternative
regions, error limits, candidate domain, decision rule, and compatible state
set. The package does not supply the clinical justification for these inputs.

## A normal example with an upper feasible boundary

Assume independent normal observations of variance one. Effects up to 0.1
are negligible and effects from 0.5 are meaningful. Both false negative and
false positive limits are 0.2. A point null test rejects a zero effect at
one sided level 0.05.

```{r normal}
point <- normal_risks(1:1000)
minimum <- normal_risks(1:1000, rule="minimum")
range(feasible_sizes(point))
range(feasible_sizes(minimum))
directional_evidence(1000, point)
```

The point null rule is feasible only from 25 through 64. At larger sizes a
small positive effect can produce too many positive decisions. The minimum
effect rule includes negligible effects in its null and stays feasible from
39 through the end of the declared domain. A larger experiment has not lost
information. Changing the rule can preserve feasibility while using all data.

## Uncertain standard deviation and a common rule

Suppose the standard deviation is in [0.22,0.30], the negligible boundary is
0.02, and the meaningful boundary is 0.05. The critical mean is calibrated
with 0.30 and remains fixed across states.

```{r normal-bounds, fig.width=6, fig.height=3.5}
b <- normal_size_bounds(1:800, sigma_range=c(0.22,0.30),
                       d_negligible=0.02, d_meaningful=0.05,
                       rule="minimum")
b
min(b$inner)
plot(b)
```

With both error limits below one half, a feasible critical mean lies between
the effect boundaries; both risks then increase with sigma. This gives a
full interval endpoint certificate for this specific normal model. In a
general model, evaluating a grid does not prove an inner bound over a
continuous state set. `size_bounds()` explicitly reports bounds over the
supplied finite states only.

## Exact binary compatibility and coordinate feasibility

When every proper subset margin of a multivariate binary distribution is
fixed, the remaining joint distributions form an affine interval through
one compatible baseline. The baseline below is uniform on four cells.

```{r binary}
cpt <- binary_compatibility(binary_mass(rep("1/4",4)))
as.character(cpt$lower)
as.character(cpt$upper)
p <- operating_polynomial(cpt,1L,function(s) as.integer(prod(2*s[1,]-1)==1))
as.character(p$coefficients)
res <- coordinate_feasibility(cpt,list(
    risk_constraint("fn","false_negative",1L-p,"3/4"),
    risk_constraint("fp","false_positive",p,"3/4")))
res
lapply(res$components,function(component)
    lapply(res$boundaries[component],function(root)
        c(lower=as.character(root$lower),upper=as.character(root$upper))))
```

The feasible coordinates are [-1/8,1/8]. Rational coefficients and endpoints
remain exact using package 'gmp'. Sturm sequences isolate every constraint
root, after which boundary points and intervening open intervals are checked.
This includes repeated roots, algebraic endpoints, isolated feasible points,
and disconnected sets. Supply character probabilities such as `"0.1"` rather
than double inputs such as `0.1` when exact arithmetic is required.

`operating_polynomial()` enumerates ordered samples and is intentionally
limited to small problems. At larger sizes, derive the risk polynomials
analytically or use the supported normal or paired binary model. Exact sign
analysis does not establish that a user supplied polynomial is the correct
statistical risk. Normal and paired binomial probabilities are numerical
distribution calculations, not arbitrary precision rational calculations.

## One common rule versus a different rule at every state

```{r family}
x <- rational_polynomial(c(0L,1L))
constraints <- function(fp) list(
    risk_constraint("fn","false_negative",0L,"1/2"),
    risk_constraint("fp","false_positive",fp,"1/2"))
family <- list(
    planned=setNames(lapply(c(0L,1L,1L,1L,1L),constraints),1:5),
    left=setNames(lapply(list(1L,0L,"1/2"+x,"5/8"+x,1L),constraints),1:5),
    right=setNames(lapply(list(1L,1L,"1/2"-x,"5/8"-x,1L),constraints),1:5))
r <- classify_rule_family(cpt,1:5,"planned",family)
r$nested_sets
r$cases
```

T1 contains sizes where the planned rule works everywhere. T2 has one common
alternative rule. T3 permits a different successful rule at each state and
therefore need not provide an implementable common rule. T4 works somewhere
only; T5 works nowhere. The returned `inner` and `outer` refer to the
**planned rule**. The outer set for the complete decision class is
`nested_sets$feasible_somewhere` and can be larger.

## Paired binary outcomes and unknown discordance

For independent pairs, let r be the discordance probability and d the
difference P(1,0)-P(0,1). Conditioning on discordant pairs gives a binomial
success probability (r+d)/(2r). The zero boundary critical values do not
depend on r.

```{r paired}
paired_binary_risks(c(300,500,1000),discordance=0.11275)
paired_discordance_bounds(0.4,0.35,minimum_difference=0.05)
```

The displayed 0.11275 is illustrative. To reproduce the historical vision
table use the exact empirical discordance count divided by its total.
The following minimum effect calculation assumes that discordance is known
when calibrating the rule:

```{r paired-known}
paired_binary_risks(c(500,1000),discordance=0.11275,rule="minimum",
                    calibration_discordance=0.11275)
```

If discordance is unknown, calibrating separately with each state supplies
state dependent rules. Keep `calibration_discordance` fixed to evaluate one
common rule; its full error guarantees must then be checked over the
declared state set. The package does not label a finite grid as a sharp
continuous bound.

## Numerical verification and scope

The package tests contain deterministic fixtures generated from the
unmodified Python `ssadmiss` 0.5.0rc1 reference. Comparisons cover operating
probabilities, feasible sets, binary endpoints and distributions, root
isolators, full interval feasibility and the five rule cases. The installed
R package does not run Python. Sampling uncertainty in planning inputs,
clustering, nonnormal outcomes and a new rule require an appropriate new
calculation; the normal illustration does not supply an AUC model by itself.
