15. Validation and plans (schema, dry run, duplicates, change records, link fields)
Tools for checking before you write. If you do not use them, nothing changes in the existing behaviour.
| Tool | Use it to |
|---|---|
Schema (Schema) | Check fields: required, type, enum, range, regex, custom rules |
Dry run (dry_run=True) and plans (Plan) | See what will change (old value → new value) before running; back up first |
Duplicate check (find_existing, upsert) | Stop or update when an entry with the same combination already exists |
Change records (record=) | Leave who changed what and why as an entry comment |
Link fields (set_link, Ref) | Put the ID of an entry found by title or conditions into an items / experiments field |
SDK check (elab.check_sdk()) | Confirm the installed elabapi_python has every API the toolkit uses |
Schema validation
from elabftw_toolkit import Schema
schema = Schema.load("eln_schema.json") # JSON or Excel (.xlsx, needs openpyxl)
r = schema.validate({"purity": "99.9", "mass": "abc"}, category="Raw material")
r.ok # True when there are no errors (warnings are allowed)
r.errors # list of Issue; r.warnings for warnings
r.to_frame() # as a DataFrame
elab.items.entry(5).fields.validate(schema) # the entry's current fields (category taken from the entry)Schema format
Two JSON shapes are accepted.
{"categories": {
"raw": {"category": "Standard samples / raw", "kind": "items",
"fields": {
"name": {"required": "required", "type": "text"},
"weight": {"type": "number", "unit": "g", "rules": "range:0-10000"},
"storage": {"type": "text", "enum": "fridge|cabinet", "severity": "warning"},
"element": {"type": "link", "enum": "Element", "required": "required"}
}}}}{"fields": {"pct": {"type": "number", "min": 0, "max": 100, "required": true},
"code": {"type": "text", "pattern": "^[A-Z]{3}$"},
"modes": {"type": "select", "enum": ["a", "b"]}}}- The first is the shape of BENTEN's
eln_schema.json(categoryis the ELN category title;schema.category()accepts either the sheet name or the category title). typefollows elabFTW extra field types (text, number, date, datetime-local, time, select, radio, checkbox, url, email, items, experiments, users).linkis treated asitems.requiredis"required"/"optional"/"automatic"(filled automatically; never reported missing) or true / false.enumis"a|b"or a list. For link types,enumis read as the target category (or writetarget_category). External enums such as"vocab:xxx"are supplied withschema.register_enum("vocab:xxx", func)(ignored otherwise).rulesis"range:0-100; regex:^Q\d+$"or a list.severity(error/warning, or誤り/注意) applies to problems found by rules and enums; missing required values and type mismatches are always errors.- You can also write the schema in Excel (see "Writing the schema in Excel" below).
Writing the schema in Excel
Instead of JSON, you can write the schema in Excel (.xlsx). Reading it requires openpyxl (pip install openpyxl).
Two sample files are available (both in examples/ in the repository):
| File | Contents |
|---|---|
| eln_schema_example.xlsx | Two categories: sample and measurement (simple introductory example) |
| eln_schema_xafs_example.xlsx | Three categories: source material, measurement sample, and measurement (practical XAFS example based on the BENTEN ELN schema) |
schema = Schema.load("examples/eln_schema_example.xlsx")There are two layouts.
One category: use a single sheet. Put column names in the first row, then one field per row from the second row. The sheet name becomes the category name.
| name | required | type | unit | enum | rules | severity |
|---|---|---|---|---|---|---|
| sample_name | required | text | no_placeholder | |||
| purity | optional | number | % | range:0-100 | ||
| form | required | select | powder|pellet|solution | |||
| storage | optional | text | fridge|cabinet | warning |
Several categories: add a sheet named category with one row per category. Write the fields of each category, in the layout above, on the sheet named in the sheet column.
The category sheet:
| sheet | category | kind |
|---|---|---|
| Sample | Sample | items |
| Measurement | Measurement | experiments |
The Measurement sheet:
| name | required | type | unit | enum | rules | severity |
|---|---|---|---|---|---|---|
| measured_on | required | date | date:2000-01-01~today | |||
| sample | required | items | Sample | |||
| temperature | optional | number | K | range:0-2000 |
categoryis the eLabFTW category name. You can pass either the sheet name or the eLabFTW category name toschema.category()andvalidate(..., category=). When checking entries (fields.validate()and so on), the eLabFTW category name is used to find the matching schema.kindisitems(Resources) orexperiments(Experiments).- The column headers in the
categorysheet can also be written in Japanese:シート,ELN のカテゴリ,種類.
Columns
| Column (English) | Column (Japanese) | What to write |
|---|---|---|
name | 項目名 | The eLabFTW field name (required column) |
required | 必須 | required, optional, or automatic (filled in automatically; missing values aren't reported). TRUE, yes, 必須, and ○ also mean required |
type | 型 | The eLabFTW field type (text, number, date, select, items, and so on; same as in JSON above) |
unit | 単位 | The unit (for number fields, compared with the unit in eLabFTW) |
enum | 列挙 | Allowed values separated by | (powder|pellet). For link types (items, experiments), the name of the target category |
rules | 確かめ / 規則 | Rules separated by ; (range:0-100; regex:^Q\d+$). See "Rules" below |
severity | 重さ | Whether problems found by enum and rules are errors (default) or warnings (warning / 注意) |
target_category | リンク先のカテゴリ | The target category for link types, if you don't want to put it in enum |
- Write ranges and regular expressions in the
rulescolumn. There are no columns for JSON'smin,max, andpattern. Writerange:0-100orregex:^L\d{4}$instead. severityonly applies to problems found byenumandrules. Missing required values and wrong types (not a number, not an email address, and so on) are always errors.- Other columns (such as
説明(日本語),例, or notes) aren't used for validation. Use them for descriptions and notes. - Empty rows are skipped.
- The sample file uses Japanese headers and category names.
Rules
Built in (no domain knowledge): range:lo-hi, regex:pattern, date (date:2000-01-01~today for a range), datetime, doi, email, no_placeholder (---, N/A and the like), pair:other_field (only one of the two is filled).
Unregistered rules are reported as warnings. Register domain rules (CAS numbers, chemical formulae, ...) from the caller:
@schema.rule("cas")
def cas(value, arg, ctx): # return a message (or list of messages) when there is a problem
if not re.fullmatch(r"\d{2,7}-\d{2}-\d", value):
return "not a CAS number"
if not cas_checksum_ok(value):
return ("warning", "check digit does not match") # tuple to change the severity
schema.register_rule("matvoc_uri", func, check_empty=True) # also called when the value is emptyctx provides ctx.value_of(name) (other fields of the entry), ctx.lookup(id, "items") (the linked entry when resolve is given) and ctx.context.
Checking entry fields with definitions
fields.validate() and schema.validate_entry(entry_dict) also check the ELN definitions: ELN type or number unit differs from the schema (error); select options not in the schema, missing definition of an optional field, field not in the schema (warning). Link fields have their target category checked via resolve (by default read from the API).
Validating automatically before writing
elab.use_schema(schema) # on_write=True by default
entry.fields.update({"mass": "abc"}) # SchemaError, nothing written
entry.fields.update({"purity": "---"}) # warnings are logged and the write goes ahead
entry.fields.update({...}, validate=False)
elab.use_schema(None)Automatic checks run in fields.update(), fields.set_link(), items.init() / experiments.init() (fields in metadata_update) and plan.execute(), and look only at the fields being written (other missing required fields do not stop the write). Entries whose category is not in the schema are skipped. Pass validate=schema for a one-off check.
Dry run and plans
Pass dry_run=True to a write operation to get a Plan instead of writing.
p = entry.fields.update({"purity": "99.9%", "mass": 3}, dry_run=True)
print(p) # old value → new value per change; unchanged ones are marked "="
p.to_frame() # entry, op, target, before, after, note, noop
p.execute()dry_run is available on fields.update, fields.set_link, entry.patch, entry.tags.add, entry.links.add_item / add_experiment, entry.files.upload (detects identical content), entry.lock / unlock, elab.items.init / elab.experiments.init and upsert.
Group several operations into a plan, check it, then run it:
plan = elab.plan()
plan.update_fields(elab.items.entry(5), {"purity": "99.9%"})
plan.add_tags(("items", 5), ["checked"])
plan.add_link(elab.items.entry(5), "items", 858)
plan.create("items", title="ZnO pellet", category_title="Measured samples",
fields={"master_sample": "858"}, template_id=8)
plan.lock(elab.items.entry(5))
plan.check(schema)
plan.execute(backup_dir="backup", # saves current entries to backup/backup_<time>.json first
record=ChangeRecord(by="Yamada", reason="register measured sample"),
schema=schema) # stops before writing anything if there are errors
plan.created_ids- Building a plan reads the entries (no writes).
execute()does not rebuild the plan, so the ELN may change in between. - Operations that change nothing are skipped. On failure execution stops; earlier writes remain (restore from the backup). Running
execute()again skips completed operations.
Duplicate check and upsert
hits = elab.items.find_existing(
category_title="Measured samples",
fields={"master_sample": "858", "target_absorption_edge": "Zn K", "amount": 10},
cache_dir="cache", # uses all(full=True, cache_dir): only changed entries are re-read
)Values are compared after stripping whitespace, and numerically when both parse as numbers ("10" equals 10.0). A callable selects entries for which it returns True. Pass entries= to search a list you already have.
r = elab.items.upsert(
title="ZnO pellet", category_title="Measured samples",
fields={"master_sample": "858", "target_absorption_edge": "Zn K", "amount": 10, "note": "..."},
match=["category", "master_sample", "target_absorption_edge", "amount"],
on_exists="skip", # "update" (default; writes changed fields only) / "skip" / "error"
on_many="error", # AmbiguousError on 2+ matches ("first" = newest)
template_id=8, cache_dir="cache", dry_run=True,
)
r.action, r.id, r.planChange records (who changed it and why)
from elabftw_toolkit import ChangeRecord
entry.fields.update({"purity": "99.9%"}, record=ChangeRecord(by="Yamada", reason="fix typo"))
entry.tags.add("checked", record="forgot the tag") # a string is the reason
entry.comments.list()After writing, one elabFTW comment is added to the entry (none by default) with the person, the reason and old → new per change.
Why comments:
- They do not touch the body or metadata. Appending to the body would break HTML tables and templates and would leak into search and exports (MaiML, ...).
- elabFTW stamps comments with the time and the API key owner and shows them on the entry page; writing the person into the text identifies who actually made the change even with a shared API key.
- elabFTW's own changelog / revisions record what changed and when, but not the reason or the real person behind a shared key.
- Comments only need read access, so they should work on locked entries too (not yet verified on a real server).
plan.execute(record=...) adds one comment per changed entry.
Link fields (items / experiments type)
f = elab.experiments.entry(120).fields
f.set_link("master_sample", title="Zinc oxide", category_title="Standard samples / raw")
f.set_link("master_sample", 858, category_title="Standard samples / raw") # only checks existence and category
f.set_link("edge", fields={"symbol": "Zn", "edge": "K"}, category_title="Edges", also_link=True)- No candidate raises
NotFoundError, two or more raiseAmbiguousError(bothLinkResolutionError, withexc.candidates). - A non-link field raises
ValueError. - Without
category_title, the target category from the schema set withelab.use_schema()is used. Ref(title=..., category_title=...)as a value resolves the ID before writing (fields.update,plan.create,upsert).elab.items.resolve_id(...)returns just the ID.
elabapi_python version differences
Class names change between elabapi_python versions (6.0: ExperimentsCategoriesApi → ExperimentCategoriesApi, ExperimentsStatusApi → ExperimentStatusApi, ...). The toolkit resolves them through _compat.api_class(...) (aliases in _compat.ALIASES).
elab.check_sdk() # [] means every class and method the toolkit uses is presenttests/test_compat.py (offline) checks the same thing; tests/live/test_sdk_compat.py checks a real 6.0.x server read-only.