File size: 11,601 Bytes
e89a301 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | import unittest
import pandas as pd
import numpy as np
import numpy.testing as npt
import os
import itertools as it
# Canonical impl
from canonical import find_fair_ranking as canonical_find_fair_ranking
from canonical import query as canonical_query
# Generated impl
from ranking_2d import find_fair_ranking as generated_find_fair_ranking
from ranking_2d import query as generated_query
# Utils provided in your project
from utils import read_file, score, polartoscalar
class TestRankingImplementations(unittest.TestCase):
@classmethod
def setUpClass(cls):
# A few reusable mini datasets to hit different code paths
cls.datasets = {}
# Balanced two-group dataset (n divisible by buckets)
cls.datasets["balanced"] = pd.DataFrame({
"feature1": [10, 20, 30, 40, 50, 60, 70, 80],
"feature2": [1, 2, 3, 4, 5, 6, 7, 8],
"sensitive_attr": [0, 1, 0, 1, 0, 1, 0, 1]
})
# Imbalanced two-group dataset (to test minority logic, ratios)
cls.datasets["imbalanced"] = pd.DataFrame({
"feature1": [5, 7, 9, 11, 13, 15, 17, 19, 21],
"feature2": [1, 1, 2, 3, 5, 8, 13, 21, 34],
"sensitive_attr": [0, 0, 0, 0, 0, 1, 1, 1, 1]
})
# Single-group dataset (forces comb(|g|, 2) path; 0 collisions if buckets=1)
cls.datasets["single_group"] = pd.DataFrame({
"feature1": [1, 2, 3, 4, 5, 6],
"feature2": [6, 5, 4, 3, 2, 1],
"sensitive_attr": [1, 1, 1, 1, 1, 1]
})
# Non-divisible bucket case (n % m != 0) — tail elements ignored by bucket_size
cls.datasets["non_divisible"] = pd.DataFrame({
"feature1": [2, 4, 6, 8, 10, 12, 14],
"feature2": [3, 1, 4, 1, 5, 9, 2],
"sensitive_attr": [0, 1, 0, 1, 0, 1, 0]
})
# String sensitive attribute values (exercise mapping)
cls.datasets["string_group"] = pd.DataFrame({
"feature1": [100, 90, 80, 70, 60, 50],
"feature2": [0, 1, 1, 2, 3, 5],
"sensitive_attr": ["A", "A", "B", "B", "B", "A"]
})
# Persist CSVs for path-based tests
cls.csv_paths = {}
for name, df in cls.datasets.items():
p = f"__tmp_{name}.csv"
df.to_csv(p, index=False)
cls.csv_paths[name] = p
@classmethod
def tearDownClass(cls):
for p in cls.csv_paths.values():
if os.path.exists(p):
os.remove(p)
# ---------- Helpers ----------
def _run_both_find(self, source, columns, sens, m):
"""Run find_fair_ranking in both impls and return tuples."""
c = canonical_find_fair_ranking(source, columns, sens, m)
g = generated_find_fair_ranking(source, columns, sens, m)
return c, g
def _assert_find_equivalence(self, ctup, gtup, decimal=5):
(c_disp, c_disp0, c_rank, c_theta, c_dur) = ctup
(g_disp, g_disp0, g_rank, g_theta, g_dur) = gtup
# Core numeric comparisons
npt.assert_almost_equal(c_disp, c_disp, decimal)
npt.assert_almost_equal(c_disp, g_disp, decimal,
err_msg="Disparity mismatch")
npt.assert_almost_equal(c_disp0, g_disp0, decimal,
err_msg="Original disparity mismatch")
npt.assert_almost_equal(c_theta, g_theta, decimal,
err_msg="Theta mismatch")
# Rankings: length and set equality (permutation)
self.assertEqual(len(c_rank), len(g_rank), "Ranking length mismatch")
self.assertEqual(set(c_rank), set(range(len(c_rank))),
"Canonical ranking is not a permutation of 0..n-1")
self.assertEqual(set(g_rank), set(range(len(g_rank))),
"Generated ranking is not a permutation of 0..n-1")
# Duration sanity (don’t require equality due to noise)
self.assertIsInstance(c_dur, float)
self.assertIsInstance(g_dur, float)
self.assertGreaterEqual(c_dur, 0.0)
self.assertGreaterEqual(g_dur, 0.0)
def _prepare_query_inputs(self, source, columns, d, m):
# Compute theta via canonical impl to build f and scores
_, _, _, theta, _ = canonical_find_fair_ranking(source, columns, "sensitive_attr", m)
dataset = read_file(source, columns) if isinstance(source, str) else source[columns].values.tolist()
f = polartoscalar([theta], d)
scores = sorted([score(dataset[i], f, d) for i in range(len(dataset))])
return f, scores, theta
# ---------- Tests: find_fair_ranking parity across many shapes ----------
def test_find_fair_ranking_divisible_balanced(self):
df = self.datasets["balanced"]
columns = ["feature1", "feature2"]
m = 4 # n=8, bucket_size=2
ctup, gtup = self._run_both_find(df, columns, "sensitive_attr", m)
self._assert_find_equivalence(ctup, gtup)
def test_find_fair_ranking_divisible_balanced_path(self):
path = self.csv_paths["balanced"]
columns = ["feature1", "feature2"]
m = 4
ctup, gtup = self._run_both_find(path, columns, "sensitive_attr", m)
self._assert_find_equivalence(ctup, gtup)
def test_find_fair_ranking_imbalanced(self):
df = self.datasets["imbalanced"]
columns = ["feature1", "feature2"]
# Try different bucket counts (including 1 and n)
for m in [1, 3, len(df)]:
with self.subTest(m=m):
ctup, gtup = self._run_both_find(df, columns, "sensitive_attr", m)
self._assert_find_equivalence(ctup, gtup)
def test_find_fair_ranking_single_group(self):
df = self.datasets["single_group"]
columns = ["feature1", "feature2"]
# Buckets=1 => trivial / all in one bucket
for m in [1, 2, len(df)]:
with self.subTest(m=m):
ctup, gtup = self._run_both_find(df, columns, "sensitive_attr", m)
self._assert_find_equivalence(ctup, gtup)
def test_find_fair_ranking_non_divisible(self):
df = self.datasets["non_divisible"] # n=7
columns = ["feature1", "feature2"]
# m=3 => bucket_size=2, tail ignored in distribution loops
for m in [3, 5]:
with self.subTest(m=m):
ctup, gtup = self._run_both_find(df, columns, "sensitive_attr", m)
self._assert_find_equivalence(ctup, gtup)
def test_find_fair_ranking_string_sensitive(self):
df = self.datasets["string_group"]
columns = ["feature1", "feature2"]
for m in [2, 3, len(df)]:
with self.subTest(m=m):
ctup, gtup = self._run_both_find(df, columns, "sensitive_attr", m)
self._assert_find_equivalence(ctup, gtup)
# ---------- Tests: query parity and behaviors ----------
def test_query_parity_across_datasets(self):
combos = [
("balanced", 4),
("imbalanced", 3),
("single_group", 2),
("non_divisible", 3),
("string_group", 3),
]
for name, m in combos:
with self.subTest(dataset=name, buckets=m):
source = self.datasets[name]
columns = ["feature1", "feature2"]
d = 2
f, scores, _ = self._prepare_query_inputs(source, columns, d, m)
# Build a grid of queries around the data ranges
df = source
f1min, f1max = df["feature1"].min(), df["feature1"].max()
f2min, f2max = df["feature2"].min(), df["feature2"].max()
queries = [
[f1min, f2min], [f1max, f2max],
[(f1min + f1max) / 2, (f2min + f2max) / 2],
[f1min - 10, f2min - 10], # below range
[f1max + 10, f2max + 10], # above range
]
for q in queries:
c_res = canonical_query(q, f, scores, d, m)
g_res = generated_query(q, f, scores, d, m)
npt.assert_equal(c_res, g_res,
err_msg=f"Query mismatch for dataset={name}, q={q}, m={m}")
def test_query_monotonicity_by_projection(self):
# Larger projection should not map to a lower bucket
name, m = "balanced", 4
source = self.datasets[name]
columns = ["feature1", "feature2"]
d = 2
f, scores, _ = self._prepare_query_inputs(source, columns, d, m)
# Create pairs with increasing projection c
pairs = [
([10, 1], [80, 8]),
([15, 2], [60, 7]),
([20, 3], [50, 6]),
]
for q_low, q_high in pairs:
with self.subTest(low=q_low, high=q_high):
# Compute projection explicitly to sanity check the ordering
c_low = sum(f[j] * q_low[j] for j in range(d))
c_high = sum(f[j] * q_high[j] for j in range(d))
self.assertLessEqual(c_low, c_high, "Test data must have increasing projection")
c_bucket_low = canonical_query(q_low, f, scores, d, m)
c_bucket_high = canonical_query(q_high, f, scores, d, m)
g_bucket_low = generated_query(q_low, f, scores, d, m)
g_bucket_high = generated_query(q_high, f, scores, d, m)
# Parity
self.assertEqual(c_bucket_low, g_bucket_low)
self.assertEqual(c_bucket_high, g_bucket_high)
# Monotonicity (non-decreasing)
self.assertLessEqual(c_bucket_low, c_bucket_high)
def test_query_bucket_bounds_extremes(self):
# Ensure extreme projections land in first/last bucket consistently
name, m = "imbalanced", 3
source = self.datasets[name]
columns = ["feature1", "feature2"]
d = 2
f, scores, _ = self._prepare_query_inputs(source, columns, d, m)
# Far below and above the data range along the same direction
q_lo = [-1e6, -1e6]
q_hi = [1e6, 1e6]
c_lo = canonical_query(q_lo, f, scores, d, m)
g_lo = generated_query(q_lo, f, scores, d, m)
c_hi = canonical_query(q_hi, f, scores, d, m)
g_hi = generated_query(q_hi, f, scores, d, m)
self.assertEqual(c_lo, g_lo)
self.assertEqual(c_hi, g_hi)
# Buckets are 1-indexed in the canonical code
self.assertGreaterEqual(c_lo, 1)
self.assertIn(c_hi, [m, m+1])
# ---------- Robustness / sanity on output structure ----------
def test_find_returns_expected_tuple_shapes(self):
for name, df in self.datasets.items():
with self.subTest(dataset=name):
columns = ["feature1", "feature2"]
m = max(1, min(5, len(df))) # keep it sane
res = canonical_find_fair_ranking(df, columns, "sensitive_attr", m)
self.assertIsInstance(res, tuple)
self.assertEqual(len(res), 5)
disp, disp0, ranking, theta, duration = res
self.assertIsInstance(disp, (float, np.floating))
self.assertIsInstance(disp0, (float, np.floating, np.ndarray))
self.assertIsInstance(ranking, list)
self.assertIsInstance(theta, (int, float, np.integer, np.floating))
self.assertIsInstance(duration, (float, np.floating))
if __name__ == "__main__":
unittest.main(argv=["first-arg-is-ignored"], exit=False)
|