riseup 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (361) hide show
  1. riseup/__init__.py +13 -0
  2. riseup/analysis/__init__.py +41 -0
  3. riseup/analysis/aggregate.py +279 -0
  4. riseup/analysis/balance.py +248 -0
  5. riseup/analysis/bootstrap.py +221 -0
  6. riseup/analysis/clustering.py +1271 -0
  7. riseup/analysis/compare.py +124 -0
  8. riseup/analysis/curves.py +127 -0
  9. riseup/analysis/evaluate.py +140 -0
  10. riseup/analysis/experiment.py +1456 -0
  11. riseup/analysis/importance.py +179 -0
  12. riseup/analysis/io/__init__.py +0 -0
  13. riseup/analysis/io/results.py +800 -0
  14. riseup/analysis/leaderboard.py +833 -0
  15. riseup/analysis/metrics/__init__.py +40 -0
  16. riseup/analysis/metrics/classification.py +274 -0
  17. riseup/analysis/metrics/clustering.py +133 -0
  18. riseup/analysis/metrics/episodes.py +577 -0
  19. riseup/analysis/metrics/registry.py +359 -0
  20. riseup/analysis/metrics/regression.py +82 -0
  21. riseup/analysis/metrics/values.py +308 -0
  22. riseup/analysis/novelty/__init__.py +10 -0
  23. riseup/analysis/novelty/alarms.py +808 -0
  24. riseup/analysis/novelty/calibrate.py +544 -0
  25. riseup/analysis/novelty/diagnostics.py +1185 -0
  26. riseup/analysis/novelty/layout.py +707 -0
  27. riseup/analysis/novelty/measures.py +726 -0
  28. riseup/analysis/novelty/profiles.py +701 -0
  29. riseup/analysis/novelty/readings.py +1461 -0
  30. riseup/analysis/permutation.py +275 -0
  31. riseup/analysis/selection.py +467 -0
  32. riseup/analysis/thresholds.py +370 -0
  33. riseup/dashboard/__init__.py +30 -0
  34. riseup/dashboard/__main__.py +6 -0
  35. riseup/dashboard/app.py +73 -0
  36. riseup/dashboard/browse.py +166 -0
  37. riseup/dashboard/cache.py +883 -0
  38. riseup/dashboard/cli.py +191 -0
  39. riseup/dashboard/guards.py +161 -0
  40. riseup/dashboard/jobs.py +396 -0
  41. riseup/dashboard/machine.py +75 -0
  42. riseup/dashboard/navigation.py +53 -0
  43. riseup/dashboard/pane.py +362 -0
  44. riseup/dashboard/refusal.py +38 -0
  45. riseup/dashboard/reset.py +56 -0
  46. riseup/dashboard/save_form.py +117 -0
  47. riseup/dashboard/state.py +57 -0
  48. riseup/dashboard/static/app.css +786 -0
  49. riseup/dashboard/static/logo-on-dark.svg +1 -0
  50. riseup/dashboard/static/logo-on-light.svg +1 -0
  51. riseup/dashboard/steps.py +214 -0
  52. riseup/dashboard/style.py +826 -0
  53. riseup/dashboard/tabs/__init__.py +1 -0
  54. riseup/dashboard/tabs/contact.py +69 -0
  55. riseup/dashboard/tabs/dataset.py +749 -0
  56. riseup/dashboard/tabs/dataset_participants.py +303 -0
  57. riseup/dashboard/tabs/explore.py +629 -0
  58. riseup/dashboard/tabs/explore_cohort.py +593 -0
  59. riseup/dashboard/tabs/explore_compare.py +565 -0
  60. riseup/dashboard/tabs/explore_features.py +259 -0
  61. riseup/dashboard/tabs/explore_quality.py +62 -0
  62. riseup/dashboard/tabs/explore_raw.py +228 -0
  63. riseup/dashboard/tabs/explore_sleep.py +254 -0
  64. riseup/dashboard/tabs/home.py +141 -0
  65. riseup/dashboard/tabs/models.py +947 -0
  66. riseup/dashboard/tabs/models_add.py +477 -0
  67. riseup/dashboard/tabs/models_launch.py +675 -0
  68. riseup/dashboard/tabs/models_runs.py +127 -0
  69. riseup/dashboard/tabs/models_settings.py +260 -0
  70. riseup/dashboard/tabs/preprocess.py +1070 -0
  71. riseup/dashboard/tabs/preprocess_features.py +502 -0
  72. riseup/dashboard/tabs/results.py +447 -0
  73. riseup/dashboard/tabs/results_clusters.py +462 -0
  74. riseup/dashboard/tabs/results_explain.py +269 -0
  75. riseup/dashboard/tabs/study_design.py +1342 -0
  76. riseup/dashboard/tabs/study_design_labels.py +377 -0
  77. riseup/dashboard/tabs/study_design_split.py +225 -0
  78. riseup/demo/__init__.py +73 -0
  79. riseup/demo/cohort.py +585 -0
  80. riseup/demo/episodic.py +566 -0
  81. riseup/demo/longitudinal.py +552 -0
  82. riseup/demo/minutes.py +414 -0
  83. riseup/demo/root.py +73 -0
  84. riseup/demo/sessions.py +944 -0
  85. riseup/demo/write.py +189 -0
  86. riseup/experiments/__init__.py +82 -0
  87. riseup/experiments/cluster_comparisons.py +534 -0
  88. riseup/experiments/compose.py +1799 -0
  89. riseup/experiments/design.py +234 -0
  90. riseup/experiments/gate.py +253 -0
  91. riseup/experiments/novelty.py +1272 -0
  92. riseup/experiments/pipeline.py +1473 -0
  93. riseup/experiments/places.py +342 -0
  94. riseup/experiments/readers.py +1178 -0
  95. riseup/experiments/results.py +328 -0
  96. riseup/experiments/specs.py +274 -0
  97. riseup/models/__init__.py +0 -0
  98. riseup/models/apply.py +1096 -0
  99. riseup/models/backbones/__init__.py +0 -0
  100. riseup/models/backbones/causal_transformer.py +63 -0
  101. riseup/models/backbones/day_tokeniser.py +219 -0
  102. riseup/models/backbones/dummy.py +55 -0
  103. riseup/models/backbones/embedding.py +68 -0
  104. riseup/models/backbones/masked_encoder.py +64 -0
  105. riseup/models/backbones/seasonal_naive.py +74 -0
  106. riseup/models/data/__init__.py +1 -0
  107. riseup/models/data/arrays.py +754 -0
  108. riseup/models/data/calendar.py +104 -0
  109. riseup/models/data/domain.py +199 -0
  110. riseup/models/data/labels.py +56 -0
  111. riseup/models/data/memory.py +26 -0
  112. riseup/models/data/normalise.py +860 -0
  113. riseup/models/data/reader.py +1350 -0
  114. riseup/models/data/split_files.py +66 -0
  115. riseup/models/data/splits.py +130 -0
  116. riseup/models/data/tabular.py +1675 -0
  117. riseup/models/day_reconstruction.py +306 -0
  118. riseup/models/domains.py +791 -0
  119. riseup/models/experiment.py +6285 -0
  120. riseup/models/explain/__init__.py +50 -0
  121. riseup/models/explain/frames.py +121 -0
  122. riseup/models/explain/gradients.py +277 -0
  123. riseup/models/explain/linear.py +98 -0
  124. riseup/models/explain/permutation.py +285 -0
  125. riseup/models/explain/tables.py +259 -0
  126. riseup/models/explain/trees.py +126 -0
  127. riseup/models/explanations.py +1008 -0
  128. riseup/models/fit.py +3465 -0
  129. riseup/models/foundation/__init__.py +32 -0
  130. riseup/models/foundation/base.py +524 -0
  131. riseup/models/foundation/cache.py +686 -0
  132. riseup/models/foundation/catalogue.py +504 -0
  133. riseup/models/foundation/chronos2.py +114 -0
  134. riseup/models/foundation/mantis.py +172 -0
  135. riseup/models/foundation/moment.py +146 -0
  136. riseup/models/foundation/pat.py +364 -0
  137. riseup/models/foundation/pat_network.py +173 -0
  138. riseup/models/foundation/standardise.py +224 -0
  139. riseup/models/foundation/weights.py +151 -0
  140. riseup/models/io/__init__.py +1 -0
  141. riseup/models/io/artifacts.py +647 -0
  142. riseup/models/io/runs.py +2351 -0
  143. riseup/models/kept.py +888 -0
  144. riseup/models/novelty/__init__.py +9 -0
  145. riseup/models/novelty/common_mode.py +989 -0
  146. riseup/models/novelty/contrast.py +677 -0
  147. riseup/models/novelty/experiment.py +1570 -0
  148. riseup/models/novelty/forecasters.py +137 -0
  149. riseup/models/novelty/models.py +273 -0
  150. riseup/models/novelty/peers.py +433 -0
  151. riseup/models/novelty/population_reference.py +1137 -0
  152. riseup/models/novelty/rounds.py +424 -0
  153. riseup/models/novelty/scorer.py +695 -0
  154. riseup/models/objectives.py +373 -0
  155. riseup/models/openmp.py +107 -0
  156. riseup/models/predict.py +361 -0
  157. riseup/models/pretrain.py +661 -0
  158. riseup/models/registry.py +1381 -0
  159. riseup/models/schema.py +1950 -0
  160. riseup/models/search.py +1618 -0
  161. riseup/models/supervised/__init__.py +22 -0
  162. riseup/models/supervised/base.py +1216 -0
  163. riseup/models/supervised/models.py +257 -0
  164. riseup/models/supervised/networks.py +244 -0
  165. riseup/models/tabular/__init__.py +8 -0
  166. riseup/models/tabular/models.py +1421 -0
  167. riseup/models/tasks/__init__.py +10 -0
  168. riseup/models/tasks/analyses.py +252 -0
  169. riseup/models/tasks/presets.py +273 -0
  170. riseup/models/tasks/spec.py +1021 -0
  171. riseup/models/tasks/support.py +1563 -0
  172. riseup/models/tasks/targets.py +248 -0
  173. riseup/models/tasks/units.py +1965 -0
  174. riseup/models/train/__init__.py +7 -0
  175. riseup/models/train/checkpoint.py +83 -0
  176. riseup/models/train/config.py +129 -0
  177. riseup/models/train/context.py +168 -0
  178. riseup/models/train/device.py +159 -0
  179. riseup/models/train/engine.py +525 -0
  180. riseup/models/train/ledger.py +60 -0
  181. riseup/models/train/logging/__init__.py +7 -0
  182. riseup/models/train/logging/local.py +111 -0
  183. riseup/models/train/logging/recording.py +441 -0
  184. riseup/models/train/logging/wandb_sink.py +311 -0
  185. riseup/models/train/losses.py +253 -0
  186. riseup/models/train/meters.py +71 -0
  187. riseup/models/train/optim.py +150 -0
  188. riseup/models/train/schedule.py +105 -0
  189. riseup/preprocessing/__init__.py +15 -0
  190. riseup/preprocessing/build_cost.py +321 -0
  191. riseup/preprocessing/build_settings.py +245 -0
  192. riseup/preprocessing/datasets/__init__.py +171 -0
  193. riseup/preprocessing/datasets/axivity/__init__.py +16 -0
  194. riseup/preprocessing/datasets/axivity/adapt.py +434 -0
  195. riseup/preprocessing/datasets/axivity/compliance.py +115 -0
  196. riseup/preprocessing/datasets/axivity/fetch.py +322 -0
  197. riseup/preprocessing/datasets/axivity/synthetic.py +201 -0
  198. riseup/preprocessing/datasets/compliance.py +206 -0
  199. riseup/preprocessing/datasets/e4/__init__.py +56 -0
  200. riseup/preprocessing/datasets/e4/adapt.py +657 -0
  201. riseup/preprocessing/datasets/e4/compliance.py +265 -0
  202. riseup/preprocessing/datasets/e4/fetch.py +1070 -0
  203. riseup/preprocessing/datasets/e4/synthetic.py +322 -0
  204. riseup/preprocessing/datasets/eplus/__init__.py +61 -0
  205. riseup/preprocessing/datasets/eplus/adapt.py +903 -0
  206. riseup/preprocessing/datasets/eplus/compliance.py +170 -0
  207. riseup/preprocessing/datasets/eplus/fetch.py +577 -0
  208. riseup/preprocessing/datasets/eplus/materialize/__init__.py +424 -0
  209. riseup/preprocessing/datasets/eplus/materialize/_avro.py +76 -0
  210. riseup/preprocessing/datasets/eplus/materialize/_constants.py +151 -0
  211. riseup/preprocessing/datasets/eplus/materialize/_deployments.py +221 -0
  212. riseup/preprocessing/datasets/eplus/materialize/_manifest.py +246 -0
  213. riseup/preprocessing/datasets/eplus/materialize/_reconcile.py +272 -0
  214. riseup/preprocessing/datasets/eplus/materialize/_scan.py +324 -0
  215. riseup/preprocessing/datasets/eplus/sessions.py +189 -0
  216. riseup/preprocessing/datasets/fitbit_export/__init__.py +12 -0
  217. riseup/preprocessing/datasets/layout.py +31 -0
  218. riseup/preprocessing/io/__init__.py +18 -0
  219. riseup/preprocessing/io/batch_run.py +884 -0
  220. riseup/preprocessing/io/budget.py +418 -0
  221. riseup/preprocessing/io/canonical.py +3854 -0
  222. riseup/preprocessing/io/features.py +1092 -0
  223. riseup/preprocessing/io/paths.py +586 -0
  224. riseup/preprocessing/io/processes.py +530 -0
  225. riseup/preprocessing/io/qc_summary.py +299 -0
  226. riseup/preprocessing/io/run_marker.py +211 -0
  227. riseup/preprocessing/io/tree.py +268 -0
  228. riseup/preprocessing/io/workbench.py +454 -0
  229. riseup/preprocessing/labeling.py +1652 -0
  230. riseup/preprocessing/outcomes/__init__.py +39 -0
  231. riseup/preprocessing/outcomes/labels.py +2056 -0
  232. riseup/preprocessing/outcomes/other_events.py +391 -0
  233. riseup/preprocessing/outcomes/split_files.py +1368 -0
  234. riseup/preprocessing/outcomes/splits.py +1757 -0
  235. riseup/preprocessing/provenance.py +291 -0
  236. riseup/preprocessing/qc.py +142 -0
  237. riseup/preprocessing/rawsignal.py +248 -0
  238. riseup/preprocessing/schema.py +1836 -0
  239. riseup/preprocessing/sensors/__init__.py +26 -0
  240. riseup/preprocessing/sensors/accelerometer/__init__.py +22 -0
  241. riseup/preprocessing/sensors/accelerometer/calibration.py +190 -0
  242. riseup/preprocessing/sensors/accelerometer/cwa_reader.py +476 -0
  243. riseup/preprocessing/sensors/accelerometer/epoching.py +364 -0
  244. riseup/preprocessing/sensors/accelerometer/metrics.py +82 -0
  245. riseup/preprocessing/sensors/accelerometer/nonwear.py +306 -0
  246. riseup/preprocessing/sensors/accelerometer/readers.py +325 -0
  247. riseup/preprocessing/sensors/accelerometer/regrid.py +247 -0
  248. riseup/preprocessing/sensors/accelerometer/resampling.py +187 -0
  249. riseup/preprocessing/sensors/accelerometer/rescoring.py +170 -0
  250. riseup/preprocessing/sensors/accelerometer/sleep_episodes.py +519 -0
  251. riseup/preprocessing/sensors/accelerometer/sleep_window.py +447 -0
  252. riseup/preprocessing/sensors/accelerometer/staging.py +307 -0
  253. riseup/preprocessing/sensors/bvp/__init__.py +356 -0
  254. riseup/preprocessing/sensors/bvp/beats.py +451 -0
  255. riseup/preprocessing/sensors/bvp/epoching.py +117 -0
  256. riseup/preprocessing/sensors/bvp/prv.py +434 -0
  257. riseup/preprocessing/sensors/bvp/quality.py +110 -0
  258. riseup/preprocessing/sensors/ecg/__init__.py +6 -0
  259. riseup/preprocessing/sensors/eda/__init__.py +266 -0
  260. riseup/preprocessing/sensors/eda/decompose.py +328 -0
  261. riseup/preprocessing/sensors/eda/epoching.py +180 -0
  262. riseup/preprocessing/sensors/eda/quality.py +407 -0
  263. riseup/preprocessing/sensors_extraction.py +1835 -0
  264. riseup/preprocessing/tables/__init__.py +36 -0
  265. riseup/preprocessing/tables/balance.py +40 -0
  266. riseup/preprocessing/tables/bands.py +75 -0
  267. riseup/preprocessing/tables/covariates.py +726 -0
  268. riseup/preprocessing/tables/coverage.py +157 -0
  269. riseup/preprocessing/tables/daily.py +773 -0
  270. riseup/preprocessing/tables/epochs.py +651 -0
  271. riseup/preprocessing/tables/participants.py +1313 -0
  272. riseup/preprocessing/tables/reduce.py +193 -0
  273. riseup/preprocessing/tables/sessions.py +399 -0
  274. riseup/preprocessing/timebase.py +569 -0
  275. riseup/preprocessing/windowing/__init__.py +38 -0
  276. riseup/preprocessing/windowing/classical.py +1548 -0
  277. riseup/preprocessing/windowing/dense.py +460 -0
  278. riseup/preprocessing/windowing/features/__init__.py +0 -0
  279. riseup/preprocessing/windowing/features/circadian/__init__.py +19 -0
  280. riseup/preprocessing/windowing/features/circadian/cosinor.py +403 -0
  281. riseup/preprocessing/windowing/features/circadian/nonparametric.py +397 -0
  282. riseup/preprocessing/windowing/features/day.py +246 -0
  283. riseup/preprocessing/windowing/features/descriptive.py +153 -0
  284. riseup/preprocessing/windowing/nights.py +280 -0
  285. riseup/preprocessing/windowing/segments.py +624 -0
  286. riseup/preprocessing/windowing/stream.py +350 -0
  287. riseup/preprocessing/windowing/verify.py +316 -0
  288. riseup/run/__init__.py +47 -0
  289. riseup/run/_entry.py +527 -0
  290. riseup/run/apply.py +282 -0
  291. riseup/run/axivity.py +523 -0
  292. riseup/run/check_tables.py +651 -0
  293. riseup/run/compare_clusters.py +210 -0
  294. riseup/run/coverage.py +275 -0
  295. riseup/run/demo.py +249 -0
  296. riseup/run/e4.py +870 -0
  297. riseup/run/embed.py +416 -0
  298. riseup/run/eplus.py +883 -0
  299. riseup/run/eplus_materialize.py +253 -0
  300. riseup/run/experiment.py +1233 -0
  301. riseup/run/explain.py +413 -0
  302. riseup/run/labels.py +577 -0
  303. riseup/run/leaderboard.py +182 -0
  304. riseup/run/learners.py +77 -0
  305. riseup/run/predict.py +259 -0
  306. riseup/run/pretrain.py +741 -0
  307. riseup/run/split.py +958 -0
  308. riseup/run/status.py +176 -0
  309. riseup/run/windowing.py +1138 -0
  310. riseup/viz/__init__.py +25 -0
  311. riseup/viz/docs.py +98 -0
  312. riseup/viz/extracts.py +143 -0
  313. riseup/viz/figures.py +451 -0
  314. riseup/viz/palette.py +436 -0
  315. riseup/viz/render/__init__.py +5 -0
  316. riseup/viz/render/ds.py +127 -0
  317. riseup/viz/render/explain.py +432 -0
  318. riseup/viz/render/mpl.py +1920 -0
  319. riseup/viz/views/__init__.py +4 -0
  320. riseup/viz/views/actigram.py +455 -0
  321. riseup/viz/views/build_estimate.py +283 -0
  322. riseup/viz/views/cohort.py +1199 -0
  323. riseup/viz/views/cohort_export.py +503 -0
  324. riseup/viz/views/cohort_labels.py +221 -0
  325. riseup/viz/views/cohort_summary.py +847 -0
  326. riseup/viz/views/compare.py +444 -0
  327. riseup/viz/views/coverage.py +157 -0
  328. riseup/viz/views/dataset.py +1566 -0
  329. riseup/viz/views/demo.py +312 -0
  330. riseup/viz/views/effort.py +214 -0
  331. riseup/viz/views/embed_estimate.py +186 -0
  332. riseup/viz/views/experiment_files.py +406 -0
  333. riseup/viz/views/features.py +784 -0
  334. riseup/viz/views/foundation.py +668 -0
  335. riseup/viz/views/machine.py +186 -0
  336. riseup/viz/views/model.py +1325 -0
  337. riseup/viz/views/models_view.py +2583 -0
  338. riseup/viz/views/preprocess.py +2422 -0
  339. riseup/viz/views/qc_record.py +884 -0
  340. riseup/viz/views/raw.py +678 -0
  341. riseup/viz/views/readouts.py +106 -0
  342. riseup/viz/views/recording.py +796 -0
  343. riseup/viz/views/refusals.py +848 -0
  344. riseup/viz/views/reset.py +26 -0
  345. riseup/viz/views/results.py +2637 -0
  346. riseup/viz/views/run_progress.py +162 -0
  347. riseup/viz/views/signals.py +344 -0
  348. riseup/viz/views/sleep.py +618 -0
  349. riseup/viz/views/split_example.py +163 -0
  350. riseup/viz/views/split_use.py +1213 -0
  351. riseup/viz/views/steps.py +358 -0
  352. riseup/viz/views/study_design.py +1777 -0
  353. riseup/viz/views/windowing_example.py +159 -0
  354. riseup/viz/words.py +74 -0
  355. riseup-0.1.0a1.dist-info/METADATA +416 -0
  356. riseup-0.1.0a1.dist-info/RECORD +361 -0
  357. riseup-0.1.0a1.dist-info/WHEEL +5 -0
  358. riseup-0.1.0a1.dist-info/entry_points.txt +2 -0
  359. riseup-0.1.0a1.dist-info/licenses/LICENSE +397 -0
  360. riseup-0.1.0a1.dist-info/licenses/NOTICE +99 -0
  361. riseup-0.1.0a1.dist-info/top_level.txt +1 -0
