02 · Units and variables¶
You will learn how to describe a study's structure: the units that were observed (sites, subjects, sessions, trials) and how they nest or cross, and the variables measured on them, with their units of measurement and allowed values.
You need 01 · Quickstart.
import pandas as pd
import synaptome as syn
from synaptome.study import Dim
Levels of units¶
Units come in levels. Here, subjects were recruited at two sites and each came for two sessions. The
shorthand "site > subject > session" says that sessions belong to subjects, which belong to sites.
study = syn.Study("Sleep study")
study.units.define("site > subject > session")
study.units.levels
(Level(name='site', parents=(), description=''),
Level(name='subject', parents=('site',), description=''),
Level(name='session', parents=('subject',), description=''))
study.units.parents("session"), study.units.ancestors("session")
(('subject',), ('site', 'subject'))
Units are added from the top down. A subject row names its site, and a session row names its site and subject, so synaptome knows exactly which unit each one belongs to.
study.add_units("site", ["lyon", "paris"])
study.add_units(
"subject", pd.DataFrame({"site": ["lyon", "lyon", "paris"], "subject": ["s01", "s02", "s03"]})
)
sessions = pd.DataFrame(
{
"site": ["lyon", "lyon", "lyon", "lyon", "paris", "paris"],
"subject": ["s01", "s01", "s02", "s02", "s03", "s03"],
"session": [1, 2, 1, 2, 1, 2],
}
)
study.add_units("session", sessions)
study.units.ids("session")
| site | subject | session | |
|---|---|---|---|
| 0 | lyon | s01 | 1 |
| 1 | lyon | s01 | 2 |
| 2 | lyon | s02 | 1 |
| 3 | lyon | s02 | 2 |
| 4 | paris | s03 | 1 |
| 5 | paris | s03 | 2 |
Session ids 1 and 2 repeat for every subject. That is fine: a session is identified by its own id
and its subject's (and site's). Ids are kept exactly as you gave them.
Levels can also cross. In a reaction-time experiment, each trial belongs to one subject and one
stimulus, and every stimulus is seen by every subject. < reads "under":
rt_study = syn.Study("Reaction times")
rt_study.units.define("trial < subject * stimulus")
rt_study.units.parents("trial")
('subject', 'stimulus')
Units or dimensions?¶
One rule decides where each piece of information goes, and later tells synaptome which comparisons are paired and which are independent:
| What it is | Where it goes | Example |
|---|---|---|
| differs between units | a variable at that unit's level | group, sex, site |
| differs within a unit | a dimension of the measurement | condition, time, frequency |
| units grouped inside others | the hierarchy of levels | sessions within subjects |
So "time" is never a level: it is a dimension of the variable measured over time.
Defining variables¶
You can let synaptome infer definitions (tutorial 01), but writing them down documents the data and makes validation strict from the first value. A definition says at which level the variable lives, its type, unit, scale and allowed values.
study.variables.define(
"group",
level="subject",
dtype="category",
categories=("control", "insomnia"),
scale="nominal",
)
study.variables.define(
"sleep_hours",
level="session",
measurement_unit="h",
scale="ratio",
range=(0, 24),
description="Total sleep time, from actigraphy.",
)
study.variables.define(
"alertness",
level="session",
dims=[Dim("hour", measurement_unit="h")],
scale="interval",
range=(0, 10),
description="Self-rated alertness, sampled during the day.",
)
study.variables
VariableDictionary group: category @ subject sleep_hours: float (h) @ session alertness[hour]: float @ session
Dimensions have a scale too, in the same words as variables. By default, numeric coordinates
(hours, weeks, frequencies) are taken as ordered and evenly measured (interval), and anything else as
unordered labels (nominal). Numbers that are only codes, such as EEG channel numbers, should say so,
so that nobody later takes a slope "along the channels":
study.variables.define(
"eeg_power",
level="session",
dims=[Dim("channel", scale="nominal")],
scale="ratio",
measurement_unit="µV²",
)
study.variables["eeg_power"].dims
(Dim(name='channel', measurement_unit=None, description='', kind=None, scale='nominal'),)
to_frame lists the data dictionary as a table, with every field.
study.variables.to_frame()
| name | level | dtype | dims | measurement_unit | scale | kind | origin | replicates_of | inferred | description | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | group | subject | category | NaN | nominal | None | None | None | False | ||
| 1 | sleep_hours | session | float | h | ratio | None | None | None | False | Total sleep time, from actigraphy. | |
| 2 | alertness | session | float | hour | NaN | interval | None | None | None | False | Self-rated alertness, sampled during the day. |
| 3 | eeg_power | session | float | channel | µV² | ratio | None | None | None | False |
Values now have to match their definition. A session at 30 hours of sleep is rejected, and the message says which values broke which rule:
bad = sessions.assign(sleep_hours=[7.5, 6.9, 30.0, 5.1, 8.2, 7.7])
try:
study.add("sleep_hours", bad)
except ValueError as err:
print(err)
Variable 'sleep_hours': value(s) [30.0] outside range [0, 24].
study.add("sleep_hours", sessions.assign(sleep_hours=[7.5, 6.9, 6.0, 5.1, 8.2, 7.7]))
study.to_df("sleep_hours")
| site | subject | session | sleep_hours | |
|---|---|---|---|---|
| 0 | lyon | s01 | 1 | 7.5 |
| 1 | lyon | s01 | 2 | 6.9 |
| 2 | lyon | s02 | 1 | 6.0 |
| 3 | lyon | s02 | 2 | 5.1 |
| 4 | paris | s03 | 1 | 8.2 |
| 5 | paris | s03 | 2 | 7.7 |
Refining an inferred definition¶
When a definition was inferred, update completes it. The variable is then no longer marked as inferred.
study.add(
"age",
pd.DataFrame({"site": ["lyon", "lyon", "paris"], "subject": ["s01", "s02", "s03"], "age": [34, 52, 47]}),
)
study.variables.update("age", measurement_unit="years", scale="ratio", range=(18, 99))
age = study.variables["age"]
age.measurement_unit, age.range, age.inferred
/tmp/ipykernel_2592/4224553864.py:1: InferenceNotice: Inferred definition for 'age': age: int @ subject. Review it with study.variables['age'], or define the variable explicitly. study.add(
('years', (18, 99), False)
Replicate variables¶
Sometimes resampling happens before the data reach you. In a simulation benchmark, for example, the accuracy of each run is also recomputed on 1000 bootstrap resamples of its spikes. Those draws are not new runs: they all come from the same data, so they must not be stored as units.
Store them as a replicate variable: the same level and dimensions as the variable they resample, plus
one dimension of kind "replicate" that numbers the draws. replicates_of links the two, so confidence
intervals computed later can use these draws instead of resampling again.
bench = syn.Study("Spike-sorting benchmark")
bench.units.define("region > run")
bench.variables.define("accuracy", level="run", dims=["method"], scale="ratio")
bench.variables.define(
"accuracy_boot",
level="run",
dims=["method", Dim("draw", kind="replicate")],
replicates_of="accuracy",
description="Accuracy recomputed on bootstrap resamples of the spikes.",
)
bench.variables.to_frame()[["name", "level", "dims", "replicates_of"]]
| name | level | dims | replicates_of | |
|---|---|---|---|---|
| 0 | accuracy | run | method | NaN |
| 1 | accuracy_boot | run | method, draw | accuracy |
The draws must line up with the variable they replicate. Here a replicate stored per region, while
accuracy is per run, is refused:
try:
bench.variables.define(
"accuracy_region_boot",
level="region",
dims=["method", Dim("draw", kind="replicate")],
replicates_of="accuracy",
)
except ValueError as err:
print(err)
Variable 'accuracy_region_boot' is at level 'region', but the variable it replicates, 'accuracy', is at level 'run'.
Next: 03 · Adding values covers the different ways to put data into a study: tables, arrays, single values, missing values and corrections.