07 · Toy studies¶
You will learn how to get a complete, realistic study in one line from synaptome.datasets, one for
each common study design, and how to read the effects that were planted in it. Toy studies are handy to
try synaptome, to learn the statistics coming in the next tutorials, and to test your own analysis code:
you know the right answer in advance.
You need 02 · Units and variables (units vs dimensions) and
04 · Selecting and reshaping (to_df, table, reduce=).
import pandas as pd
import synaptome as syn
The eight studies¶
| Function | Design | Units | What differs |
|---|---|---|---|
case_control |
two independent groups | subject |
score by group |
crossover |
every subject under both conditions (paired) | subject |
score by condition |
longitudinal |
two groups weighed over weeks, some visits missing | subject |
weight curves and slopes by group |
simulation_benchmark |
methods compared over regions, repeated runs, noise levels | region > run |
accuracy by method |
timepoint_pairing |
methods compared sample by sample within one recording | subject |
correlation by method |
repeated_trials |
an ERP study: many trials per subject | subject > trial |
erp by group, around 300 ms |
crossed |
every subject sees every stimulus | trial < subject * stimulus |
rt by condition |
method_comparison |
methods scored per source against a reference, one method failing in some subjects | subject |
error by method |
Each call returns a new Study, fully defined: no definition is guessed, so no notice is shown.
A first toy study¶
A case-control study: 30 controls and 30 patients, with an age, a sex and a score.
study = syn.datasets.case_control()
study.describe()
| variable | level | dims | dtype | measurement_unit | units_with_values | units_at_level | values | missing | inferred | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | group | subject | category | NaN | 60 | 60 | 60 | 0 | False | |
| 1 | age | subject | int | years | 60 | 60 | 60 | 0 | False | |
| 2 | sex | subject | category | NaN | 60 | 60 | 60 | 0 | False | |
| 3 | score | subject | float | points | 60 | 60 | 60 | 0 | False |
What makes a toy study useful is that the truth is known. The planted effects are stored in the study
itself, in study.info.extra["planted"]. Each entry reads like a comparison: the outcome, the factor
by which it is compared, the contrast (first minus second) and the true value. A value of 0 is a
null effect: there is no difference to find, and a good analysis should not find one.
pd.DataFrame(study.info.extra["planted"])
| outcome | by | contrast | statistic | value | |
|---|---|---|---|---|---|
| 0 | score | group | [patient, control] | mean_diff | 10.0 |
| 1 | age | group | [patient, control] | mean_diff | 0.0 |
Plain pandas finds roughly the planted 10 points between patients and controls, and roughly no difference in age. "Roughly", because 30 subjects per group are a sample, not the whole population:
subjects = study.table("subject")
subjects.groupby("group", observed=True)[["score", "age"]].mean()
| score | age | |
|---|---|---|
| group | ||
| control | 51.746395 | 46.133333 |
| patient | 59.956273 | 43.9 |
Paired designs: factors as dimensions¶
In the crossover trial, condition is a dimension of score, not a subject variable: each subject
was measured under placebo and under drug. Here, subjects differ a lot from each other, but each
subject's two scores are close. That is why the comparison has to be paired:
crossover = syn.datasets.crossover()
scores = crossover.to_df("score").pivot(index="subject", columns="condition", values="score")
differences = scores["drug"] - scores["placebo"]
pd.Series(
{
"spread of placebo scores (SD)": scores["placebo"].std(),
"spread of the differences (SD)": differences.std(),
"mean difference (planted: 5)": differences.mean(),
}
).round(2)
spread of placebo scores (SD) 12.78 spread of the differences (SD) 4.64 mean difference (planted: 5) 4.96 dtype: float64
Curves, missing visits and slopes¶
In the longitudinal study, weight is a curve over week. Some visits are missing, so subjects don't all
have the same weeks:
weights = syn.datasets.longitudinal()
weights.to_df("weight").groupby("subject").size().value_counts()
7 19 6 9 5 2 Name: count, dtype: int64
Some entries hold one true value per week (along): the treated group starts losing weight after
week 4. Another entry is about each subject's slope, which reduce={"week": "slope"} computes:
curve = next(e for e in weights.info.extra["planted"] if e.get("along") == "week")
pd.Series(curve["value"], index=curve["coordinates"], name="treated - control (kg)")
0 0.0 2 0.0 4 0.0 6 -2.0 8 -4.0 10 -6.0 12 -8.0 Name: treated - control (kg), dtype: float64
slopes = weights.table("subject", ["group", "weight"], reduce={"week": "slope"})
slopes.groupby("group", observed=True)["weight"].mean()
group control 0.058651 treated -0.635364 Name: weight, dtype: float64
Repetitions and replicates¶
The simulation benchmark has repeated runs inside each region, a unit level (region > run), to average
before comparing methods. Its accuracy_boot variable holds upstream bootstrap draws of each run's
accuracy: a replicate variable (tutorial 02), linked to accuracy.
bench = syn.datasets.simulation_benchmark()
bench.variables.to_frame()[["name", "level", "dims", "replicates_of"]]
| name | level | dims | replicates_of | |
|---|---|---|---|---|
| 0 | accuracy | run | method, snr | NaN |
| 1 | accuracy_boot | run | method, snr, draw | accuracy |
per_region = bench.to_df("accuracy", reduce={"run": "mean"})
per_region.pivot_table(index="snr", columns="method", values="accuracy").round(3)
| method | a | b | wcset |
|---|---|---|---|
| snr | |||
| 0.0 | 0.501 | 0.533 | 0.535 |
| 5.0 | 0.576 | 0.604 | 0.610 |
| 10.0 | 0.647 | 0.679 | 0.680 |
| 20.0 | 0.807 | 0.833 | 0.827 |
repeated_trials has trials inside subjects, and crossed has trials that belong to a subject and
a stimulus, with the condition stored on the stimulus:
crossed = syn.datasets.crossed()
crossed.units
UnitHierarchy subject: 20 units stimulus: 16 units trial < subject * stimulus: 640 units
crossed.table("stimulus").head()
| stimulus | condition | |
|---|---|---|
| 0 | x01 | congruent |
| 1 | x02 | incongruent |
| 2 | x03 | congruent |
| 3 | x04 | incongruent |
| 4 | x05 | congruent |
Samples along time¶
In timepoint_pairing, the methods are compared at every time sample of one recording. Neighbouring
samples are strongly correlated (planted: 0.9), so 500 samples carry much less information than 500
independent observations. 10 · Tests and corrections shows how tests account for this.
tp = syn.datasets.timepoint_pairing()
one = tp.to_df("correlation").query("subject == 's01'")
wide = one.pivot(index="time", columns="method", values="correlation")
(wide["improved"] - wide["standard"]).autocorr(lag=1).round(2)
np.float64(0.88)
Per-source errors, with a failed method¶
method_comparison scores three methods at every source of every subject, for three sensor types.
Subjects have different sources (ragged), and alternative failed in 5 subjects, as accepted records.
Reducing the sources to one median per subject gives the numbers a comparison would use:
mc = syn.datasets.method_comparison()
medians = mc.to_df("error", reduce={"source": "median"})
medians.pivot_table(index="sensors", columns="method", values="error", aggfunc="count")
| method | alternative | baseline | proposed |
|---|---|---|---|
| sensors | |||
| eeg | 11 | 16 | 16 |
| grad | 11 | 16 | 16 |
| mag | 11 | 16 | 16 |
medians.pivot_table(index="sensors", columns="method", values="error").round(3)
| method | alternative | baseline | proposed |
|---|---|---|---|
| sensors | |||
| eeg | 0.301 | 0.249 | 0.199 |
| grad | 0.338 | 0.251 | 0.248 |
| mag | 0.298 | 0.249 | 0.205 |
proposed has a lower error than baseline for EEG and magnetometers, but not for gradiometers (a
null effect). Only 11 subjects can compare alternative with the others.
Seeds and sizes¶
Every generator takes a seed: the same seed gives exactly the same study, another seed a new sample.
Size and effect parameters let you make a study as small or as large as you need. The parameters used are
stored with the planted effects:
a = syn.datasets.crossover(seed=1)
b = syn.datasets.crossover(seed=1)
a.to_df("score").equals(b.to_df("score"))
True
big = syn.datasets.crossover(n_subjects=500, effect=2.0, seed=7)
big.info.extra["generator"]
{'name': 'synaptome.datasets.crossover',
'parameters': {'n_subjects': 500, 'effect': 2.0, 'seed': 7}}
Toy studies are ordinary studies: you can select, reduce, save and share them like any other.
Next: 08 · Questions asks questions of these studies: what to compare, on which data, before any test is chosen.