riseup/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """RISE UP: an open-source platform for research with wearable data.
2
+
3
+ ``preprocessing`` brings each dataset to one common format, the canonical tables; ``models``, ``analysis`` and
4
+ ``experiments`` fit, score and record models on them; ``run`` holds the commands, ``dashboard`` the no-code app (its
5
+ views in ``viz``) and ``demo`` the invented demo datasets.
6
+ """
7
+
8
+ from importlib.metadata import version as _version
9
+
10
+ #: The installed release, read from the package's metadata, so ``pyproject.toml`` is the one place it is written.
11
+ __version__: str = _version("riseup")
12
+
13
+ del _version
@@ -0,0 +1,41 @@
1
+ """Outputs plus labels become claims.
2
+
3
+ ``models`` produces a fitted artifact and a table of
4
+ outputs; ``analysis`` consumes those outputs plus labels and produces
5
+ evaluation, stratification and comparison. They are siblings that talk through
6
+ a store on disk, **never through imports** -- with one exemption:
7
+
8
+ analysis -> preprocessing, and models.schema / models.io ONLY
9
+
10
+ the contract and the store, never the implementation. The producer owns the
11
+ contract, the same shape as ``models -> preprocessing.schema``. The reverse is
12
+ not allowed either: ``models`` imports nothing from ``analysis``
13
+ (``tests/models/test_import_purity.py``). Where a fit selects a model on a
14
+ tuning fold with the code it is judged by,
15
+ ``analysis``'s functions are lent to it as callables by ``riseup.experiments``,
16
+ the package above both that runs and scores an experiment.
17
+
18
+ 🛑 **This is where a scientific claim is made, and nowhere else.** A
19
+ training-time metric is a model-selection device, an evaluation metric is a
20
+ scientific claim, and the second never lives in ``models/``. Three consequences
21
+ that are easy to lose:
22
+
23
+ - **No result without its uncertainty**, and intervals are
24
+ **participant-clustered**. Windows within one person are not independent, so a
25
+ window-level bootstrap is far too narrow.
26
+ - **Comparison refuses what it cannot compare.** Two runs share an axis
27
+ only if they share cohort, split and labelling.
28
+ - **``analysis/`` output is the only candidate for leaving the
29
+ Workbench**, and then only through an explicit export step that holds every
30
+ stratum to the floor the dataset declares (``DisclosureFloor``; the step is
31
+ decided, not built).
32
+
33
+ Two paths: ``experiment.evaluate`` scores an experiment's scored rows (the
34
+ supervised trait task); ``evaluate.evaluate_run`` scores one prediction run (the single-run path). The open scoring questions
35
+ of episode detection -- what a true positive is when episode boundaries are fuzzy,
36
+ the tolerance threshold, how to score a subject with several episodes -- are
37
+ answered for online novelty detection (the ``state`` task):
38
+ the episode metrics in ``metrics/episodes.py``,
39
+ the tolerance in the alarm policies of ``novelty/alarms.py``. For every other
40
+ task they are **not settled here**.
41
+ """
@@ -0,0 +1,279 @@
1
+ """From scored rows to one score per scoring key: the aggregation registry.
2
+
3
+ A model scores **units** (windows of *L* days) or sequences of them; the claim
4
+ is about what the task's **level** scores once -- a person at ``participant``, a
5
+ recording session at ``session`` (``models.schema.scoring_key``). An
6
+ **aggregator** turns a group's rows into the one number it is scored by.
7
+ In the
8
+ matched reading a person is scored once **per matched set** they belong to, so
9
+ the grouping is :func:`aggregation_key`: (rung, reading, fold, set) plus the
10
+ scoring key. A control reused in two sets has two scores, each over that set's
11
+ dates. Every reduction in ``riseup/models`` and ``riseup/analysis`` that groups
12
+ "one per person" reads :func:`aggregation_key`; none spells the key again.
13
+
14
+ Four aggregators, each recorded with the result:
15
+
16
+ - ``mean_probability`` -- the mean of the person's row values, for a binary or
17
+ multiclass task. It keeps a ranking, so AUROC applies. **The headline.** On
18
+ rows already aggregated to one per person (the runner may do so per round to
19
+ bound its memory) it is the identity.
20
+ - ``mean_value`` -- the same mean, for a regression task: a scoring key's
21
+ prediction is the mean of its units' predicted values, so a visit's
22
+ prediction is the mean of its units'. A name of its own
23
+ because an aggregator's name is a hashed spec value (``level_aggregation``):
24
+ ``mean_probability`` keeps the kinds it had, and no id moves.
25
+ - ``key_value`` -- a clustering task's: the scoring key's one value, as its
26
+ key-level model gave it (an assignment, a cluster's score). A clustering rung
27
+ writes one row per key and output, so this is the identity; a group whose
28
+ values differ is refused, since an assignment is never averaged.
29
+ - ``majority_vote`` -- the share of the person's rows at or above a threshold.
30
+ Needs a threshold (from a threshold policy, ``analysis.thresholds``) and is
31
+ refused without one; binary only. Its person-level decision is then
32
+ ``share >= 0.5`` -- *against one half*. It needs unit rows:
33
+ on rows already aggregated to person level it would vote once.
34
+
35
+ Exact constants
36
+ ---------------
37
+ Every aggregator takes its group's mean as ``first + mean(x - first)``: the
38
+ group's first value plus the mean of each value's offset from it. A constant
39
+ group's offsets are all 0, so its mean is exactly its value, which a plain mean
40
+ of *n* copies of *p* need not be (``(0.1 + 0.1 + 0.1) / 3 != 0.1``). It matters
41
+ for a constant score: ``dummy_prior`` scores every unit its base rate, and a
42
+ plain mean that moved in its last bit with the number of units a person holds
43
+ would let AUROC rank the people by it, so the floor would score other than 0.5.
44
+ On any other group the two means differ in their last bits only.
45
+
46
+ A row whose ``value`` is ``NaN`` is a unit the rung could not score. It is left
47
+ out of the person's score; **a person with no scorable row is not scored and is
48
+ counted** (:func:`unscored`), never dropped in silence.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import dataclasses
54
+ import typing as t
55
+
56
+ import numpy as np
57
+ import pandas as pd
58
+
59
+ from riseup.models import schema
60
+
61
+ __all__ = [
62
+ "AGGREGATORS",
63
+ "Aggregator",
64
+ "CARRIED_COLUMNS",
65
+ "MAJORITY",
66
+ "PERSON_KEY",
67
+ "aggregate",
68
+ "aggregation_key",
69
+ "get_aggregator",
70
+ "unscored",
71
+ ]
72
+
73
+ #: The columns every aggregation groups by before the scoring key: one score per
74
+ #: (rung, reading, fold, matched set). ``set_id`` is null throughout the
75
+ #: unmatched reading, so there it adds nothing.
76
+ _GROUP_PREFIX: tuple[str, ...] = ("rung", "analysis", "fold", "set_id")
77
+
78
+
79
+ def aggregation_key(level: str) -> tuple[str, ...]:
80
+ """The grouping one score is computed over at task ``level``: the one definition.
81
+
82
+ ``("rung", "analysis", "fold", "set_id") + models.schema.scoring_key(level)``:
83
+ at ``participant`` one score per (rung, reading, fold, set, person), at
84
+ ``session`` one per (..., person, session).
85
+
86
+ Raises
87
+ ------
88
+ ValueError
89
+ A level not in ``models.schema.LEVELS``.
90
+ """
91
+ return _GROUP_PREFIX + tuple(schema.scoring_key(level))
92
+
93
+
94
+ #: The participant-level grouping, ``aggregation_key("participant")``: one score
95
+ #: per (rung, reading, fold, matched set, participant).
96
+ PERSON_KEY: tuple[str, ...] = aggregation_key("participant")
97
+
98
+ #: Columns constant within a person (or a set membership) that travel with the
99
+ #: score, each where the rows carry it: a classification task's class
100
+ #: (``target``) or a regression task's number (``target_value``), each in its
101
+ #: kind's place (``models.schema.scored_row_columns``). A group in which one of
102
+ #: them varies is refused: one target per scoring key.
103
+ CARRIED_COLUMNS: tuple[str, ...] = ("target", "target_value", "representative", "role", "output_kind")
104
+
105
+ #: The share at or above which a majority vote calls a person positive.
106
+ MAJORITY: float = 0.5
107
+
108
+
109
+ @dataclasses.dataclass(frozen=True)
110
+ class Aggregator:
111
+ """One registered aggregator.
112
+
113
+ Attributes
114
+ ----------
115
+ name : str
116
+ needs_threshold : bool
117
+ Refused without a threshold.
118
+ kinds : tuple of str
119
+ The task kinds it applies to.
120
+ description : str
121
+ """
122
+
123
+ name: str
124
+ needs_threshold: bool
125
+ kinds: tuple[str, ...]
126
+ description: str
127
+
128
+
129
+ #: Every aggregator's ``kinds`` is written out, never ``schema.TASK_KINDS``:
130
+ #: an aggregator's name is a hashed spec value (``level_aggregation``), so what
131
+ #: it applies to must not widen by itself when a task kind is added.
132
+ AGGREGATORS: dict[str, Aggregator] = {
133
+ "mean_probability": Aggregator(
134
+ "mean_probability", False, (schema.BINARY, schema.MULTICLASS),
135
+ "the mean of the person's row values; keeps a ranking, so AUROC applies"),
136
+ "majority_vote": Aggregator(
137
+ "majority_vote", True, (schema.BINARY,),
138
+ "the share of the person's rows at or above a threshold; positive when the share is at "
139
+ "least one half"),
140
+ "mean_value": Aggregator(
141
+ "mean_value", False, (schema.REGRESSION,),
142
+ "the mean of a regression task's predicted values over the scoring key's rows; a visit's "
143
+ "prediction is the mean of its units'"),
144
+ "key_value": Aggregator(
145
+ "key_value", False, (schema.CLUSTERING,),
146
+ "a clustering task's: the scoring key's one value (its assignment, a cluster's score), as its key-level "
147
+ "model gave it; a key whose rows differ is refused"),
148
+ }
149
+
150
+
151
+ def get_aggregator(name: str, task_kind: str | None = None) -> Aggregator:
152
+ """The registered aggregator ``name``, refusing an unknown one or one that does not apply to ``task_kind``."""
153
+ if name not in AGGREGATORS:
154
+ raise schema.SchemaError(f"unknown aggregation {name!r}; registered are {sorted(AGGREGATORS)}")
155
+ aggregator = AGGREGATORS[name]
156
+ if task_kind is not None and task_kind not in aggregator.kinds:
157
+ raise schema.SchemaError(
158
+ f"aggregation {name!r} applies to {list(aggregator.kinds)} tasks, not {task_kind!r}")
159
+ return aggregator
160
+
161
+
162
+ def _row_thresholds(rows: pd.DataFrame, threshold: t.Any) -> np.ndarray:
163
+ """One threshold per row, from a number, a thresholds table or a {(rung, fold): value} mapping."""
164
+ if threshold is None:
165
+ raise schema.SchemaError(
166
+ "aggregation 'majority_vote' needs a threshold; state a threshold policy")
167
+ if isinstance(threshold, pd.DataFrame):
168
+ schema.assert_thresholds(threshold)
169
+ joined = rows[["rung", "fold", "output"]].merge(
170
+ threshold[["rung", "fold", "output", "threshold"]], on=["rung", "fold", "output"],
171
+ how="left", validate="many_to_one")
172
+ values = joined["threshold"].to_numpy(dtype="float64")
173
+ elif isinstance(threshold, t.Mapping):
174
+ keys = zip(rows["rung"].tolist(), rows["fold"].tolist())
175
+ values = np.array([threshold.get(k, np.nan) for k in keys], dtype="float64")
176
+ else:
177
+ values = np.full(len(rows), float(threshold))
178
+ if np.isnan(values).any():
179
+ raise schema.SchemaError(
180
+ f"{int(np.isnan(values).sum())} row(s) have no threshold for their (rung, fold)")
181
+ return values
182
+
183
+
184
+ def aggregate(
185
+ rows: pd.DataFrame,
186
+ *,
187
+ level: str,
188
+ method: str = "mean_probability",
189
+ threshold: t.Any = None,
190
+ ) -> pd.DataFrame:
191
+ """Aggregate scored rows to one score per :func:`aggregation_key` group (per scoring key per set).
192
+
193
+ Parameters
194
+ ----------
195
+ rows : pandas.DataFrame
196
+ Scored rows (``models.schema.SCORED_ROW_COLUMNS``), or any frame with
197
+ the :func:`aggregation_key` columns, ``output`` and ``value``.
198
+ level : str
199
+ The task's level (``models.schema.LEVELS``): the grouping is
200
+ :func:`aggregation_key` of it, and ``output`` is always added to it, so
201
+ a multiclass task keeps one score per class.
202
+ method : str
203
+ A key of :data:`AGGREGATORS`.
204
+ threshold : float, pandas.DataFrame or mapping, optional
205
+ ``majority_vote`` only: one number, a thresholds table
206
+ (``models.schema.THRESHOLD_COLUMNS``), or ``{(rung, fold): value}``.
207
+
208
+ Returns
209
+ -------
210
+ pandas.DataFrame
211
+ :func:`aggregation_key` + ``output`` + the :data:`CARRIED_COLUMNS`
212
+ present + ``value`` (the group's score) + ``n_rows`` (scorable rows it
213
+ was computed from). Groups with no scorable row are absent; count them
214
+ with :func:`unscored`.
215
+
216
+ Raises
217
+ ------
218
+ SchemaError
219
+ An unknown method, a missing threshold, a multiclass majority vote, or
220
+ a carried column that varies within a group.
221
+ """
222
+ aggregator = get_aggregator(method)
223
+ by = list(aggregation_key(level))
224
+ missing = [c for c in [*by, "output", "value"] if c not in rows.columns]
225
+ if missing:
226
+ raise schema.SchemaError(f"cannot aggregate: rows lack column(s) {missing}")
227
+ carried = [c for c in CARRIED_COLUMNS if c in rows.columns and c not in by]
228
+ keys = [*by, "output"]
229
+ scored = rows.loc[rows["value"].notna(), [*keys, *carried, "value"]]
230
+ if aggregator.needs_threshold:
231
+ if scored["output"].nunique() > 1:
232
+ raise schema.SchemaError(
233
+ "aggregation 'majority_vote' is binary only; these rows carry several outputs")
234
+ cut = _row_thresholds(scored, threshold)
235
+ scored = scored.assign(value=(scored["value"].to_numpy() >= cut).astype("float64"))
236
+ grouped = scored.groupby(keys, dropna=False, observed=True, sort=True)
237
+ if aggregator.name == "key_value" and len(scored) and (grouped["value"].nunique() > 1).any():
238
+ raise schema.SchemaError(
239
+ "aggregation 'key_value' reads a scoring key's one value, and a key's rows hold several: a "
240
+ "clustering rung writes one row per key and output, and an assignment is never averaged")
241
+ # Every aggregator's mean is ``first + mean(x - first)`` (module docstring, *Exact constants*): a constant
242
+ # group's mean is then exactly its value, which a plain mean of its copies need not be.
243
+ first = grouped["value"].transform("first").to_numpy(dtype="float64")
244
+ offsets = scored.assign(value=scored["value"].to_numpy(dtype="float64") - first)
245
+ out = offsets.groupby(keys, dropna=False, observed=True, sort=True)["value"].agg(["mean", "size"])
246
+ out["mean"] = grouped["value"].first().to_numpy(dtype="float64") + out["mean"].to_numpy(dtype="float64")
247
+ out = out.rename(columns={"mean": "value", "size": "n_rows"})
248
+ if carried:
249
+ varying = grouped[carried].nunique(dropna=False)
250
+ bad = [c for c in carried if (varying[c] > 1).any()]
251
+ if bad:
252
+ raise schema.SchemaError(
253
+ f"column(s) {bad} vary within an aggregation group; they are one fact per "
254
+ "person (per set membership in the matched reading)")
255
+ out = grouped[carried].first().join(out)
256
+ out = out.reset_index()
257
+ out["n_rows"] = out["n_rows"].astype("int64")
258
+ return out[[*keys, *carried, "value", "n_rows"]]
259
+
260
+
261
+ def unscored(rows: pd.DataFrame, *, level: str) -> pd.DataFrame:
262
+ """The :func:`aggregation_key` groups with rows but no scorable one (every ``value`` NaN): who is not scored.
263
+
264
+ Returns the :func:`aggregation_key` (``level``) columns plus the
265
+ :data:`CARRIED_COLUMNS` present, one row per unscored group. A person must
266
+ be counted, never dropped in silence.
267
+ """
268
+ by = list(aggregation_key(level))
269
+ carried = [c for c in CARRIED_COLUMNS if c in rows.columns and c not in by]
270
+ has_value = rows["value"].notna().groupby(
271
+ [rows[c] for c in by], dropna=False, observed=True).any()
272
+ lost = has_value[~has_value].index
273
+ if len(lost) == 0:
274
+ return pd.DataFrame({c: pd.Series(dtype=rows[c].dtype) for c in [*by, *carried]})
275
+ firsts = rows.groupby(by, dropna=False, observed=True)[carried].first() if carried else None
276
+ frame = lost.to_frame(index=False)
277
+ if firsts is not None:
278
+ frame = frame.merge(firsts.reset_index(), on=by, how="left")
279
+ return frame
@@ -0,0 +1,248 @@
1
+ """The balance report: how far apart cases and controls sit on what a model could read besides the wearable data.
2
+
3
+ A matched set (a case and its controls, frozen with the split) exists
4
+ to compare people who share their calendar: a model that reads only the date
5
+ should score a set's case and its controls alike. Whether it can is a property
6
+ of the **units each reading scores**, not of any model, so it is measured on
7
+ the units, for every experiment whose task reads matched sets.
8
+ A calendar rung away from chance then
9
+ names its carrier without a refit.
10
+
11
+ The experiment runner (``models.experiment.run_experiment``) supplies the data:
12
+ every reading's units with the calendar inputs beside them
13
+ (``ExperimentOutcome.calendar``; the inputs are
14
+ ``models.data.tabular.calendar_inputs``, the definition the calendar rung
15
+ reads). This module describes them; nothing here knows which columns are
16
+ calendar ones, so any input column handed in is described the same way.
17
+
18
+ What one row says, top down
19
+ ---------------------------
20
+ For one reading, one outer fold, one stratum and one **input**:
21
+
22
+ 1. **Each member's value** is the mean of the input over the member's units in
23
+ its set -- the same aggregation a person's score uses (``mean_probability``
24
+ is a mean over units, so is this). A control reused in two sets has two
25
+ values, one per set, each over that set's units; it is one person in the
26
+ counts.
27
+ 2. **Each set's difference** is the case's value minus the mean of its
28
+ controls' values (equal to the mean of case minus control over its pairs).
29
+ A set without its case or without any control in the stratum is left out,
30
+ and counted (``attrs["sets_left_out"]``).
31
+ 3. **Over the fold's sets**: the mean difference, its standard deviation, the
32
+ mean absolute difference, and the **standardised mean difference** (SMD) of
33
+ the cases' member values against the controls'
34
+ (``preprocessing.tables.balance.standardised_differences``, with
35
+ :data:`SMD_MIN_N`), so it reads on the scale of the cohort's own balance
36
+ tables.
37
+ 4. **Over folds** (``fold == "all"``): the mean of the per-fold values, as every
38
+ result is summarised (a fold with no value makes the mean NaN rather than a
39
+ mean over fewer folds); the counts summed (each person is in one fold).
40
+
41
+ In the ``unmatched`` reading there are no sets: only the SMD, between every case
42
+ and every control of the fold (one value per person), which is the size of the
43
+ confound the matching is there to remove.
44
+
45
+ **The strata are the results table's**, from ``analysis.experiment._strata``:
46
+ ``all``, ``representative`` and one per report group of the task spec, each a
47
+ mask over the units, so a balance row and a result row with the same stratum
48
+ describe the same people.
49
+
50
+ Nothing is decided from the table: no threshold turns an imbalance into a
51
+ warning. No quantile is reported (a quantile of per-set differences is one
52
+ set's value); the counts on each row are what an export step's disclosure
53
+ floor holds it to (``models.schema.assert_balance``).
54
+ """
55
+
56
+ from __future__ import annotations
57
+
58
+ import typing as t
59
+
60
+ import numpy as np
61
+ import pandas as pd
62
+
63
+ from riseup.analysis import aggregate as aggregate_mod
64
+ from riseup.analysis import experiment as evaluation
65
+ from riseup.models import schema
66
+ from riseup.preprocessing.tables.balance import standardised_differences
67
+
68
+ __all__ = ["ID_COLUMNS", "SMD_MIN_N", "balance", "member_values"]
69
+
70
+ #: The fewest member values per group an SMD is computed over: a sample variance
71
+ #: needs two. Not a disclosure floor -- that is held on the counts, at export.
72
+ #: Recorded with the experiment (``record["balance"]["smd_min_n"]``).
73
+ SMD_MIN_N: int = 2
74
+
75
+ #: The identifying columns of the units handed in; every other column is an input.
76
+ ID_COLUMNS: tuple[str, ...] = (
77
+ "analysis", "fold", "set_id", "role", "participant_id", "session_id", "occasion_id", "representative",
78
+ "label_state", "target")
79
+
80
+
81
+ def member_values(units: pd.DataFrame, inputs: t.Sequence[str], *, matched: bool, level: str) -> pd.DataFrame:
82
+ """Each member's mean of every input over its units: one row per (fold, set, scoring key), or per (fold, scoring key).
83
+
84
+ The grouping is ``analysis.aggregate.aggregation_key(level)`` within one
85
+ reading: the member is a person at ``participant``, a person's session at
86
+ ``session``, a person's occasion at ``occasion`` -- what a score is
87
+ computed over.
88
+
89
+ Returns
90
+ -------
91
+ pandas.DataFrame
92
+ ``fold``, ``set_id``, the scoring key (``participant_id``, and
93
+ ``session_id`` at ``session``, ``occasion_id`` at ``occasion``), ``role``, ``target`` and one column per
94
+ input.
95
+ """
96
+ frame = units.assign(participant_id=units["participant_id"].astype(str))
97
+ scoring = [c for c in aggregate_mod.aggregation_key(level) if c not in ("rung", "analysis", "fold", "set_id")]
98
+ key = ["fold", "set_id", *scoring] if matched else ["fold", *scoring]
99
+ grouped = frame.groupby(key, observed=True, dropna=False, sort=True)
100
+ out = pd.concat([grouped[["role", "target"]].first(), grouped[list(inputs)].mean()], axis=1).reset_index()
101
+ if not matched:
102
+ out.insert(1, "set_id", pd.array([pd.NA] * len(out), dtype="Int64"))
103
+ return out[["fold", "set_id", *scoring, "role", "target", *inputs]]
104
+
105
+
106
+ def _summary(values: pd.DataFrame, inputs: list[str], *, matched: bool,
107
+ positive_class: str) -> tuple[dict[str, dict], int]:
108
+ """One fold's row per input, and how many sets were left out."""
109
+ left_out = 0
110
+ if matched:
111
+ is_case = (values["role"].astype(str) == "case").to_numpy(dtype=bool)
112
+ whole = values.assign(_case=is_case).groupby("set_id")["_case"].agg(["any", "all"])
113
+ kept = whole.index[whole["any"] & ~whole["all"]]
114
+ left_out = int(len(whole) - len(kept))
115
+ values = values.loc[values["set_id"].isin(kept).to_numpy(dtype=bool)]
116
+ is_case = (values["role"].astype(str) == "case").to_numpy(dtype=bool)
117
+ else:
118
+ is_case = (values["target"].astype(str) == positive_class).to_numpy(dtype=bool)
119
+ people = values["participant_id"].astype(str)
120
+ # Distinct people per side, each computed: at session level a person can sit on both.
121
+ n_people, n_positive = int(people.nunique()), int(people[is_case].nunique())
122
+ n_negative = int(people[~is_case].nunique())
123
+ smd = standardised_differences(values[inputs], pd.Series(is_case), pd.Series(~is_case), min_n=SMD_MIN_N)
124
+ n_sets = int(values["set_id"].nunique()) if matched else None
125
+ out = {}
126
+ for column in inputs:
127
+ row = {"mean_difference": np.nan, "sd_difference": np.nan, "mean_abs_difference": np.nan,
128
+ "smd": smd[column], "n_sets": n_sets, "n_participants": n_people, "n_positive": n_positive,
129
+ "n_negative": n_negative}
130
+ if matched and n_sets:
131
+ case_value = values.loc[is_case].set_index("set_id")[column]
132
+ control_mean = values.loc[~is_case].groupby("set_id")[column].mean()
133
+ difference = (case_value - control_mean.reindex(case_value.index)).dropna()
134
+ if len(difference):
135
+ row["mean_difference"] = float(difference.mean())
136
+ row["sd_difference"] = float(difference.std(ddof=1)) if len(difference) > 1 else np.nan
137
+ row["mean_abs_difference"] = float(difference.abs().mean())
138
+ out[column] = row
139
+ return out, left_out
140
+
141
+
142
+ def balance(
143
+ units: pd.DataFrame,
144
+ *,
145
+ positive_class: str,
146
+ level: str,
147
+ representative: t.Any,
148
+ report_groups: t.Mapping[str, t.Sequence[str]] | t.Sequence[tuple[str, t.Sequence[str]]] = (),
149
+ task_set: str | None = None,
150
+ ) -> pd.DataFrame:
151
+ """The balance table of every reading in ``units`` (module docstring), ``analysis_id`` ``"pending"``.
152
+
153
+ Parameters
154
+ ----------
155
+ units : pandas.DataFrame
156
+ One row per scored unit and reading: :data:`ID_COLUMNS` (``analysis``
157
+ one of ``models.schema.SCORED_ANALYSES``; ``occasion_id`` required at
158
+ ``level`` ``occasion`` only; ``set_id`` and ``role`` set
159
+ on the matched readings' rows) and one numeric column per input
160
+ (``ExperimentOutcome.calendar``).
161
+ positive_class : str
162
+ The case class: the unmatched reading's groups. A task without one (a
163
+ multiclass task) has no balance report: the runner records why instead.
164
+ level : str
165
+ The task's level (``models.schema.LEVELS``): a member's value is over
166
+ its scoring key's units (:func:`member_values`).
167
+ representative : None, object or "all"
168
+ The task spec's ``representative`` form, as ``evaluate`` takes it: under
169
+ ``"all"`` there is no ``representative`` stratum.
170
+ report_groups : mapping or sequence of pairs
171
+ The task spec's report groups, as ``analysis.experiment.evaluate``
172
+ takes them: each one stratum.
173
+ task_set : str, optional
174
+ Under ``single_split``, the scored task set the units are, stamped on
175
+ every row (as ``analysis.experiment.evaluate`` stamps its results);
176
+ ``None`` (null) over parts.
177
+
178
+ Returns
179
+ -------
180
+ pandas.DataFrame
181
+ ``models.schema.BALANCE_COLUMNS``, gated. ``attrs["sets_left_out"]``
182
+ maps each matched reading to, per fold (and ``"all"``), the sets of the
183
+ ``all`` stratum left out because their case or every control has no
184
+ unit there.
185
+
186
+ Raises
187
+ ------
188
+ ValueError
189
+ A missing identifying column, no input column, an unknown reading, or a
190
+ matched row without its set or role.
191
+ """
192
+ # occasion_id is required only where it is the scoring key; elsewhere it may be absent.
193
+ scoring = schema.scoring_key(level)
194
+ missing = [c for c in ID_COLUMNS if c not in units.columns and (c != schema.OCCASION_COLUMN or c in scoring)]
195
+ if missing:
196
+ raise ValueError(f"balance needs the columns {list(ID_COLUMNS)}; missing {missing}")
197
+ inputs = [c for c in units.columns if c not in ID_COLUMNS]
198
+ if not inputs:
199
+ raise ValueError("balance was given no input column to describe")
200
+ stray = sorted(set(units["analysis"].astype(str)) - set(schema.SCORED_ANALYSES))
201
+ if stray:
202
+ raise ValueError(f"analysis holds {stray}; the readings are {list(schema.SCORED_ANALYSES)}")
203
+ on_sets = units["analysis"].isin(schema.MATCHED_ANALYSES).to_numpy(dtype=bool)
204
+ if (units.loc[on_sets, ["set_id", "role"]].isna().any(axis=1)).any():
205
+ raise ValueError("a matched reading's unit has no set or role; every member carries both")
206
+ units = units.astype({c: "float64" for c in inputs}).reset_index(drop=True)
207
+ groups = evaluation._report_groups(units, report_groups)
208
+ class_of_state = dict(zip(units["label_state"], units["target"]))
209
+ records: list[dict[str, t.Any]] = []
210
+ left: dict[str, dict[str, int]] = {}
211
+ for reading in [r for r in schema.SCORED_ANALYSES if (units["analysis"] == r).any()]:
212
+ matched = reading in schema.MATCHED_ANALYSES
213
+ part = units.loc[(units["analysis"] == reading).to_numpy(dtype=bool)].reset_index(drop=True)
214
+ folds = sorted(int(f) for f in part["fold"].dropna().unique())
215
+ strata = evaluation._strata(part, reading, groups, class_of_state,
216
+ representative_stratum=evaluation._column_form(representative))
217
+ for stratum, mask in strata:
218
+ values = member_values(part.loc[mask], inputs, matched=matched, level=level)
219
+ per_fold: dict[int, dict] = {}
220
+ for fold in folds:
221
+ here = values.loc[(values["fold"] == fold).to_numpy(dtype=bool)]
222
+ per_fold[fold], n_left = _summary(here, inputs, matched=matched, positive_class=positive_class)
223
+ if matched and stratum == evaluation.STRATUM_ALL:
224
+ left.setdefault(reading, {})[str(fold)] = n_left
225
+ for column in inputs:
226
+ rows = [per_fold[f][column] for f in folds]
227
+ for fold, row in zip(folds, rows):
228
+ records.append({"analysis": reading, "fold": str(fold), "stratum": stratum, "input": column,
229
+ **row})
230
+ records.append({
231
+ "analysis": reading, "fold": schema.FOLD_ALL, "stratum": stratum, "input": column,
232
+ **{k: float(np.mean([r[k] for r in rows])) if rows else np.nan
233
+ for k in ("mean_difference", "sd_difference", "mean_abs_difference", "smd")},
234
+ "n_sets": int(sum(r["n_sets"] for r in rows)) if matched else None,
235
+ **{k: int(sum(r[k] for r in rows)) for k in ("n_participants", "n_positive", "n_negative")},
236
+ })
237
+ if matched:
238
+ left[reading][schema.FOLD_ALL] = int(sum(left[reading].values()))
239
+ frame = pd.DataFrame(records, columns=[c for c in schema.BALANCE_COLUMNS if c != "analysis_id"])
240
+ frame.insert(0, "analysis_id", evaluation.PENDING_ANALYSIS_ID)
241
+ unmatched = ~frame["analysis"].isin(schema.MATCHED_ANALYSES)
242
+ frame.loc[unmatched, ["mean_difference", "sd_difference", "mean_abs_difference"]] = np.nan
243
+ frame["n_sets"] = pd.array([None if pd.isna(v) else int(v) for v in frame["n_sets"]], dtype="Int64")
244
+ frame["task_set"] = pd.array([task_set] * len(frame), dtype="string")
245
+ frame = frame.astype(schema.BALANCE_DTYPES).reset_index(drop=True)
246
+ schema.assert_balance(frame)
247
+ frame.attrs["sets_left_out"] = left
248
+ return frame