Coverage for src/courtpy/critic/_strata.py: 100%

28 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-22 15:51 +0000

1"""Strata of cases (such as a court in a year), which the critics share. 

2 

3Panels are assigned at random within a court in a year (or so a study 

4assumes), so the critics compare cases only with the cases of their own 

5stratum: they remove each stratum's mean and shuffle values within strata. 

6 

7Contents: 

8 demean: returns values less the mean of their stratum. 

9 permute_within: returns values shuffled within their strata. 

10 stratum_codes: returns the stratum of each row as a whole number. 

11 

12""" 

13 

14from __future__ import annotations 

15 

16from collections.abc import Sequence 

17 

18import numpy as np 

19import pandas as pd 

20 

21from ..core import cases 

22 

23""" Public Functions """ 

24 

25 

26def demean(values: np.ndarray, codes: np.ndarray) -> np.ndarray: 

27 """Returns values less the mean of their stratum. 

28 

29 Args: 

30 values: the values, one for each row (or a column for each of 

31 several variables, a row for each row of the data). 

32 codes: the stratum of each row (see `stratum_codes`), from 0. 

33 

34 Returns: 

35 The values, with the mean of each stratum's values subtracted from 

36 them, in the shape of `values`. 

37 

38 """ 

39 counts = np.bincount(codes) 

40 if values.ndim == 1: 

41 means = np.bincount(codes, weights = values) / counts 

42 single: np.ndarray = values - means[codes] 

43 return single 

44 centered = np.empty_like(values, dtype = float) 

45 for column in range(values.shape[1]): 

46 means = np.bincount(codes, weights = values[:, column]) / counts 

47 centered[:, column] = values[:, column] - means[codes] 

48 return centered 

49 

50 

51def permute_within( 

52 values: np.ndarray, 

53 codes: np.ndarray, 

54 generator: np.random.Generator) -> np.ndarray: 

55 """Returns values shuffled within their strata. 

56 

57 Args: 

58 values: the values, one for each row. 

59 codes: the stratum of each row (see `stratum_codes`). 

60 generator: the source of random numbers. 

61 

62 Returns: 

63 The values, each moved to a random row of its own stratum, so each 

64 stratum keeps the same values (and so the same mean). 

65 

66 """ 

67 ordered = np.argsort(codes, kind = 'stable') 

68 shuffled = np.lexsort((generator.random(len(codes)), codes)) 

69 permuted = np.empty_like(values) 

70 permuted[ordered] = values[shuffled] 

71 return permuted 

72 

73 

74def stratum_codes( 

75 data: pd.DataFrame, 

76 columns: Sequence[str]) -> pd.Series: 

77 """Returns the stratum of each row as a whole number. 

78 

79 Args: 

80 data: the rows. 

81 columns: the columns whose values together make a stratum, such as 

82 "court_num" and "year". 

83 

84 Raises: 

85 KeyError: if `data` lacks a column of `columns`. 

86 

87 Returns: 

88 A number for each stratum, from 0, with -1 for a row that is missing 

89 any of `columns`. 

90 

91 """ 

92 cases.require_columns(data, list(columns), 'the strata') 

93 codes, _ = pd.MultiIndex.from_frame( 

94 data[list(columns)].astype('string')).factorize() 

95 missing = data[list(columns)].isna().any(axis = 1).to_numpy() 

96 return pd.Series(np.where(missing, -1, codes), index = data.index)