synaptome.study¶
synaptome.study
¶
The study: identity, protocol, units, variables and values -- everything that does not change between analyses.
Attachment
dataclass
¶
One attachment.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
|
filename |
str
|
Original file name. |
sha256 |
str
|
|
size |
int
|
Bytes. |
media_type |
str | None
|
|
description |
str
|
|
path |
str | None
|
For references: where the file lives (not copied into the study). |
data |
bytes | None
|
For embedded attachments: the content. |
embedded
property
¶
Whether the file's bytes are stored in the study (else only its path and checksum).
read_bytes()
¶
The content: embedded bytes, or the referenced file (checked against its checksum).
verify()
¶
For references: True if the file still exists with the same checksum. Always True if embedded.
to_dict()
¶
Metadata only (never the embedded bytes).
Attachments
¶
The study's attachments, by name.
add(name, path, embed=True, description='')
¶
Attaches a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Letters, digits, '.', '_' and '-'. |
required |
path
|
str | Path
|
The file. |
required |
embed
|
bool
|
Copy the content into the study (default). With False, only the path, size and checksum are kept -- for large files that should travel separately. |
True
|
description
|
str
|
|
''
|
remove(name)
¶
Removes the attachment name.
Person
dataclass
¶
StudyInfo
dataclass
¶
Identity and context of a study. Every field is optional except the
title; assigning a field (directly or via update) validates it.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
|
description |
str
|
|
investigators |
list[Person]
|
Accepts names, dicts of |
institutions, funding, keywords |
list[str]
|
|
start_date, end_date |
date | None
|
Accept ISO strings ("2026-01-31"). |
ethics |
str | None
|
Committee and approval identifier. |
registration |
str | None
|
Registry or pre-registration identifier (e.g. "NCT01234567", an OSF link). |
license |
str | None
|
Data license (e.g. "CC-BY-4.0"). |
status |
str | None
|
One of "planned", "ongoing", "completed", "terminated". |
extra |
dict
|
Anything else; must be JSON-serializable. |
Arm
dataclass
¶
A group / arm / condition foreseen by the protocol.
to_dict()
¶
The arm as JSON-safe data.
Protocol
dataclass
¶
What was planned, fixed before data collection. Descriptive: nothing here
is used to address data, except the pre-specified questions
(add_question), which results compare with the data's arrival
(result.timing).
Attributes:
| Name | Type | Description |
|---|---|---|
arms |
list[Arm]
|
Groups / arms / conditions; accepts names, dicts or |
assignment |
str | None
|
How units are assigned to arms (e.g. "block randomization, 1:1"). |
inclusion, exclusion |
list[str]
|
Eligibility criteria. |
schedule |
str | None
|
Schedule of events, as text. |
planned_n |
int | dict[str, int] | None
|
Planned sample size, in total or per arm. |
notes |
str | None
|
|
questions |
Mapping[str, Question]
|
The registered questions by title, rebuilt on the study (read-only; see |
amendments |
list[dict]
|
Every removal or replacement of a registered question: |
questions
property
¶
The registered questions by title, rebuilt on the study on each access (read-only).
amendments
property
¶
Every removal or replacement of a registered question, with its time and reason (a copy).
add_question(question, status=None, replace=False, reason=None)
¶
Registers a question as pre-specified, under its title. The time is recorded by synaptome (it can't
be set): results compare it with when the first values they read were added (result.timing).
The question can be written before any value exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
question
|
Question
|
From |
required |
status
|
str | None
|
|
None
|
replace
|
bool
|
Replace the question registered under this title (an amendment: logged, with a new registration time). Default False: a registered title raises. |
False
|
reason
|
str | None
|
Why it is replaced; required with |
None
|
Returns:
| Type | Description |
|---|---|
Registration
|
|
remove_question(title, reason)
¶
Removes a registered question; the removal is logged in amendments with its reason.
registration(title)
¶
The registration of title (spec, status, time).
registrations()
¶
One row per registered question: title, kind, outcome, status, registered_at.
match(question)
¶
The registration this question is: same title and same analysis (roles, subset, reduce, unit; the
wording fields description, status, specified_at are ignored), or None.
update(**kwargs)
¶
Sets several fields at once. Unknown names raise.
to_dict()
¶
The descriptive fields and the amendment log; registered questions are stored on their own.
from_dict(data, registrations=None)
classmethod
¶
From to_dict output, and the registrations (Registration.to_dict) stored beside it.
Study
¶
Everything about one study that does not depend on the questions asked of
it: identity and context (info), the plan (protocol), the units and
their hierarchy (units), the data dictionary (variables), the
values and attachments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
The study's title. |
'Untitled study'
|
**info
|
Any
|
Any other |
{}
|
Examples:
>>> study = Study("Weight trial", license="CC-BY-4.0")
>>> study.add_units("subject", subjects) # ids + group, age, sex as subject variables
>>> study.add("weight", weights) # columns: subject, time, weight
>>> study.to_df("weight", with_=["group", "age"])
protocol
property
writable
¶
The plan, including the pre-specified questions (protocol.add_question).
title
property
¶
The study's title (study.info.title).
plot
property
¶
Figures of this study's values (study.plot.box(...), ...); see synaptome.plot.
add_units(level, data, create_parents=False, overwrite=False)
¶
Adds units to a level; every column other than unit ids becomes a scalar variable at that level
(e.g. a subject table with group, age, sex). The level is created as a root level if it
doesn't exist yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str
|
|
required |
data
|
DataFrame | Sequence
|
One row per unit: the level's id column, the parent id columns, and attribute columns. |
required |
create_parents
|
bool
|
Create missing parent units instead of raising (default False). |
False
|
overwrite
|
bool
|
Replace attribute values already stored for these units (default False). |
False
|
Returns:
| Type | Description |
|---|---|
int
|
Number of new units. |
add(name, data, *, value=None, level=None, dims=None, overwrite=False, create_units=None, **ids_and_coords)
¶
Adds values of one variable.
Two forms:
- A long table: one row per value, with the unit id column(s), one column per dimension, and
the values in a column named after the variable (or
value=).study.add("weight", df)with columnssubject, time, weight. - An array for one unit: unit ids and dimension coordinates as keywords, in axis order.
study.add("erp", arr, subject="s01", trial=3, time=t, channel=chs);study.add("age", 34, subject="s01").
If the variable isn't defined yet, its definition is inferred (an InferenceNotice shows it):
level from the id columns (or level=), dimensions from the remaining columns (or dims=),
dtype from the values. Once defined, every value is validated strictly against the definition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The variable. |
required |
data
|
Any
|
|
required |
value
|
str | None
|
Column holding the values (default: |
None
|
level
|
str | None
|
Level of a new variable. Required when no id column is recognized, e.g. before any level exists; the level is then created. |
None
|
dims
|
Sequence[str] | None
|
Dimensions of a new variable; by default every non-id, non-value column. |
None
|
overwrite
|
bool
|
Replace values already stored at the same addresses (default False: raise). |
False
|
create_units
|
bool | None
|
Create units that don't exist yet, at this level and above. Default: only at levels that have no units at all yet (the first data mentioning a level creates its units); at levels that already have units, an unknown id is an error, so typos are caught. |
None
|
**ids_and_coords
|
Any
|
Array form only: unit ids (scalars) and dimension coordinates (1-D arrays). |
{}
|
Returns:
| Type | Description |
|---|---|
Variable
|
The variable's definition. |
n_values(name)
¶
How many values of variable name are stored.
added_at(name)
¶
When values of name were last added (UTC), or None.
first_added_at(name)
¶
When the first values of name were added (UTC), or None (no values, or a file saved before this
was recorded). Results compare it with the time their question was registered in the protocol.
to_df(name, with_=None, reduce=None)
¶
One variable as a long table: unit id columns, dimension columns, and the values in a column named after the variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
|
required |
with_
|
Sequence[str] | bool | None
|
Other variables to join, e.g. |
None
|
reduce
|
Mapping[str, Any] | None
|
Reductions applied first, e.g. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
table(level, variables=None, reduce=None)
¶
A wide table with one row per unit of level and one column per variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
str
|
|
required |
variables
|
Sequence[str] | None
|
By default every scalar variable at |
None
|
reduce
|
Mapping[str, Any] | None
|
Reductions, e.g. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
|
describe()
¶
One row per variable: level, shape, dtype, how many units have values, and missing values.
copy()
¶
A deep copy: changing it never affects this study.
select(variables=None, units=None, where=None, coords=None)
¶
A new study keeping only part of this one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variables
|
str | Sequence[str] | None
|
Variables to keep. |
None
|
units
|
Mapping[str, Any] | None
|
|
None
|
where
|
Mapping[str, Any] | None
|
|
None
|
coords
|
Mapping[str, Any] | None
|
|
None
|
drop(variables=None, units=None, where=None, coords=None)
¶
The complement of select: a new study without the given variables, units or coordinates.
rename(variables=None, dims=None)
¶
A new study with variables and/or dimensions renamed ({old: new}).
compare(outcome, by, *, reference=None, pairs=None, higher_is_better=True, subset=None, reduce=None, unit=None, title=None, description='', status='exploratory')
¶
Asks a question: is outcome different across the levels of by? Returns a Compare question
(no test is run). Paired or independent is read from where by lives: a dimension of the outcome
is a within-unit factor (paired), a variable at the unit's level a between-unit factor
(independent). See synaptome.questions.Compare for every argument.
Examples:
>>> q = study.compare("score", by="group")
>>> q = study.compare("error", by="method", reference="proposed", subset={"sensors": "eeg"},
... reduce={"source": "median"}, higher_is_better=False)
>>> q.design, q.data
compare_along(outcome, by, along, *, reference=None, pairs=None, higher_is_better=True, subset=None, reduce=None, unit=None, title=None, description='', status='exploratory')
¶
Asks a question about curves: does outcome differ across the levels of by, coordinate by
coordinate along the ordered dimension along? Returns a CompareAlong question. See
synaptome.questions.CompareAlong.
distribution(outcome, by=None, *, subset=None, reduce=None, unit=None, title=None, description='', status='exploratory')
¶
Asks how outcome is distributed, overall or per level of by. Returns a Distribution
question. See synaptome.questions.Distribution.
verify(result)
¶
Whether result still describes this study: its question, asked again on the current data, reads
exactly the data it read then (same data_key). False if the data changed, or if the question
no longer resolves (e.g. a variable it read was removed).
question(spec)
¶
Rebuilds a recorded question on this study, from Question.to_dict output (or another question,
e.g. one asked of an earlier version of the study).
save(path, overwrite=False)
¶
Saves the study: a single zip file if path ends with .syn, a folder otherwise. See
synaptome.io.save; reload with synaptome.load.
UnitHierarchy
¶
The levels of a study and the units at each level.
Examples:
>>> units = UnitHierarchy()
>>> units.define("site > subject > session")
>>> units.add_units("session", df_with_site_subject_session_columns, create_parents=True)
levels
property
¶
All levels, parents before children.
add_level(name, parents=(), description='')
¶
Adds a level, or adds parents to an existing level that has no units yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Level name; also the column name of its ids in tables. |
required |
parents
|
str | Sequence[str]
|
Existing parent levels. Several parents mean the level is crossed. |
()
|
description
|
str
|
|
''
|
define(expression)
¶
Declares levels with a shorthand expression.
"subject": a root level."site > subject > session": nesting, from top to bottom."trial < subject * stimulus":trialunder bothsubjectandstimulus(crossing). Written top-down, the same is"subject * stimulus > trial".
> and < can't be mixed in one expression. Levels that already exist are reused.
Returns:
| Type | Description |
|---|---|
list[Level]
|
Every level named in the expression, as now defined. |
level(name)
¶
The Level named name.
parents(name)
¶
The parent levels of name.
children(name)
¶
The levels whose parents include name.
roots()
¶
The levels without parents.
ancestors(name)
¶
Every level above name, top-down.
descendants(name)
¶
Every level below name, top-down.
key_columns(name)
¶
Columns identifying a unit of name: its ancestors' ids, top-down, then its own id.
paths(source, target)
¶
Every way to relate units of source to units of target through the hierarchy.
A path goes down from source to some level below both (possibly source itself), then up to
target. Going up only (session -> subject) maps each unit to exactly one target unit. Going down
then up (subject -> trial -> stimulus) relates units through their shared children, as in crossed
designs. Paths never visit a level twice.
path(source, target)
¶
The unique path from source to target; raises if there is none or several.
n_units(name)
¶
How many units the level name has.
ids(name)
¶
The units of name, one row each, identified by their key columns (see key_columns).
add_units(name, data, create_parents=False)
¶
Adds units to a level. Units that already exist are skipped, so the same table can be passed again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The level. |
required |
data
|
DataFrame | Iterable
|
A table with a column named after the level (the ids) and, for each parent level, a column with the parent ids -- plus ancestor columns where parent ids alone are ambiguous. Other columns are ignored. For a root level, a plain list of ids is accepted too. |
required |
create_parents
|
bool
|
Create missing parent units from the same table instead of raising (default False, so a typo in a parent id can't silently create a new parent). |
False
|
Returns:
| Type | Description |
|---|---|
int
|
Number of units added. |
lookup(name, data)
¶
Finds the units of name that the rows of data refer to.
data must have the level's id column, plus enough ancestor columns to make each row point to
exactly one unit (for trial 1 of several subjects, the subject column).
Returns:
| Type | Description |
|---|---|
np.ndarray of int
|
One internal unit index per row of |
Raises:
| Type | Description |
|---|---|
KeyError
|
Some rows refer to units that don't exist. |
ValueError
|
Some rows match several units: more ancestor columns are needed. |
map_units(source, target)
¶
Pairs of related units along the unique path from source to target (see path).
Returns:
| Type | Description |
|---|---|
DataFrame
|
Columns |
keep_units(masks)
¶
Keeps only some units, in place. A unit is removed when its mask entry is False or when any of its parents is removed; levels without a mask keep every unit whose parents are kept.
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Per level, the new internal index of every old unit (-1 when removed), to remap stored values. |
levels_to_list()
¶
Every level as JSON-safe data, parents before children.
InferenceNotice
¶
Bases: UserWarning
Emitted when synaptome infers a variable definition from data. Silence it with
warnings.simplefilter("ignore", synaptome.InferenceNotice).
variables holds the names of the variables whose definitions were inferred.
Dim
dataclass
¶
A named dimension of a variable's shape (time, frequency, channel, condition, ...).
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
|
measurement_unit |
str | None
|
Measurement unit of the coordinates ( |
description |
str
|
|
kind |
str | None
|
None for an ordinary axis; |
scale |
str | None
|
Scale of the coordinates: |
Variable
dataclass
¶
The definition of one variable.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
|
level |
str
|
Unit level the variable attaches to ( |
dtype |
str
|
|
dims |
tuple[Dim, ...]
|
The variable's shape: named dimensions such as time or condition. Empty for a scalar. |
description |
str
|
|
scale |
str | None
|
|
measurement_unit |
str | None
|
Measurement unit of the values ( |
categories |
tuple | None
|
Allowed values for |
range |
tuple | None
|
|
kind |
str | None
|
|
instrument |
str | None
|
How the values were obtained. |
origin |
str | None
|
|
provenance |
dict
|
Free record of how derived values were produced (pipeline, version, parameters, sources). Documentation only; must be JSON-serializable. |
replicates_of |
str | None
|
For a variable of resampled values (upstream bootstrap draws, jackknife values): the variable it
replicates. It then has the same level and dimensions as that variable, plus one dimension of kind
|
inferred |
bool
|
True when the definition was inferred from data rather than written by the user. |
dim_names
property
¶
The names of the variable's dimensions, in order.
is_scalar
property
¶
Whether the variable has no dimension (one value per unit).
replicate_dim
property
¶
The dimension of kind "replicate" or "jackknife", if any.
check_dims(given)
¶
Raises unless given names exactly this variable's dimensions.
validate(values)
¶
Checks values against this definition and returns them converted to the variable's storage type. Missing values (NaN / None) are always allowed.
Raises:
| Type | Description |
|---|---|
TypeError
|
Values can't be read as the variable's dtype. |
ValueError
|
Values outside |
infer(name, values, level, dims=())
classmethod
¶
Builds a definition from example values: the dtype is read from the data, the scale is only set
when it is unambiguous (nominal for categories and booleans, interval for dates), and nothing else
is guessed. The result is marked inferred=True.
Integers with missing values are only inferred as int when they use pandas' nullable Int64
dtype: a plain column [1, 2, NaN] is float64 and is inferred as float, since whole-number
floats can't be told apart from a float variable that happens to hold round values.
to_dict()
¶
The definition as JSON-safe data (reload with Variable.from_dict).
VariableDictionary
¶
The study's data dictionary: one Variable per name.
Checks definitions against the unit hierarchy: the level must exist, and names can't clash with level names or with other variables' dimensions (they all become columns of the same tables).
names
property
¶
The names of the defined variables, in definition order.
all_dim_names()
¶
Every dimension name used by a variable.
define(name, level, dtype='float', dims=(), **fields)
¶
Defines a new variable (see Variable for the fields). Raises if the name is already defined.
add(variable, replace_existing=False)
¶
Adds a Variable definition as is (it must fit the study's levels and other variables).
update(name, **changes)
¶
Changes fields of an existing definition (it is no longer marked as inferred). Replicate variables
of name must still fit the new level and dimensions.
remove(name)
¶
Removes a definition, and its values if the dictionary belongs to a study. Raises while replicate variables point at it: remove them first.
replicates(name)
¶
The replicate variables of name (those with replicates_of == name).
check_level_name(name)
¶
Raises if a new level would clash with a variable or dimension name.
to_frame()
¶
The dictionary as a table, one row per variable.
to_list()
¶
Every definition as JSON-safe data, in order.
load_list(data)
¶
Adds definitions from to_list output.
concat(studies, title=None)
¶
Combines several studies with compatible structures into one -- e.g. one study per site, or per batch of subjects. Identity, protocol and attachments come from the first study.
Levels must have the same parents where they appear in several studies; variables defined in several studies must have identical definitions. The same value address in two studies is an error.