Skip to main content

qualia_core_db/specialized_libs/computational_economics/
welfare.rs

1//! Welfare economics primitives: social welfare functions, inequality and
2//! poverty metrics, cost-benefit analysis with distributional weights, and a
3//! needs/survival-floor allocation model.
4//!
5//! # Allocation class
6//!
7//! All kernels here are `AllocationClass::HotZeroHeap`. Sorting scratch uses
8//! fixed-capacity stack arrays (`[f64; MAX_POPULATION]`) or caller-provided
9//! output buffers — never `Vec`, `String`, or `Box`. No allocation occurs on
10//! any path, hot or cold, within this module.
11//!
12//! # Rights-affecting use
13//!
14//! Poverty metrics, distributional weights, and the survival-floor allocation
15//! model can inform decisions that affect entitlements, transfers, or access.
16//! Those uses MUST be paired with SHACL/deontic checks (see `deontic_logic.rs`
17//! opcodes `OP_OBLIGATE`/`OP_FORBID`/`OP_PERMIT`) and capacity-modalities
18//! review before any UI exposure or downstream action. The `repr(C)` report
19//! structs returned by rights-affecting functions carry diagnostics and
20//! assumptions, not just a scalar, so callers can audit the basis of a
21//! computed allocation. No function in this module performs or recommends an
22//! external action on its own.
23
24/// Maximum population size supported by stack-array scratch buffers.
25pub const MAX_POPULATION: usize = 256;
26
27/// Welfare kernel error vocabulary.
28///
29/// `repr(u8)` for ABI-stable reporting across WASM / edge / Webizen dispatch.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[repr(u8)]
32pub enum WelfareError {
33    /// Input failed validation (bad dimensions, negative where non-negative
34    /// is required, out-of-range parameter, mismatched lengths, etc.).
35    InvalidInput = 0,
36    /// Population or series is empty where a non-empty population is required.
37    InsufficientData = 1,
38    /// A non-finite value (NaN/inf) was encountered in input or during
39    /// computation.
40    NonFinite = 2,
41    /// A caller-supplied output buffer was too small for the request.
42    BufferTooSmall = 3,
43}
44
45impl WelfareError {
46    /// True when the failure is a caller-side buffer/dimension problem.
47    #[inline]
48    /// `true` for caller-correctable errors (invalid input, buffer
49    /// too small) vs internal failures.
50    pub fn is_caller_error(self) -> bool {
51        matches!(
52            self,
53            WelfareError::InvalidInput
54                | WelfareError::BufferTooSmall
55                | WelfareError::InsufficientData
56        )
57    }
58}
59
60/// Report returned by rights-affecting welfare kernels.
61///
62/// `repr(C)` so it can cross the WASM / edge / GPU ABI as a fixed record and
63/// be audited by deontic / SHACL layers before any UI exposure. The scalar
64/// `value` is never the whole story: `assumptions` and `diagnostics` carry the
65/// basis of the computation.
66#[derive(Debug, Clone, Copy, PartialEq)]
67#[repr(C)]
68pub struct WelfareReport {
69    /// The primary scalar result (count, ratio, allocated amount, etc.).
70    /// Semantics are documented at each call site.
71    pub value: f64,
72    /// Secondary scalar (e.g. population size as f64, or a companion metric).
73    pub auxiliary: f64,
74    /// Bit-packed assumption flags (see `ASSUMPTION_*` constants).
75    pub assumptions: u32,
76    /// Diagnostic status code (0 = clean; non-zero mirrors `WelfareError` as
77    /// u8 plus kernel-specific high bits reserved for future use).
78    pub diagnostics: u32,
79}
80
81/// Assumption flag: at least one observation was clamped to the survival floor.
82pub const ASSUMPTION_FLOOR_CLAMPED: u32 = 1 << 0;
83/// Assumption flag: distributional weights were applied (CBA only).
84pub const ASSUMPTION_WEIGHTED: u32 = 1 << 1;
85/// Assumption flag: result is degenerate (e.g. zero-mean population for Gini).
86pub const ASSUMPTION_DEGENERATE: u32 = 1 << 2;
87/// Assumption flag: poverty line is above the maximum observed income.
88pub const ASSUMPTION_LINE_ABOVE_MAX: u32 = 1 << 3;
89
90impl WelfareReport {
91    /// Construct a clean report with no assumption flags.
92    pub const fn clean(value: f64, auxiliary: f64) -> Self {
93        Self {
94            value,
95            auxiliary,
96            assumptions: 0,
97            diagnostics: 0,
98        }
99    }
100
101    /// Construct a report with assumption flags set.
102    pub const fn with_assumptions(value: f64, auxiliary: f64, assumptions: u32) -> Self {
103        Self {
104            value,
105            auxiliary,
106            assumptions,
107            diagnostics: 0,
108        }
109    }
110}
111
112// ---------------------------------------------------------------------------
113// Validation helpers
114// ---------------------------------------------------------------------------
115
116/// `x` is finite (no NaN/inf in welfare aggregates).
117#[inline]
118/// `true` when `x` is finite (not NaN/±∞).
119fn finite(x: f64) -> bool {
120    x.is_finite()
121}
122
123/// `x` is finite and ≥ 0 (incomes, weights).
124#[inline]
125/// `true` when `x` is finite and ≥ 0.
126fn finite_nonnegative(x: f64) -> bool {
127    x.is_finite() && x >= 0.0
128}
129
130/// `x` is finite and > 0 (denominators, elasticities).
131#[inline]
132/// `true` when `x` is finite and > 0.
133fn finite_strictly_positive(x: f64) -> bool {
134    x.is_finite() && x > 0.0
135}
136
137/// Validate a population slice: non-empty, within capacity, all finite and
138/// non-negative. Returns the population count on success.
139fn validate_population(incomes: &[f64]) -> Result<usize, WelfareError> {
140    if incomes.is_empty() {
141        return Err(WelfareError::InsufficientData);
142    }
143    if incomes.len() > MAX_POPULATION {
144        return Err(WelfareError::BufferTooSmall);
145    }
146    for &x in incomes {
147        if !finite_nonnegative(x) {
148            if !finite(x) {
149                return Err(WelfareError::NonFinite);
150            }
151            return Err(WelfareError::InvalidInput);
152        }
153    }
154    Ok(incomes.len())
155}
156
157/// Validate a population slice where strictly positive values are required
158/// (e.g. geometric-mean based Atkinson index).
159fn validate_positive_population(incomes: &[f64]) -> Result<usize, WelfareError> {
160    if incomes.is_empty() {
161        return Err(WelfareError::InsufficientData);
162    }
163    if incomes.len() > MAX_POPULATION {
164        return Err(WelfareError::BufferTooSmall);
165    }
166    for &x in incomes {
167        if !finite(x) {
168            return Err(WelfareError::NonFinite);
169        }
170        if x <= 0.0 {
171            return Err(WelfareError::InvalidInput);
172        }
173    }
174    Ok(incomes.len())
175}
176
177/// Copy `incomes` into a stack scratch array and sort ascending. Returns the
178/// count (== `incomes.len()`). Zero-heap: scratch is a fixed `[f64; MAX_POPULATION]`.
179fn copy_sort_ascending(incomes: &[f64]) -> Result<[f64; MAX_POPULATION], WelfareError> {
180    let n = validate_population(incomes)?;
181    let mut scratch = [0.0f64; MAX_POPULATION];
182    for (i, &x) in incomes.iter().enumerate() {
183        scratch[i] = x;
184    }
185    scratch[..n].sort_by(|a, b| a.total_cmp(b));
186    Ok(scratch)
187}
188
189// ---------------------------------------------------------------------------
190// Inequality metrics
191// ---------------------------------------------------------------------------
192
193/// Gini coefficient in `[0, 1]` via the mean-absolute-difference formula:
194///
195/// `G = sum_i sum_j |x_i - x_j| / (2 * n^2 * mean)`
196///
197/// Returns `WelfareError::InvalidInput` when the mean is zero (degenerate
198/// population of all zeros) since the Gini is undefined there. Inputs must be
199/// non-negative and finite; an empty population returns `InsufficientData`.
200///
201/// Allocation class: `HotZeroHeap`. The O(n^2) mean-absolute-difference sum
202/// is computed in place over the input slice — no sort is needed for this
203/// formula, so no scratch is used.
204pub fn gini_coefficient(incomes: &[f64]) -> Result<f64, WelfareError> {
205    let n = validate_population(incomes)?;
206    let mut sum: f64 = 0.0;
207    let mut total: f64 = 0.0;
208    for i in 0..n {
209        total += incomes[i];
210        for j in 0..n {
211            let d = incomes[i] - incomes[j];
212            sum += d.abs();
213        }
214    }
215    if total <= 0.0 {
216        // All-zero (or all-degenerate) population: Gini undefined.
217        return Err(WelfareError::InvalidInput);
218    }
219    let mean = total / n as f64;
220    let denom = 2.0 * (n as f64).powi(2) * mean;
221    Ok(sum / denom)
222}
223
224/// Write the Lorenz curve as interleaved `(cumulative_population_share,
225/// cumulative_income_share)` pairs into `out`: `[pop0, inc0, pop1, inc1, ...]`,
226/// sorted ascending by income. Returns the number of points written.
227///
228/// Each point corresponds to one observation (no binning), so `out` must hold
229/// at least `2 * n` `f64` slots. The first point is `(1/n, x_min/total)` and
230/// the last is `(1, 1)`.
231///
232/// Allocation class: `HotZeroHeap`. Sorting uses a fixed `[f64; MAX_POPULATION]`
233/// stack scratch array.
234pub fn lorenz_curve_into(incomes: &[f64], out: &mut [f64]) -> Result<usize, WelfareError> {
235    let n = validate_population(incomes)?;
236    if out.len() < 2 * n {
237        return Err(WelfareError::BufferTooSmall);
238    }
239    let sorted = copy_sort_ascending(incomes)?;
240    let mut total = 0.0f64;
241    for i in 0..n {
242        total += sorted[i];
243    }
244    if total <= 0.0 {
245        return Err(WelfareError::InvalidInput);
246    }
247    let mut cum = 0.0f64;
248    for i in 0..n {
249        cum += sorted[i];
250        out[2 * i] = (i + 1) as f64 / n as f64;
251        out[2 * i + 1] = cum / total;
252    }
253    Ok(n)
254}
255
256/// Atkinson inequality index with inequality-aversion parameter `epsilon > 0`.
257///
258/// - For `epsilon != 1`: `A = 1 - (geometric_mean / arithmetic_mean)^(1-epsilon)`.
259/// - For `epsilon == 1`: `A = 1 - geometric_mean / arithmetic_mean`.
260///
261/// All incomes must be strictly positive (the geometric mean is undefined for
262/// zero/negative values). `epsilon` must be finite and `> 0`. Returns a value
263/// in `[0, 1)`: `0` under perfect equality, increasing toward `1` as
264/// inequality rises and as `epsilon` (inequality aversion) rises.
265///
266/// Allocation class: `HotZeroHeap`.
267pub fn atkinson_inequality(incomes: &[f64], epsilon: f64) -> Result<f64, WelfareError> {
268    let n = validate_positive_population(incomes)?;
269    if !finite(epsilon) || epsilon <= 0.0 {
270        return Err(WelfareError::InvalidInput);
271    }
272
273    let mut sum = 0.0f64;
274    for i in 0..n {
275        if incomes[i] <= 0.0 {
276            return Err(WelfareError::InvalidInput);
277        }
278        sum += incomes[i];
279    }
280    let arithmetic_mean = sum / n as f64;
281    if arithmetic_mean <= 0.0 {
282        return Err(WelfareError::InvalidInput);
283    }
284
285    if (epsilon - 1.0).abs() < f64::EPSILON {
286        // Limit case: 1 - geo / arith
287        let mut log_sum = 0.0f64;
288        for i in 0..n {
289            log_sum += incomes[i].ln();
290        }
291        let geo = (log_sum / n as f64).exp();
292        let a = 1.0 - (geo / arithmetic_mean);
293        return Ok(a.clamp(0.0, 1.0));
294    }
295
296    // General case: 1 - ( power mean of order (1-eps) / arith )
297    let one_minus_eps = 1.0 - epsilon;
298    let mut sum_pow = 0.0f64;
299    for i in 0..n {
300        sum_pow += incomes[i].powf(one_minus_eps);
301    }
302    let mean_pow = sum_pow / n as f64;
303    let power_mean = if one_minus_eps.abs() > 1e-12 {
304        mean_pow.powf(1.0 / one_minus_eps)
305    } else {
306        arithmetic_mean
307    };
308    let a = 1.0 - (power_mean / arithmetic_mean);
309    if !a.is_finite() {
310        return Err(WelfareError::NonFinite);
311    }
312    Ok(a.clamp(0.0, 1.0))
313}
314
315/// Headcount poverty: returns `(count_poor, headcount_ratio)` where
316/// `count_poor` is the number of observations strictly below `poverty_line`
317/// and `headcount_ratio = count_poor / n`.
318///
319/// `poverty_line` must be finite and strictly positive. Incomes must be
320/// non-negative and finite.
321///
322/// Allocation class: `HotZeroHeap`.
323pub fn headcount_poverty(incomes: &[f64], poverty_line: f64) -> Result<(usize, f64), WelfareError> {
324    let n = validate_population(incomes)?;
325    if !finite_strictly_positive(poverty_line) {
326        return Err(WelfareError::InvalidInput);
327    }
328    let mut count = 0usize;
329    for &x in incomes {
330        if x < poverty_line {
331            count += 1;
332        }
333    }
334    let ratio = count as f64 / n as f64;
335    Ok((count, ratio))
336}
337
338/// Poverty gap ratio: `sum(max(0, line - income)) / (n * line)`.
339///
340/// Returns a value in `[0, 1]`: `0` when nobody is below the line, `1` when
341/// every observation is zero. `poverty_line` must be finite and strictly
342/// positive. Incomes must be non-negative and finite.
343///
344/// Allocation class: `HotZeroHeap`.
345pub fn poverty_gap_ratio(incomes: &[f64], poverty_line: f64) -> Result<f64, WelfareError> {
346    let n = validate_population(incomes)?;
347    if !finite_strictly_positive(poverty_line) {
348        return Err(WelfareError::InvalidInput);
349    }
350    let mut gap = 0.0f64;
351    for &x in incomes {
352        if x < poverty_line {
353            gap += poverty_line - x;
354        }
355    }
356    Ok(gap / (n as f64 * poverty_line))
357}
358
359// ---------------------------------------------------------------------------
360// Social welfare functions
361// ---------------------------------------------------------------------------
362
363/// Utilitarian (sum) social welfare: `sum_i u_i`.
364///
365/// Utilities must be finite. Negative utilities are permitted (welfare can be
366/// negative). An empty population returns `InsufficientData`.
367///
368/// Allocation class: `HotZeroHeap`.
369pub fn utilitarian_welfare(utilities: &[f64]) -> Result<f64, WelfareError> {
370    if utilities.is_empty() {
371        return Err(WelfareError::InsufficientData);
372    }
373    if utilities.len() > MAX_POPULATION {
374        return Err(WelfareError::BufferTooSmall);
375    }
376    let mut sum = 0.0f64;
377    for &u in utilities {
378        if !finite(u) {
379            return Err(WelfareError::NonFinite);
380        }
381        sum += u;
382    }
383    Ok(sum)
384}
385
386/// Rawlsian (minimax / maximin) social welfare: `min_i u_i`.
387///
388/// The welfare of a society is the welfare of its worst-off member. Utilities
389/// must be finite. An empty population returns `InsufficientData`.
390///
391/// Allocation class: `HotZeroHeap`.
392pub fn rawlsian_welfare(utilities: &[f64]) -> Result<f64, WelfareError> {
393    if utilities.is_empty() {
394        return Err(WelfareError::InsufficientData);
395    }
396    if utilities.len() > MAX_POPULATION {
397        return Err(WelfareError::BufferTooSmall);
398    }
399    let mut min = utilities[0];
400    if !finite(min) {
401        return Err(WelfareError::NonFinite);
402    }
403    for &u in &utilities[1..] {
404        if !finite(u) {
405            return Err(WelfareError::NonFinite);
406        }
407        if u < min {
408            min = u;
409        }
410    }
411    Ok(min)
412}
413
414/// Nash social welfare: the **product** of utilities, `prod_i u_i`.
415///
416/// This is the unnormalised Nash product (the sum of logs is the log of the
417/// product). It is *not* the geometric mean; divide by `n` externally if the
418/// geometric mean is required. All utilities must be strictly positive so the
419/// product is well-defined and non-degenerate; a single zero utility would
420/// collapse the product to zero and is rejected as `InvalidInput`. An empty
421/// population returns `InsufficientData`.
422///
423/// Allocation class: `HotZeroHeap`.
424pub fn nash_welfare(utilities: &[f64]) -> Result<f64, WelfareError> {
425    let n = validate_positive_population(utilities)?;
426    let mut product = 1.0f64;
427    for i in 0..n {
428        product *= utilities[i];
429    }
430    if !product.is_finite() {
431        return Err(WelfareError::NonFinite);
432    }
433    Ok(product)
434}
435
436// ---------------------------------------------------------------------------
437// Cost-benefit analysis
438// ---------------------------------------------------------------------------
439
440/// Net present value: `NPV = sum_{t=0}^{n_periods-1} (B_t - C_t) / (1+r)^t`.
441///
442/// `benefits` and `costs` must each have length `>= n_periods`; only the first
443/// `n_periods` entries are consumed. `discount_rate` must be finite and `> -1`
444/// (a rate of `-1` or below makes the discount factor non-positive). The
445/// period-0 cash flow is discounted by `(1+r)^0 = 1` (i.e. not discounted).
446///
447/// `n_periods` must be `> 0` and `<= MAX_POPULATION`.
448///
449/// Allocation class: `HotZeroHeap`.
450pub fn net_present_value(
451    benefits: &[f64],
452    costs: &[f64],
453    discount_rate: f64,
454    n_periods: usize,
455) -> Result<f64, WelfareError> {
456    if n_periods == 0 {
457        return Err(WelfareError::InsufficientData);
458    }
459    if n_periods > MAX_POPULATION {
460        return Err(WelfareError::BufferTooSmall);
461    }
462    if benefits.len() < n_periods || costs.len() < n_periods {
463        return Err(WelfareError::InvalidInput);
464    }
465    if !finite(discount_rate) || discount_rate <= -1.0 {
466        return Err(WelfareError::InvalidInput);
467    }
468    let one_plus_r = 1.0 + discount_rate;
469    let mut npv = 0.0f64;
470    // Documented convention: NPV = Σ_{t=0}^{n-1} (B_t − C_t)/(1+r)^t, so period 0
471    // is undiscounted ((1+r)^0 = 1) and each later period divides by another
472    // (1+r). (The prior code *multiplied* by (1+r) each period, computing a
473    // future value — the opposite of a present value.)
474    let mut discount = 1.0f64; // (1+r)^0
475    for t in 0..n_periods {
476        let b = benefits[t];
477        let c = costs[t];
478        if !finite(b) || !finite(c) {
479            return Err(WelfareError::NonFinite);
480        }
481        npv += (b - c) * discount;
482        discount /= one_plus_r;
483    }
484    if !npv.is_finite() {
485        return Err(WelfareError::NonFinite);
486    }
487    Ok(npv)
488}
489
490/// Distributional NPV: NPV with per-period distributional weights.
491///
492/// `NPV_w = sum_{t=0}^{n_periods-1} w_t * (B_t - C_t) / (1+r)^t`.
493///
494/// `weights` must have length `>= n_periods`. Weights must be finite and
495/// non-negative (a zero weight simply zeroes that period's contribution).
496/// `benefits`, `costs`, `discount_rate`, and `n_periods` follow the same
497/// rules as [`net_present_value`].
498///
499/// Returns a [`WelfareReport`] carrying the `ASSUMPTION_WEIGHTED` flag so
500/// downstream deontic / SHACL auditors can see that distributional weights
501/// were applied. `value` is the weighted NPV; `auxiliary` is the unweighted
502/// NPV for comparison.
503///
504/// Rights-affecting: distributional weights encode value judgements about
505/// whose benefits count how much. Pair with deontic / SHACL review before UI
506/// exposure.
507///
508/// Allocation class: `HotZeroHeap`.
509pub fn distributional_npv(
510    benefits: &[f64],
511    costs: &[f64],
512    weights: &[f64],
513    discount_rate: f64,
514    n_periods: usize,
515) -> Result<WelfareReport, WelfareError> {
516    if n_periods == 0 {
517        return Err(WelfareError::InsufficientData);
518    }
519    if n_periods > MAX_POPULATION {
520        return Err(WelfareError::BufferTooSmall);
521    }
522    if benefits.len() < n_periods || costs.len() < n_periods || weights.len() < n_periods {
523        return Err(WelfareError::InvalidInput);
524    }
525    if !finite(discount_rate) || discount_rate <= -1.0 {
526        return Err(WelfareError::InvalidInput);
527    }
528    let one_plus_r = 1.0 + discount_rate;
529    let mut weighted_npv = 0.0f64;
530    let mut unweighted_npv = 0.0f64;
531    let mut discount = 1.0f64;
532    for t in 0..n_periods {
533        let b = benefits[t];
534        let c = costs[t];
535        let w = weights[t];
536        if !finite(b) || !finite(c) || !finite(w) {
537            return Err(WelfareError::NonFinite);
538        }
539        if w < 0.0 {
540            return Err(WelfareError::InvalidInput);
541        }
542        let flow = (b - c) * discount;
543        weighted_npv += w * flow;
544        unweighted_npv += flow;
545        discount /= one_plus_r;
546    }
547    if !weighted_npv.is_finite() || !unweighted_npv.is_finite() {
548        return Err(WelfareError::NonFinite);
549    }
550    Ok(WelfareReport {
551        value: weighted_npv,
552        auxiliary: unweighted_npv,
553        assumptions: ASSUMPTION_WEIGHTED,
554        diagnostics: 0,
555    })
556}
557
558// ---------------------------------------------------------------------------
559// Needs / survival-floor allocation model
560// ---------------------------------------------------------------------------
561
562/// Allocate a fixed budget `budget` across `needs` so that each recipient
563/// first receives their survival floor `floors[i]`, then the residual is
564/// distributed proportionally to surplus need `needs[i] - floors[i]`.
565///
566/// Composes with deontic and capacity modalities: the returned
567/// [`WelfareReport`] carries assumption flags so a downstream deontic / SHACL
568/// layer can verify that floors were honoured (`ASSUMPTION_FLOOR_CLAMPED` is
569/// set when any allocation was clamped to the floor) and that the budget was
570/// sufficient (`ASSUMPTION_DEGENERATE` is set when the budget could not cover
571/// all floors, in which case floors are scaled proportionally).
572///
573/// `value` is the total actually allocated; `auxiliary` is the residual after
574/// floors (the amount distributed proportionally). Results are written into
575/// the caller-owned `out` buffer (`out.len() >= n`).
576///
577/// Rights-affecting: this model can determine access to subsistence resources.
578/// Pair with `OP_OBLIGATE`/`OP_FORBID` deontic checks and capacity-modalities
579/// review before any UI exposure or downstream transfer.
580///
581/// Allocation class: `HotZeroHeap`.
582pub fn survival_floor_allocation_into(
583    needs: &[f64],
584    floors: &[f64],
585    budget: f64,
586    out: &mut [f64],
587) -> Result<WelfareReport, WelfareError> {
588    if needs.is_empty() {
589        return Err(WelfareError::InsufficientData);
590    }
591    let n = needs.len();
592    if n > MAX_POPULATION {
593        return Err(WelfareError::BufferTooSmall);
594    }
595    if floors.len() != n || out.len() < n {
596        return Err(WelfareError::InvalidInput);
597    }
598    if !finite(budget) || budget < 0.0 {
599        return Err(WelfareError::InvalidInput);
600    }
601
602    let mut total_floor = 0.0f64;
603    let mut total_surplus_need = 0.0f64;
604    for i in 0..n {
605        if !finite(needs[i]) || !finite(floors[i]) {
606            return Err(WelfareError::NonFinite);
607        }
608        if needs[i] < 0.0 || floors[i] < 0.0 {
609            return Err(WelfareError::InvalidInput);
610        }
611        if floors[i] > needs[i] {
612            // Floor cannot exceed total need.
613            return Err(WelfareError::InvalidInput);
614        }
615        total_floor += floors[i];
616        total_surplus_need += needs[i] - floors[i];
617    }
618
619    let mut assumptions: u32 = 0;
620    let mut total_allocated = 0.0f64;
621    let mut residual_distributed = 0.0f64;
622
623    if budget >= total_floor {
624        // Floors fully covered; distribute residual proportionally to surplus need.
625        let residual = budget - total_floor;
626        for i in 0..n {
627            let base = floors[i];
628            let extra = if total_surplus_need > 0.0 {
629                residual * (needs[i] - floors[i]) / total_surplus_need
630            } else {
631                0.0
632            };
633            let alloc = base + extra;
634            out[i] = alloc;
635            total_allocated += alloc;
636            residual_distributed += extra;
637        }
638    } else {
639        // Insufficient budget: scale floors proportionally so no recipient is
640        // arbitrarily zeroed out. This is a degenerate (under-budget) case.
641        assumptions |= ASSUMPTION_DEGENERATE;
642        let scale = if total_floor > 0.0 {
643            budget / total_floor
644        } else {
645            0.0
646        };
647        for i in 0..n {
648            let alloc = floors[i] * scale;
649            out[i] = alloc;
650            total_allocated += alloc;
651        }
652        assumptions |= ASSUMPTION_FLOOR_CLAMPED;
653    }
654
655    if !total_allocated.is_finite() || !residual_distributed.is_finite() {
656        return Err(WelfareError::NonFinite);
657    }
658
659    Ok(WelfareReport {
660        value: total_allocated,
661        auxiliary: residual_distributed,
662        assumptions,
663        diagnostics: 0,
664    })
665}
666
667// ---------------------------------------------------------------------------
668// Tests
669// ---------------------------------------------------------------------------
670
671#[cfg(test)]
672mod tests {
673    use super::*;
674
675    fn approx(a: f64, b: f64) -> bool {
676        (a - b).abs() < 1e-9
677    }
678
679    // --- Gini ---------------------------------------------------------------
680
681    #[test]
682    fn gini_perfect_equality_is_zero() {
683        let incomes = [10.0, 10.0, 10.0];
684        let g = gini_coefficient(&incomes).unwrap();
685        assert!(approx(g, 0.0));
686    }
687
688    #[test]
689    fn gini_extreme_inequality_approaches_one_minus_one_over_n() {
690        // [0, 0, 100]: G = 1 - 1/n = 2/3 for n = 3.
691        let incomes = [0.0, 0.0, 100.0];
692        let g = gini_coefficient(&incomes).unwrap();
693        let expected = 1.0 - 1.0 / 3.0;
694        assert!(approx(g, expected));
695    }
696
697    #[test]
698    fn gini_two_person_split_is_one_half() {
699        // [0, 1]: G = 1 - 1/2 = 0.5.
700        let incomes = [0.0, 1.0];
701        let g = gini_coefficient(&incomes).unwrap();
702        assert!(approx(g, 0.5));
703    }
704
705    #[test]
706    fn gini_empty_is_insufficient_data() {
707        assert_eq!(gini_coefficient(&[]), Err(WelfareError::InsufficientData));
708    }
709
710    #[test]
711    fn gini_all_zero_is_invalid() {
712        assert_eq!(
713            gini_coefficient(&[0.0, 0.0]),
714            Err(WelfareError::InvalidInput)
715        );
716    }
717
718    #[test]
719    fn gini_nan_is_non_finite() {
720        assert_eq!(
721            gini_coefficient(&[1.0, f64::NAN]),
722            Err(WelfareError::NonFinite)
723        );
724    }
725
726    #[test]
727    fn gini_negative_is_invalid() {
728        assert_eq!(
729            gini_coefficient(&[1.0, -1.0]),
730            Err(WelfareError::InvalidInput)
731        );
732    }
733
734    // --- Lorenz -------------------------------------------------------------
735
736    #[test]
737    fn lorenz_curve_cumulative_shares() {
738        let incomes = [1.0, 2.0, 3.0];
739        let mut out = [0.0f64; 6];
740        let n = lorenz_curve_into(&incomes, &mut out).unwrap();
741        assert_eq!(n, 3);
742        // Sorted: [1, 2, 3], total = 6.
743        // Points: (1/3, 1/6), (2/3, 3/6=1/2), (3/3=1, 6/6=1).
744        assert!(approx(out[0], 1.0 / 3.0));
745        assert!(approx(out[1], 1.0 / 6.0));
746        assert!(approx(out[2], 2.0 / 3.0));
747        assert!(approx(out[3], 0.5));
748        assert!(approx(out[4], 1.0));
749        assert!(approx(out[5], 1.0));
750    }
751
752    #[test]
753    fn lorenz_buffer_too_small() {
754        let incomes = [1.0, 2.0, 3.0];
755        let mut out = [0.0f64; 5]; // need 6
756        assert_eq!(
757            lorenz_curve_into(&incomes, &mut out),
758            Err(WelfareError::BufferTooSmall)
759        );
760    }
761
762    #[test]
763    fn lorenz_empty_is_insufficient_data() {
764        let mut out = [0.0f64; 2];
765        assert_eq!(
766            lorenz_curve_into(&[], &mut out),
767            Err(WelfareError::InsufficientData)
768        );
769    }
770
771    // --- Atkinson -----------------------------------------------------------
772
773    #[test]
774    fn atkinson_equality_is_zero() {
775        let incomes = [10.0, 10.0, 10.0];
776        let a = atkinson_inequality(&incomes, 0.5).unwrap();
777        assert!(approx(a, 0.0));
778    }
779
780    #[test]
781    fn atkinson_higher_epsilon_is_more_inequality_averse() {
782        let incomes = [1.0, 2.0, 10.0];
783        let a_low = atkinson_inequality(&incomes, 0.5).unwrap();
784        let a_high = atkinson_inequality(&incomes, 2.0).unwrap();
785        assert!(a_high > a_low, "higher epsilon must yield higher A");
786    }
787
788    #[test]
789    fn atkinson_epsilon_one_uses_log_form() {
790        let incomes = [1.0, 2.0, 4.0];
791        let a = atkinson_inequality(&incomes, 1.0).unwrap();
792        // geometric mean = (1*2*4)^(1/3) = 8^(1/3) = 2
793        // arithmetic mean = 7/3
794        // A = 1 - 2 / (7/3) = 1 - 6/7 = 1/7
795        assert!(approx(a, 1.0 / 7.0));
796    }
797
798    #[test]
799    fn atkinson_zero_income_is_invalid() {
800        assert_eq!(
801            atkinson_inequality(&[0.0, 1.0], 0.5),
802            Err(WelfareError::InvalidInput)
803        );
804    }
805
806    #[test]
807    fn atkinson_nonpositive_epsilon_is_invalid() {
808        assert_eq!(
809            atkinson_inequality(&[1.0, 2.0], 0.0),
810            Err(WelfareError::InvalidInput)
811        );
812        assert_eq!(
813            atkinson_inequality(&[1.0, 2.0], -1.0),
814            Err(WelfareError::InvalidInput)
815        );
816    }
817
818    // --- Headcount ----------------------------------------------------------
819
820    #[test]
821    fn headcount_counts_poor_and_ratio() {
822        let incomes = [5.0, 15.0, 25.0];
823        let (count, ratio) = headcount_poverty(&incomes, 10.0).unwrap();
824        assert_eq!(count, 1);
825        assert!(approx(ratio, 1.0 / 3.0));
826    }
827
828    #[test]
829    fn headcount_none_poor() {
830        let incomes = [20.0, 30.0];
831        let (count, ratio) = headcount_poverty(&incomes, 10.0).unwrap();
832        assert_eq!(count, 0);
833        assert!(approx(ratio, 0.0));
834    }
835
836    #[test]
837    fn headcount_line_at_income_excludes_boundary() {
838        // Strictly below the line: an income equal to the line is not poor.
839        let incomes = [10.0, 20.0];
840        let (count, _) = headcount_poverty(&incomes, 10.0).unwrap();
841        assert_eq!(count, 0);
842    }
843
844    #[test]
845    fn headcount_zero_line_is_invalid() {
846        assert_eq!(
847            headcount_poverty(&[1.0, 2.0], 0.0),
848            Err(WelfareError::InvalidInput)
849        );
850    }
851
852    // --- Poverty gap --------------------------------------------------------
853
854    #[test]
855    fn poverty_gap_ratio_basic() {
856        let incomes = [5.0, 15.0, 25.0];
857        let g = poverty_gap_ratio(&incomes, 10.0).unwrap();
858        // gap = 5; n*line = 30; 5/30 = 1/6.
859        assert!(approx(g, 1.0 / 6.0));
860    }
861
862    #[test]
863    fn poverty_gap_none_poor_is_zero() {
864        let incomes = [20.0, 30.0];
865        let g = poverty_gap_ratio(&incomes, 10.0).unwrap();
866        assert!(approx(g, 0.0));
867    }
868
869    #[test]
870    fn poverty_gap_all_zero_is_one() {
871        let incomes = [0.0, 0.0];
872        let g = poverty_gap_ratio(&incomes, 10.0).unwrap();
873        assert!(approx(g, 1.0));
874    }
875
876    // --- Utilitarian / Rawlsian / Nash --------------------------------------
877
878    #[test]
879    fn utilitarian_is_sum() {
880        let u = [1.0, 2.0, 3.0];
881        assert!(approx(utilitarian_welfare(&u).unwrap(), 6.0));
882    }
883
884    #[test]
885    fn utilitarian_allows_negative() {
886        let u = [-1.0, 2.0, 3.0];
887        assert!(approx(utilitarian_welfare(&u).unwrap(), 4.0));
888    }
889
890    #[test]
891    fn rawlsian_is_min() {
892        let u = [1.0, 2.0, 3.0];
893        assert!(approx(rawlsian_welfare(&u).unwrap(), 1.0));
894    }
895
896    #[test]
897    fn rawlsian_negative_min() {
898        let u = [-5.0, 2.0, 3.0];
899        assert!(approx(rawlsian_welfare(&u).unwrap(), -5.0));
900    }
901
902    #[test]
903    fn nash_is_product() {
904        let u = [1.0, 2.0, 3.0];
905        assert!(approx(nash_welfare(&u).unwrap(), 6.0));
906    }
907
908    #[test]
909    fn nash_zero_utility_is_invalid() {
910        assert_eq!(nash_welfare(&[0.0, 2.0]), Err(WelfareError::InvalidInput));
911    }
912
913    #[test]
914    fn nash_negative_utility_is_invalid() {
915        assert_eq!(nash_welfare(&[-1.0, 2.0]), Err(WelfareError::InvalidInput));
916    }
917
918    #[test]
919    fn welfare_empty_is_insufficient_data() {
920        assert_eq!(
921            utilitarian_welfare(&[]),
922            Err(WelfareError::InsufficientData)
923        );
924        assert_eq!(rawlsian_welfare(&[]), Err(WelfareError::InsufficientData));
925        assert_eq!(nash_welfare(&[]), Err(WelfareError::InsufficientData));
926    }
927
928    #[test]
929    fn welfare_nan_is_non_finite() {
930        assert_eq!(
931            utilitarian_welfare(&[1.0, f64::NAN]),
932            Err(WelfareError::NonFinite)
933        );
934        assert_eq!(
935            rawlsian_welfare(&[1.0, f64::NAN]),
936            Err(WelfareError::NonFinite)
937        );
938    }
939
940    // --- NPV ----------------------------------------------------------------
941
942    #[test]
943    fn npv_basic_discounting() {
944        let benefits = [10.0, 10.0];
945        let costs = [5.0, 5.0];
946        let r = 0.1;
947        let npv = net_present_value(&benefits, &costs, r, 2).unwrap();
948        // Documented convention (period 0 undiscounted): 5/(1.1)^0 + 5/(1.1)^1.
949        // (The prior expected value 5/1.1 + 5/1.21 discounted period 0 too, which
950        // contradicts both the doc comment and `npv_period_zero_not_discounted`.)
951        let expected = 5.0 + 5.0 / 1.1;
952        assert!(approx(npv, expected));
953    }
954
955    #[test]
956    fn npv_period_zero_not_discounted() {
957        let benefits = [100.0, 0.0];
958        let costs = [0.0, 0.0];
959        let npv = net_present_value(&benefits, &costs, 0.5, 2).unwrap();
960        assert!(approx(npv, 100.0));
961    }
962
963    #[test]
964    fn npv_zero_rate_is_sum() {
965        let benefits = [10.0, 10.0, 10.0];
966        let costs = [1.0, 2.0, 3.0];
967        let npv = net_present_value(&benefits, &costs, 0.0, 3).unwrap();
968        assert!(approx(npv, 24.0));
969    }
970
971    #[test]
972    fn npv_length_mismatch_is_invalid() {
973        let benefits = [10.0];
974        let costs = [5.0, 5.0];
975        assert_eq!(
976            net_present_value(&benefits, &costs, 0.1, 2),
977            Err(WelfareError::InvalidInput)
978        );
979    }
980
981    #[test]
982    fn npv_zero_periods_is_insufficient_data() {
983        assert_eq!(
984            net_present_value(&[1.0], &[1.0], 0.1, 0),
985            Err(WelfareError::InsufficientData)
986        );
987    }
988
989    #[test]
990    fn npv_rate_at_minus_one_is_invalid() {
991        assert_eq!(
992            net_present_value(&[1.0], &[1.0], -1.0, 1),
993            Err(WelfareError::InvalidInput)
994        );
995    }
996
997    // --- Distributional NPV -------------------------------------------------
998
999    #[test]
1000    fn distributional_npv_applies_weights() {
1001        let benefits = [10.0, 10.0];
1002        let costs = [5.0, 5.0];
1003        let weights = [1.0, 2.0];
1004        let r = 0.1;
1005        let report = distributional_npv(&benefits, &costs, &weights, r, 2).unwrap();
1006        // t=0: *1.0 , t=1: /1.1
1007        let expected_weighted = 1.0 * 5.0 + 2.0 * 5.0 / 1.1;
1008        let expected_unweighted = 5.0 + 5.0 / 1.1;
1009        assert!(approx(report.value, expected_weighted));
1010        assert!(approx(report.auxiliary, expected_unweighted));
1011        assert!(report.assumptions & ASSUMPTION_WEIGHTED != 0);
1012    }
1013
1014    #[test]
1015    fn distributional_npv_negative_weight_is_invalid() {
1016        assert_eq!(
1017            distributional_npv(&[10.0], &[5.0], &[-1.0], 0.1, 1),
1018            Err(WelfareError::InvalidInput)
1019        );
1020    }
1021
1022    #[test]
1023    fn distributional_npv_weights_length_mismatch() {
1024        assert_eq!(
1025            distributional_npv(&[10.0, 10.0], &[5.0, 5.0], &[1.0], 0.1, 2),
1026            Err(WelfareError::InvalidInput)
1027        );
1028    }
1029
1030    // --- Survival-floor allocation ------------------------------------------
1031
1032    #[test]
1033    fn allocation_covers_floors_then_distributes_residual() {
1034        let needs = [10.0, 20.0, 30.0];
1035        let floors = [4.0, 5.0, 6.0];
1036        let budget = 25.0; // total_floor = 15, residual = 10
1037        let mut out = [0.0f64; 3];
1038        let report = survival_floor_allocation_into(&needs, &floors, budget, &mut out).unwrap();
1039        // surplus needs: 6, 15, 24 -> total 45
1040        // extras: 10*6/45, 10*15/45, 10*24/45
1041        let expected = [
1042            4.0 + 10.0 * 6.0 / 45.0,
1043            5.0 + 10.0 * 15.0 / 45.0,
1044            6.0 + 10.0 * 24.0 / 45.0,
1045        ];
1046        for i in 0..3 {
1047            assert!(approx(out[i], expected[i]));
1048        }
1049        assert!(approx(report.value, budget));
1050        assert!(approx(report.auxiliary, 10.0));
1051        assert_eq!(report.assumptions, 0);
1052    }
1053
1054    #[test]
1055    fn allocation_under_budget_scales_floors() {
1056        let needs = [10.0, 20.0];
1057        let floors = [4.0, 6.0];
1058        let budget = 5.0; // total_floor = 10 > budget -> degenerate
1059        let mut out = [0.0f64; 2];
1060        let report = survival_floor_allocation_into(&needs, &floors, budget, &mut out).unwrap();
1061        // scale = 5/10 = 0.5 -> [2, 3]
1062        assert!(approx(out[0], 2.0));
1063        assert!(approx(out[1], 3.0));
1064        assert!(approx(report.value, 5.0));
1065        assert!(report.assumptions & ASSUMPTION_DEGENERATE != 0);
1066        assert!(report.assumptions & ASSUMPTION_FLOOR_CLAMPED != 0);
1067    }
1068
1069    #[test]
1070    fn allocation_floor_exceeds_need_is_invalid() {
1071        assert_eq!(
1072            survival_floor_allocation_into(&[5.0], &[10.0], 100.0, &mut [0.0]),
1073            Err(WelfareError::InvalidInput)
1074        );
1075    }
1076
1077    #[test]
1078    fn allocation_buffer_too_small() {
1079        let needs = [10.0, 20.0];
1080        let floors = [4.0, 6.0];
1081        let mut out = [0.0f64; 1];
1082        assert_eq!(
1083            survival_floor_allocation_into(&needs, &floors, 100.0, &mut out),
1084            Err(WelfareError::InvalidInput)
1085        );
1086    }
1087
1088    #[test]
1089    fn allocation_empty_is_insufficient_data() {
1090        assert_eq!(
1091            survival_floor_allocation_into(&[], &[], 100.0, &mut []),
1092            Err(WelfareError::InsufficientData)
1093        );
1094    }
1095
1096    // --- Error classification -----------------------------------------------
1097
1098    #[test]
1099    fn error_is_caller_error_classification() {
1100        assert!(WelfareError::InvalidInput.is_caller_error());
1101        assert!(WelfareError::InsufficientData.is_caller_error());
1102        assert!(WelfareError::BufferTooSmall.is_caller_error());
1103        assert!(!WelfareError::NonFinite.is_caller_error());
1104    }
1105
1106    #[test]
1107    fn welfare_report_clean_constructor() {
1108        let r = WelfareReport::clean(1.0, 2.0);
1109        assert_eq!(r.value, 1.0);
1110        assert_eq!(r.auxiliary, 2.0);
1111        assert_eq!(r.assumptions, 0);
1112        assert_eq!(r.diagnostics, 0);
1113    }
1114
1115    #[test]
1116    fn welfare_report_with_assumptions_constructor() {
1117        let r = WelfareReport::with_assumptions(1.0, 2.0, ASSUMPTION_WEIGHTED);
1118        assert!(r.assumptions & ASSUMPTION_WEIGHTED != 0);
1119    }
1120
1121    #[test]
1122    fn over_capacity_population_is_buffer_too_small() {
1123        let big = [1.0f64; MAX_POPULATION + 1];
1124        // Use a small slice that exceeds capacity.
1125        let slice = &big[..MAX_POPULATION + 1];
1126        assert_eq!(gini_coefficient(slice), Err(WelfareError::BufferTooSmall));
1127    }
1128}