Skip to content

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.

ToolUse 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 ​

python
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.

json
{"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"}
          }}}}
json
{"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 (category is the ELN category title; schema.category() accepts either the sheet name or the category title).
  • type follows elabFTW extra field types (text, number, date, datetime-local, time, select, radio, checkbox, url, email, items, experiments, users). link is treated as items.
  • required is "required" / "optional" / "automatic" (filled automatically; never reported missing) or true / false.
  • enum is "a|b" or a list. For link types, enum is read as the target category (or write target_category). External enums such as "vocab:xxx" are supplied with schema.register_enum("vocab:xxx", func) (ignored otherwise).
  • rules is "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):

FileContents
eln_schema_example.xlsxTwo categories: sample and measurement (simple introductory example)
eln_schema_xafs_example.xlsxThree categories: source material, measurement sample, and measurement (practical XAFS example based on the BENTEN ELN schema)
python
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.

namerequiredtypeunitenumrulesseverity
sample_namerequiredtextno_placeholder
purityoptionalnumber%range:0-100
formrequiredselectpowder|pellet|solution
storageoptionaltextfridge|cabinetwarning

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:

sheetcategorykind
SampleSampleitems
MeasurementMeasurementexperiments

The Measurement sheet:

namerequiredtypeunitenumrulesseverity
measured_onrequireddatedate:2000-01-01~today
samplerequireditemsSample
temperatureoptionalnumberKrange:0-2000
  • category is the eLabFTW category name. You can pass either the sheet name or the eLabFTW category name to schema.category() and validate(..., category=). When checking entries (fields.validate() and so on), the eLabFTW category name is used to find the matching schema.
  • kind is items (Resources) or experiments (Experiments).
  • The column headers in the category sheet 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 rules column. There are no columns for JSON's min, max, and pattern. Write range:0-100 or regex:^L\d{4}$ instead.
  • severity only applies to problems found by enum and rules. 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:

python
@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 empty

ctx 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 ​

python
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.

python
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:

python
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 ​

python
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.

python
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.plan

Change records (who changed it and why) ​

python
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.

python
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 raise AmbiguousError (both LinkResolutionError, with exc.candidates).
  • A non-link field raises ValueError.
  • Without category_title, the target category from the schema set with elab.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).

python
elab.check_sdk()     # [] means every class and method the toolkit uses is present

tests/test_compat.py (offline) checks the same thing; tests/live/test_sdk_compat.py checks a real 6.0.x server read-only.

Apache License 2.0