Skip to content

synaptome

The top-level package: Study, loading and saving, toy datasets, result files and corrections.

synaptome

synaptome -- collect, store, and share all the metrics from a research study as one portable object, with statistics and plots on demand.

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.

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 StudyInfo field (investigators, license, status, ...).

{}

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 columns subject, 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: name).

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. ["group", "age"]. Each must sit at the (result) level or above it, on any branch of the hierarchy, and its dimensions must be among the remaining ones (scalars are repeated along them). True joins every scalar variable at that level or above.

None
reduce Mapping[str, Any] | None

Reductions applied first, e.g. {"time": "slope"}, {"time": ("at", 12)} or {"trial": "mean"} (see synaptome.study.reduce). Dimensions are reduced first, in the order written (a median of means isn't a mean of medians), then unit levels from the bottom up. Levels reduced must be the variable's level and, optionally, the levels above it one by one; each is collapsed into its parent, which must be unique (for a crossed level, use table(level, reduce=...) to say which parent).

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 level or above. A variable with dimensions, or below level, can be listed when reduce brings it to one value per unit of level.

None
reduce Mapping[str, Any] | None

Reductions, e.g. {"time": "slope"} or {"session": "mean", "trial": "median"} (see synaptome.study.reduce). Every dimension of a listed variable must be reduced, and so must every level between the variable's level and level (otherwise several values would stand for one unit). A crossed level is collapsed into the parent on the way to level.

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

{level: id(s)} -- units to keep at that level. Units below removed units are removed too.

None
where Mapping[str, Any] | None

{variable: value(s)} -- keep units of that (scalar) variable's level whose value is among these, e.g. {"group": "A"}.

None
coords Mapping[str, Any] | None

{dimension: values} -- keep these coordinates in every variable with that dimension. Values are a list, a single value, or a slice(low, high) (inclusive; either end may be 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.

load(path, variables=None)

Loads a saved study (folder or .syn file).

Parameters:

Name Type Description Default
path str | Path
required
variables list[str] | None

Load only these variables (definitions and values); by default all of them. The variable that a requested replicate variable replicates is loaded too. Units, identity, protocol (with every pre-specified question) and attachments are always loaded.

None

Returns:

Type Description
Study

peek(path)

What a saved study contains, read from its manifest only (no data is loaded).

Returns:

Type Description
dict

title, created_at, synaptome_version, software, levels ({name: n_units}), variables ({name: {level, dims, dtype, n_values}}), questions ({title: status}, the pre-specified questions) and attachments (names).

load_result(path, study=None)

Loads a result saved with Result.save.

Parameters:

Name Type Description Default
path str | Path
required
study Study | None

Rebuilds the result's question on this study (result.question). Without it, only result.question_spec is available. Loading doesn't check the data: use study.verify(result).

None

Returns:

Type Description
Result

Of the kind saved (e.g. EstimateResult).

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.