Implement Benjamini-Hochberg FDR adjusted p-values without statsmodels
Quick Overview
Implement Benjamini-Hochberg adjusted p-values in NumPy so they match the statsmodels fdr_bh output without importing the library. Tests sorting with 1-indexed ranks, the cumulative minimum that enforces monotonicity, and mapping the results back to input order.
Implement Benjamini-Hochberg FDR adjusted p-values without statsmodels
Role: Data Scientist
Category: Analytics & Experimentation
Difficulty: medium
Interview Round: Other
Implement the function below so that it reproduces `statsmodels.stats.multitest.multipletests(pvals, method='fdr_bh')[1]` exactly, without importing statsmodels. Let `m = len(pvals)`.
```python
def bh_adjust_manual(pvals: list[float]) -> np.ndarray:
```
The function must:
- Sort the p-values ascending and compute `p_(i) * m / i` at each 1-indexed rank `i`.
- Enforce monotonicity with a cumulative minimum taken from the largest p-value down to the smallest.
- Clip all values at `1.0`.
- Return a 1-D `float64` array of length `m` in the original input order.
Example:
```python
pvals = [0.001, 0.008, 0.039, 0.041, 0.042, 0.06, 0.074, 0.205, 0.212, 0.216]
bh_adjust_manual(pvals)
# -> [0.01, 0.04, 0.084, 0.084, 0.084, 0.1, 0.10571429, 0.216, 0.216, 0.216]
```
```hint Running minimum in NumPy
`np.minimum.accumulate` computes a running minimum from the start of an array. Think about how to make it run from the end instead.
```
```hint Back to input order
You need the inverse of the sort permutation, not the permutation itself. Check which side of the assignment the sort order belongs on.
```
### Constraints & Assumptions
- Inputs are valid floats in `[0, 1]`.
- `m >= 1`. Empty input is out of scope.
### What a Strong Answer Covers
- How the raw ratios are computed from the sorted p-values at 1-indexed ranks
- Which direction the cumulative minimum runs, and why that direction makes the adjusted values non-decreasing in rank
- The clip at 1.0 and the mapping back to the original input order
- Time and space complexity
- How the result is compared with the library output (bit-for-bit or within a tolerance)
### Follow-up Questions
- How would you handle ties in the p-values?
- Why does the scan run from the largest p-value down to the smallest, and what goes wrong if it runs the other way?
- How do you turn the adjusted p-values into reject decisions at a target FDR level $q$?
- How would the function change for the Benjamini-Yekutieli procedure, and when would you need it?
Overview: Implement Benjamini-Hochberg adjusted p-values in NumPy so they match the statsmodels fdr_bh output without importing the library. Tests sorting with 1-indexed ranks, the cumulative minimum that enforces monotonicity, and mapping the results back to input order.
Implement the function below so that it reproduces statsmodels.stats.multitest.multipletests(pvals, method='fdr_bh')[1] exactly, without importing statsmodels. Let m = len(pvals).