Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### [Unreleased]

### [3.0.0-alpha.18] - 2026-11-21

Additive: no existing API changes. (`LogisticRegression.validatedDesign` gains a defaulted parameter that leaves the unpenalised path as it was.)

**A grouped-ranking toolkit and a penalised `LogisticRegression.fit`.** New in `Statistics/GroupedRanking`: the conditional-logit (subset) and
Plackett-Luce (ranking) likelihoods over grouped candidates, a prior-centred penalty with non-negativity, per-group ranking metrics, a bootstrap
over groups, grouped and nested k-fold, and `HeldOutComparison`; and `LogisticRegression.fit(penalty:)`, which fits data the unpenalised fit refuses
as separated. Source-compatible for everyone on alpha.17. Documented in the DocC article `2.8-GroupedRanking` and ADR-011. The entries below say
exactly what each part does.

**Grouped-ranking toolkit (`Statistics/GroupedRanking`), phases B1 to B5 of `project/plans/proposals/BusinessMathGroupedRanking.md`.** All additive;
no existing symbol changes. `GroupedChoiceData` (dense or sparse candidates grouped by chooser, with optional fixed per-candidate offsets, or ranked
groups), `GroupedChoiceModel` (the exact conditional-logit likelihood for an unordered chosen set, and the Plackett-Luce likelihood for ordered
top choices, with gradients), `fitScale` / `referenceFit` / `fit` (a penalty on the relative change of each multiplier toward a reference,
non-negativity by projection, a restart-guarded accelerated search, and a thrown `didNotConverge` rather than an unsettled result),
`GroupRankingMetrics` (per-group percentile, top-own and top-k, and the pooled `ClassifierEvaluation`), `GroupResampling` (an unbiased bounded draw,
bootstrap weights over groups, balanced fold assignment), and `GroupedCrossValidation` (nested penalty choice, group-bootstrap intervals, and
`HeldOutComparison`, which reports a fact about held-out groups and applies no adoption threshold). A softmax per chosen candidate is biased on the
same data (a recovery test shows a true weight of 1 fitted at about 0.64, so it understates the weight); the conditional likelihood recovers it. The
penalised `LogisticRegression.fit` is the next entry (B6). Documentation (B7): the DocC article `2.8-GroupedRanking` (its examples are run by
`GroupedRankingDocumentationTests`) and ADR-011, which records the deviations from the proposal. Not yet built: the MCP tools (phase D, in
businessMathMCP).

**Added: a penalised `LogisticRegression.fit(penalty:)` (phase B6 of `project/plans/proposals/BusinessMathGroupedRanking.md`).**
Additive; the existing `fit(maxIterations:tolerance:)`, its errors and its tests are unchanged, and `validatedDesign` gains a defaulted
parameter that leaves the unpenalised path as it was. A ridge-type penalty `(lambda / 2) * sum (beta_k - c_k)^2` over the slopes, centred on
a supplied vector (zero by default), with the intercept unpenalised. With `lambda > 0` the objective is strictly concave, so data that the
unpenalised fit refuses as separated or rank-deficient, and designs with more predictors than observations, are fitted. It still refuses a
constant outcome when an intercept is fitted (the intercept is not penalised), a penalty that is not positive and finite, a centre of the
wrong width, malformed data, and an exhausted iteration budget. New public types: `LogisticPenalty`, `PenalisedLogisticFit` (no classical
standard errors: they are not valid under a penalty; use a bootstrap). The coefficient-space form is deliberate: `LogisticRegression` has no
reference weights, so the relative-change form planned for the grouped models does not apply here. It is not Firth's penalty. Newton steps
are halved until the penalised objective does not fall, and a singular system (every fitted probability saturated, so the intercept's
information is zero) is solved with Levenberg damping. Tests were checked against an independent BFGS run and against the penalised score
equations, and a mutation audit killed 22 of 25 applicable mutants; the three survivors (the start point, which does not change a strictly concave optimum, and two finiteness checks on the damped solve that no input reached) are recorded in the build report.

### [3.0.0-alpha.17] - 2026-11-14

