05 · Save and share¶
You will learn how to document a study (who ran it, its plan, attached files), save it as one .syn
file or a folder, look inside a saved study without loading it, and load only what you need.
You need 01 · Quickstart. Tutorials 02 to 04 help but aren't required.
import tempfile
import zipfile
from pathlib import Path
import pandas as pd
import synaptome as syn
Identity and plan¶
Everything about the study's identity is optional and can be given when creating it. Investigators can be names or dictionaries with affiliation, ORCID and role.
study = syn.Study(
"Weight trial",
description="Twelve-week weight change under a dietary intervention.",
investigators=[{"name": "A. Researcher", "affiliation": "University of Lyon", "role": "PI"}],
license="CC-BY-4.0",
status="ongoing",
)
study.info
StudyInfo(title='Weight trial', description='Twelve-week weight change under a dietary intervention.', investigators=[Person(name='A. Researcher', affiliation='University of Lyon', orcid=None, role='PI')], institutions=[], start_date=None, end_date=None, funding=[], ethics=None, registration=None, license='CC-BY-4.0', status='ongoing', keywords=[], extra={})
The protocol records what was planned: arms, assignment, eligibility, planned sample size. It is descriptive and never used to address data; it also holds the study's pre-specified questions (below).
study.protocol.arms = ["control", "treated"]
study.protocol.assignment = "block randomization, 1:1"
study.protocol.inclusion = ["adults 18-65", "BMI 25-35"]
study.protocol.planned_n = {"control": 20, "treated": 20}
study.protocol
Protocol(arms=[Arm(name='control', description=''), Arm(name='treated', description='')], assignment='block randomization, 1:1', inclusion=['adults 18-65', 'BMI 25-35'], exclusion=[], schedule=None, planned_n={'control': 20, 'treated': 20}, notes=None)
Some data to save:
study.add_units(
"subject",
pd.DataFrame(
{"subject": ["s01", "s02", "s03", "s04"], "group": ["control", "control", "treated", "treated"]}
),
)
weights = pd.DataFrame(
{
"subject": ["s01", "s01", "s02", "s02", "s03", "s03", "s04", "s04"],
"time": [0, 12] * 4,
"weight": [82.1, 82.3, 75.4, 75.6, 79.0, 75.9, 85.3, 81.4],
}
)
study.add("weight", weights)
study.add(
"height", pd.DataFrame({"subject": ["s01", "s02", "s03", "s04"], "height": [1.78, 1.65, 1.71, 1.82]})
)
study
/tmp/ipykernel_2672/1113074581.py:1: InferenceNotice: Inferred definitions for subject variables: group: category @ subject. Review them with study.variables, or define them explicitly.
study.add_units(
/tmp/ipykernel_2672/1113074581.py:14: InferenceNotice: Inferred definition for 'weight': weight[time]: float @ subject. Review it with study.variables['weight'], or define the variable explicitly.
study.add("weight", weights)
/tmp/ipykernel_2672/1113074581.py:15: InferenceNotice: Inferred definition for 'height': height: float @ subject. Review it with study.variables['height'], or define the variable explicitly.
study.add(
Study('Weight trial', ongoing; levels: subject(4); variables: 3)
The protocol can also hold the study's pre-specified questions. They are saved with the study, and their results say whether the question came before the data. This one is registered after the data, so its results will say so; 12 · Pre-registration registers questions first.
study.protocol.add_question(
study.compare("weight", by="group", reduce={"time": "slope"}, title="Slope by group"), status="primary"
)
study.protocol.registrations()
| title | kind | outcome | status | registered_at | |
|---|---|---|---|---|---|
| 0 | Slope by group | compare | weight | primary | 2026-11-27 08:23:05.654906+00:00 |
Attachments¶
Files that belong with the study, such as the protocol document or the analysis code, can be embedded (copied into the study) or referenced (only their path is stored, with a checksum to detect later changes). We create two small files in a temporary folder.
tmp = tempfile.TemporaryDirectory()
folder = Path(tmp.name)
(folder / "protocol.txt").write_text("Twelve weeks, weighed at baseline and at the end.\n")
(folder / "raw.csv").write_text("subject,kg\ns01,82.1\n")
study.attachments.add("protocol", folder / "protocol.txt", description="Study protocol")
study.attachments.add("raw_export", folder / "raw.csv", embed=False, description="Scale export")
study.attachments
Attachments protocol: protocol.txt (50 bytes, embedded) raw_export: raw.csv (20 bytes, -> /tmp/tmpwbw24s2j/raw.csv)
study.attachments["protocol"].read_bytes(), study.attachments["raw_export"].verify()
(b'Twelve weeks, weighed at baseline and at the end.\n', True)
Saving¶
A path ending in .syn gives a single file. Any other path gives a folder with the same content.
path = study.save(folder / "weight_trial.syn")
sorted(zipfile.ZipFile(path).namelist())
['attachments/protocol/protocol.txt', 'manifest.json', 'questions/Slope_by_group.json', 'study.json', 'units/subject.parquet', 'values/group.parquet', 'values/height.parquet', 'values/weight.parquet']
Inside: a manifest, the study description in JSON, and one Parquet table per level and per variable. These are open formats: a collaborator can read them without synaptome. The folder form shows the same tree:
tree = study.save(folder / "weight_trial")
sorted(str(p.relative_to(tree)) for p in tree.rglob("*") if p.is_file())
['attachments/protocol/protocol.txt', 'manifest.json', 'questions/Slope_by_group.json', 'study.json', 'units/subject.parquet', 'values/group.parquet', 'values/height.parquet', 'values/weight.parquet']
Saving again to the same path raises, so a study is never replaced by accident:
try:
study.save(path)
except FileExistsError as err:
print(err)
study.save(path, overwrite=True)
/tmp/tmpwbw24s2j/weight_trial.syn already exists. Use overwrite=True to replace it.
PosixPath('/tmp/tmpwbw24s2j/weight_trial.syn')
Opening a saved study¶
peek reads only the manifest, which is quick even for a large study: what levels, variables and
attachments it holds.
syn.peek(path)["variables"]
{'group': {'level': 'subject', 'dims': [], 'dtype': 'category', 'n_values': 4},
'weight': {'level': 'subject',
'dims': ['time'],
'dtype': 'float',
'n_values': 8},
'height': {'level': 'subject', 'dims': [], 'dtype': 'float', 'n_values': 4}}
syn.peek(path)["questions"]
{'Slope by group': 'primary'}
load reads it back. With variables=, only those variables are loaded. Units, identity, protocol and
attachments always come along.
light = syn.load(path, variables=["weight"])
light.describe()
| variable | level | dims | dtype | measurement_unit | units_with_values | units_at_level | values | missing | inferred | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | weight | subject | time(2) | float | None | 4 | 4 | 8 | 0 | True |
light.info.investigators, list(light.attachments)
([Person(name='A. Researcher', affiliation='University of Lyon', orcid=None, role='PI')], ['protocol', 'raw_export'])
tmp.cleanup()
Next: 06 · Array statistics introduces the statistics engine that questions and tests are built on.