**The Network module gains weighted graphs and the graph measures that lived in the ClassGraph package** (ADR-006 to ADR-010; plan
Expand Down
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ Build DCF models, optimize portfolios, run Monte Carlo simulations, and value se

---

## Pre-release: 3.0.0-alpha.17
## Pre-release: 3.0.0-alpha.18

**The breaking set shipped first, in alpha.1 and alpha.2** — the items that had been waiting
for a major since August. Everything since has been correctness work and one protocol
requirement. **alpha.8 is source-breaking again**, in a handful of signatures listed below;
alpha.9 through alpha.17 are source-compatible; alpha.11 changes four *answers*, alpha.12
alpha.9 through alpha.18 are source-compatible; alpha.11 changes four *answers*, alpha.12
adds a validating form of one optimiser and bounds its table, alpha.13 adds
`ConcordanceResult.friedmanCorrected` and changes what an all-tied panel answers (`nan`, as in
SciPy and R, where it was a χ² of 0 and p = 1), and alpha.14 adds exact, tie-aware rank-sum
Expand All @@ -26,7 +26,8 @@ tie-aware Spearman critical values and p-values (`spearmanDistribution`, `spearm
`spearmanTest`), and alpha.17 adds weighted graphs and graph measures to the Network module (`WeightedGraph`, weighted centrality,
community and brokerage measures, diffusion, seed selection, siting, a metric registry) and changes the answers of two existing
functions, `Graph.eigenvectorCentrality` (correct on bipartite graphs; `nil` when not converged within `maxIterations`) and
`Graph.louvainCommunities` (now contracts communities).
`Graph.louvainCommunities` (now contracts communities), and alpha.18 adds a grouped-ranking toolkit (`Statistics/GroupedRanking`: conditional-logit and Plackett-Luce likelihoods, a prior-centred
penalty, per-group ranking metrics, a group bootstrap, grouped and nested k-fold, `HeldOutComparison`) and a penalised `LogisticRegression.fit(penalty:)`.

This notice said until 2026-10-09 that alpha.8 through alpha.11 "add no API at all" and that
what breaks "has not moved since alpha.7". Neither was true of alpha.8, and a consumer pinned
Expand All @@ -36,7 +37,7 @@ at alpha.7 found out by failing to compile: see *What alpha.8 breaks* below.
`from: "2.7.0"` you stay on 2.18.0 and nothing changes. To try the alpha, ask for it by name:

```swift
.package(url: "https://github.com/jpurnell/BusinessMath.git", exact: "3.0.0-alpha.17")
.package(url: "https://github.com/jpurnell/BusinessMath.git", exact: "3.0.0-alpha.18")
```

What breaks:
Expand Down Expand Up @@ -81,7 +82,7 @@ zero, and `EOQModel` overflowed to a non-finite order quantity with no error. It
`ModifiedZScoreAnomalyDetector` and `IQRAnomalyDetector`, and a `seed:` on
`runFinancialSimulation`.

**alpha.8 is source-breaking; alpha.9 through alpha.17 are not.** alpha.8 closes the
**alpha.8 is source-breaking; alpha.9 through alpha.18 are not.** alpha.8 closes the
contaminated-input campaign: ~1,200 sites read, ~215 real defects and 6 hard crashes, in 32
commits, against one class — *a guard that is correct while the value it returns is a claim
landing at the favourable end of a scale the caller reads.* The principle it produced:
Expand Down
177 changes: 177 additions & 0 deletions Sources/BusinessMath/BusinessMath.docc/2.8-GroupedRanking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
# Grouped Ranking: What Predicts a Choice

Fit what predicts which candidates get chosen *within* each chooser's own set, test whether a refit beats the weights you already have, and keep the verdict honest.

## Overview

Some data has the shape "within each group, some candidates were chosen": a person and the colleagues they named, a shopper and the products they clicked, a query and the results someone opened. The question is what about a candidate predicts being chosen. A pooled regression answers a different question. It credits any feature that merely correlates with choosers who choose a lot, because a chooser who names fifteen people contributes fifteen positives and one who names two contributes two.

The grouped-ranking toolkit compares each group only with itself, so how much a group chooses drops out. It is in `Statistics/GroupedRanking`, generic over `T: Real & Sendable & BinaryFloatingPoint`, and additive: no existing symbol changed.

- ``GroupedChoiceData`` holds the groups, candidates with numeric features, and which were chosen (or in what order).
- ``GroupedChoiceModel`` pairs the data with **reference weights** and a ``ChoiceLikelihood``. ``GroupedChoiceModel/fit(groupWeights:penalty:frozen:start:maxIterations:)`` refits the weights, pulled toward the reference by a penalty.
- ``GroupRankingMetrics`` scores a set of candidate scores group by group.
- ``GroupedCrossValidation`` chooses the penalty, bootstraps over groups, and runs ``GroupedCrossValidation/heldOutComparison(model:penalties:minimumChosen:folds:innerFolds:resamples:level:seed:)``, which returns a ``HeldOutComparison``.
- ``LogisticRegression/fit(penalty:maxIterations:tolerance:)`` is a separate, penalised logistic fit.

Everything fitted here **ranks**. A candidate nobody chose is *unknown*, not rejected, so the weights say which candidates a chooser is more likely to choose, not by how much they are chosen.

## The data

A group is one chooser's candidates. Each candidate is a row of features and a flag.

```swift
let small = GroupedChoiceData<Double>(groups: [
[(features: [1, 0], chosen: true), (features: [0, 1], chosen: false), (features: [0, 0], chosen: false)],
[(features: [1, 1], chosen: true), (features: [0, 0], chosen: false)],
])
// small?.groupCount == 2, small?.featureCount == 2, small?.informativeGroups == [0, 1]
```

Initialisers return `nil` for malformed data. Features are stored sparsely (only the non-zero entries), so a wide, mostly-zero feature matrix costs memory in proportion to what is present. An optional fixed offset per candidate carries a term the model must not fit, such as a deduction you apply by rule.

A *group with no chosen candidate, or with every candidate chosen, has nothing to compare*; it is not an error, and it adds nothing to the fit (``GroupedChoiceData/informativeGroups`` lists the groups that do).

## Two likelihoods, not one

``ChoiceLikelihood`` has two cases, and they are different functions.

- ``ChoiceLikelihood/subset``: the group chose an *unordered* set of candidates, the **conditional logit**. How many a group chose does not move the weights.
- ``ChoiceLikelihood/ranking``: the group ranked its top candidates *in order*, the **Plackett-Luce** model. Each next choice is made among the candidates not yet taken.

With exactly one chosen candidate per group they coincide. With more than one they do not, and Plackett-Luce taken over an arbitrary order of an unordered set would make the answer depend on the order chosen. So each model refuses the other's data:

```swift
let ranked = GroupedChoiceData<Double>(rankedGroups: [
(candidates: [[1, 0], [0, 1], [0, 0]], ranking: [0, 1]), // candidate 0 first, then 1
(candidates: [[1, 1], [0, 0], [1, 0]], ranking: [0, 2]),
(candidates: [[0, 1], [1, 0], [0, 0]], ranking: [1]),
])
// GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .ranking) is a model;
// the same data with .subset is nil, and unordered data with .ranking is nil.
```

## Fitting around a reference

Most uses start from weights somebody already believes in. The model fits two things: one **scale** that turns the reference weights into log-odds, then a **multiplier** on each weight (at least zero), with a penalty on how far a multiplier moves from 1. A large penalty returns your weights; a small one approaches the unpenalised optimum. The data has to argue for any change.

The example below builds 60 choosers with six candidates each. Feature 0 genuinely drives the choice; feature 1 does not. The reference weights say both matter equally.

```swift
var generator = SplitMix64(seed: 11)
let groups: [[(features: [Double], chosen: Bool)]] = (0..<60).map { _ in
let candidates: [[Double]] = (0..<6).map { _ in
[Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0,
Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0]
}
let appeal: [Double] = candidates.map { exp(1.5 * $0[0]) }
var pick = Double.random(in: 0..<1, using: &generator) * appeal.reduce(0, +)
var chosenIndex = appeal.count - 1
for (index, share) in appeal.enumerated() {
if pick < share { chosenIndex = index; break }
pick -= share
}
return candidates.enumerated().map { (features: $0.element, chosen: $0.offset == chosenIndex) }
}

guard let data = GroupedChoiceData<Double>(groups: groups),
let model = GroupedChoiceModel(data: data, reference: [1, 1], likelihood: .subset) else {
fatalError("the example's data is well-formed")
}
let weights = [Double](repeating: 1, count: data.groupCount) // every group counts once
let fit = try model.fit(groupWeights: weights, penalty: 0.05)
// fit.multipliers ≈ [1.69, 0.27] (the real feature is raised, the other lowered)
// fit.scale ≈ 0.785 (effective weights ≈ 1.32 and 0.21, against a true 1.5 and 0)
// fit.converged true
```

`fit` **throws** ``GroupedChoiceError/didNotConverge(iterations:gradientNorm:)`` if the search does not settle. It never returns an unsettled estimate as though it had settled.

The penalty acts on each multiplier's *relative* change. A feature whose reference is `0` cannot move, because its multiplier is not identified. ``GroupedChoiceModel/referenceFit(groupWeights:)`` keeps every multiplier at 1 and fits only the scale: the reference weights, calibrated.

## Ranking metrics, group by group

``GroupRankingMetrics/perGroup(scores:data:k:)`` takes one score per candidate row and returns, for each group, where its chosen candidates fell.

```swift
if let scores = model.scores(for: fit),
let perGroup = GroupRankingMetrics.perGroup(scores: scores, data: data, k: 3) {
let summary = GroupRankingMetrics.summary(perGroup)
// summary.groups 60
// summary.meanPercentile ≈ 0.65 (0.5 is chance)
// summary.topOwnShare ≈ 0.33 (the share of a group's chosen candidates inside its top *n*, *n* being how many it chose)
}
```

``GroupRankingMetrics/pooledEvaluation(scores:data:)`` pools the comparable groups and hands the result to ``ClassifierEvaluation``, so the ROC area and the confusion matrix are the library's own.

A metric is `nil` where it is not defined: scores that are not one per row, a group with nothing to compare, a score that is not finite.

## Does a refit beat what you had?

Fitting on the data you score flatters the refit. ``GroupedCrossValidation/heldOutComparison(model:penalties:minimumChosen:folds:innerFolds:resamples:level:seed:)`` holds each group out of the fit exactly once, picks the penalty on the training groups only (nested folds), and compares the refit with the reference weights on the groups it never saw.

```swift
let comparison = GroupedCrossValidation.heldOutComparison(
model: model, penalties: [.reference, .penalty(0.05), .penalty(0.5)], minimumChosen: 10,
folds: 5, innerFolds: 3, resamples: 200, level: 0.9, seed: 1)
// comparison?.referencePercentile ≈ 0.63
// comparison?.refitPercentile ≈ 0.65
// comparison?.difference ≈ 0.023
// comparison?.lower, comparison?.upper ≈ 0.003, 0.045 (90% bootstrap interval over groups)
// comparison?.refitBeatsReference true
```

``HeldOutComparison`` states a **fact**: the two mean percentiles, their paired difference, and a bootstrap interval for the difference over *groups* (never rows). It does not say whether to adopt anything. ``HeldOutComparison/refitBeatsReference`` is true when the interval's lower end is above zero; ``HeldOutComparison/intervalExcludesZero`` is true on either side. How big a move counts, and how many chosen candidates a feature needs before it is refitted (`minimumChosen`, which keeps a thin feature at its reference value), belong to your own policy and sit on top of these figures.

Seeds are `UInt64` values. The fold assignment, each inner assignment and the bootstrap use derived seeds from `SplitMix64`, so a run repeats exactly.

## A penalised logistic regression

``LogisticRegression/fit(maxIterations:tolerance:)`` refuses data a feature separates perfectly, because the coefficient would run to infinity. A small ridge penalty fixes that:

```swift
let regression = LogisticRegression<Double>(predictors: [[0], [1], [2], [3]],
outcomes: [false, false, true, true])
// regression.fit() throws LogisticRegressionError.separation
let logisticFit = try regression.fit(penalty: LogisticPenalty(lambda: 0.1))
// logisticFit.coefficients ≈ [-3.98, 2.65] (intercept, then slope)
// logisticFit.probability([1.5]) ≈ 0.5
```

``LogisticPenalty`` is `(lambda / 2) × Σ (β − centre)²`, with the intercept left unpenalised and a centre of zero by default. The result is a ``PenalisedLogisticFit``, not a `LogisticFit`: it has **no classical standard errors**, because they are not valid under a penalty. Use a bootstrap. The existing unpenalised `fit` and its errors are unchanged.

A constant outcome is still refused when an intercept is fitted, since the unpenalised intercept would diverge.

## What it does not do

- It estimates **rankings, not probabilities**. A candidate nobody chose is unknown; the fitted weights say who is more likely to be chosen, not how likely.
- It does **not** decide whether to adopt a refit. ``HeldOutComparison`` reports; you decide.
- The penalty on the grouped models acts on the *relative* change of each reference weight. ``LogisticRegression`` has no reference weights, so its penalty is a coefficient-space ridge.
- The MCP tools for this toolkit are a later phase, in businessMathMCP.

## Topics

### Data and models

- ``GroupedChoiceData``
- ``GroupedChoiceModel``
- ``ChoiceLikelihood``
- ``GroupedChoiceFit``
- ``GroupedChoiceError``

### Evaluation

- ``GroupRankingMetrics``
- ``GroupRanking``
- ``GroupRankingSummary``
- ``GroupedCrossValidation``
- ``HeldOutComparison``
- ``PenaltyChoice``
- ``BootstrapIntervals``
- ``GroupResampling``

### Penalised logistic regression

- ``LogisticPenalty``
- ``PenalisedLogisticFit``
3 changes: 3 additions & 0 deletions Sources/BusinessMath/BusinessMath.docc/Part2-Analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ This section bridges the gap between calculation and insight. Whether you're eva
- <doc:2.6-RankSumSignificance>
- <doc:2.7-SpearmanSignificance>

### Choice Models and Rankings
- <doc:2.8-GroupedRanking>

## Prerequisites

Before diving into Part II, you should be comfortable with time series operations, basic financial calculations, and the fluent API patterns from Part I. If you skipped Part I, at minimum review chapters 1.1-1.3 before proceeding.
Expand Down
Loading
Loading