10. MaiML (JIS K 0200) export
Creating MaiML (XML) files from eLabFTW entries.
In eLabFTW, the JSON metadata (extra_fields) is the source of truth. MaiML is treated as a format generated from it for passing data between and connecting instruments, facilities, and databases (no XML metadata field is created). elabftw_toolkit.maiml only contains facility-independent building blocks; which field maps to which MaiML key (the mapping table) is decided by the caller.
Installation
pip install "elabftw-toolkit[maiml]" # pymaiml (with MaiML-Schema-1_0 validation)For a development checkout, use python -m pip install -e ".[maiml]".
Minimal example
from elabftw_toolkit import maiml
from elabftw_toolkit.maiml import FieldMap as F
SITE = "https://eln.example.org"
FMAP = [F("chemical_formula", "ex:chemical_formula", description="chemical formula"),
F("calculated_mass", "ex:calculated_mass", "float", "mg", "calculated mass")]
entry = elab.experiments.entry(12).raw() # an eLabFTW entry (dict, API v2 JSON)
fields = maiml.extra_fields(entry)
b = maiml.MaimlBuilder(namespaces={"ex": "https://example.org/ns#"})
b.document("exp_12", "Measurement 12", uuid=maiml.stable_uuid(SITE, "experiments", 12, "maiml"),
owner=("ORG", "Example Org"), vendor=("FAC", "Example Facility"), instrument=("BL1", "Beamline 1"))
b.flow("xas", places=[("sample", "Sample"), ("spec", "Spectrum")], transitions=[("meas", "Measurement")],
arcs=[("place-sample", "tr-meas"), ("tr-meas", "place-spec")])
b.method("XAS", "X-ray absorption spectroscopy", materials=[("sample", "Sample")], results=[("spec", "Spectrum")],
properties=[b.uri("ex:technique", "http://purl.org/pan-science/PaNET/PaNET01196")])
b.material("mat-sample", "sample", entry["title"], props=maiml.props_from_fields(fields, FMAP),
uuid=maiml.stable_uuid(SITE, "items", 34))
b.result("res-spec", "spec", "spectrum", insertions=maiml.insertions_from_uploads(entry, "ex:data/", base=SITE))
b.event("meas", with_results=True)
result = maiml.dump_and_validate(b.build(), "exp12.maiml", namespaces=b.namespaces)
assert result.ok, resultKey points
stable_uuid()is a uuid (UUIDv5) determined by the ELN entry. The same sample gets the same uuid in every file, so files and instruments can be connected mechanically.- The uuids of owner, vendor, instrument and creator are derived from the role and id (
stable_uuid(ENTITY_UUID_BASE, "vendor", "SPring-8")and so on), so the same facility or instrument has the same uuid in every file. - To point to another MaiML document as a parent, pass
b.parent(uuid, path, key)(uuid + SHA-256) todocument(parents=[...]). - External vocabularies (PaNET, MatVoc, and so on) are embedded through key prefixes and URI values (
b.uri(...)). Chapter 17 covers building on existing vocabularies and what to watch when an AI drafts the mapping. - MaiML names are xs:QName, so Japanese names, spaces, and parentheses are replaced with
qname(), and the original name is kept in the description. - A written .maiml file can be attached to the entry with
elab.experiments.entry(id).files.upload(path). maiml.extra_fields/extra_field_unitsare the same aselabftw_toolkit.extra_fields/extra_field_units.
Reading
You can read the content of a MaiML file (yours or another facility's) as a dict; pymaiml is not needed.
from elabftw_toolkit import maiml
r = maiml.read("xafs_exp1563.maiml") # a path, bytes or XML text
r["document"]["parents"] # [{"key": "benten:master_sample", "uuid": "461c…"}]
[m["name"] for m in r["materials"]] # ["MnSb_Q1562", "MnSb_一覧未記載_Lot3640375"]
r["results"][0]["insertions"] # [{"uri": "benten:…/….txt", "format": "txt", "hash": "…"}, …]It returns document (uuid, name, date, creator, owner, instrument, parent documents), methods, materials / conditions / results (properties as {key, value, units, description}, a material's sources as made_from, a result's referenced files as insertions), and events (eventLog). The MCP server's read_maiml tool reads attached MaiML files with it.
Checking (files and the links between them)
MaiML files link to each other by pointing to a parent, as in raw material → sample → measurement. XSD checks what is inside one file, but not the links between files. check does both.
elabftw-maiml check <folder or .maiml> [--json result.json] [--info] [--no-schema]| What | Looks at | Kind |
|---|---|---|
Matches the XSD; every ref inside the file points somewhere | pymaiml (when installed) | error / warning / info (info with --info) |
A document with the parent's (<parent>) uuid exists | the given folders (for a single file, its folder) | parent-missing (warning; it may live elsewhere) |
| The parent file has not changed since the child was made | the parent's <hash> (SHA-256) | parent-hash (error) |
| A material with the same uuid as one in the parent has the same name and values | material name and properties | material-differs (warning) |
Results are printed as file:line:col: error: message [kind] (the VS Code task below reads them as is); the exit code is 1 when there are errors. From Python, maiml.check(["folder"]) returns [{file, line, level, code, message}].
BENTEN example: raw material → sample → measurement
SPring-8 BENTEN writes one hub per raw material (master765.maiml) and one MaiML per measurement (xafs_exp1000.maiml).
master765.maiml (raw-material hub) xafs_exp1000.maiml (measurement)
document uuid 1909870d… ◀── <parent key="benten:master_sample"> uuid 1909870d…, hash (SHA-256)
material mat-raw uuid e4e61c23… ═══ material mat-raw uuid e4e61c23… (supplier, model, formula, MatVoc)
material mat-pellet (the sample) ──instanceRef──▶ mat-raw
condition, result (spectrum and metadata files)- The measurement's
<parent>holds the hub's document uuid and the SHA-256 of the hub file. - The raw material in the measurement (
mat-raw) has the same uuid and content as in the hub. - The sample (
mat-pellet, a pellet or foil) points to the raw material withinstanceRef.
Checking the 3,045 exported public files (2,245 XAFS measurements, 37 HAXPES measurements, 763 raw-material hubs) finds the parent of every XAFS measurement and no errors or warnings. Broken on purpose, they show:
| Change | Reported |
|---|---|
The sample's instanceRef points to mat-rav | REF-01 (error: no such id) |
| The model number of the raw material in a measurement is edited | material-differs (benten:model_number) |
The <parent> uuid is edited | parent-missing |
| The hub's supplier is corrected after the measurement was made | parent-hash (error) and material-differs (supplier) |
So you can check the rule "when a hub changes, export the measurements that point to it again".
Linking across places (collect, check, draw)
MaiML files are rarely in one place. They end up as attachments of ELN entries, in shared-drive folders, in a public copy, on other facilities' or instruments' PCs. The links survive anyway, because files point to each other by uuid, not by location:
- A document's uuid (
<document><uuid>) is its name everywhere (derive it from the ELN entry withstable_uuid()and it stays the same however often you regenerate the file). - A child writes its parent's uuid and SHA-256 in
<parent>. Wherever the parent is, the uuid finds it and the SHA-256 tells whether it changed after the child was made. - The same raw material has the same material uuid in every file.
So "collect the files where you can read them and look them up by uuid" is all it takes to check and draw the links.
1. Collect
Prepare one folder per place (a copy, or just point at the shared-drive folder).
| Place | How to collect |
|---|---|
| ELN attachments | entry.files.download(...) (chapter 5) into a folder |
| Shared drive, other PCs | point at the folder as it is |
| Public copy | the export folder (maiml/ in BENTEN) |
The same document (same uuid) may be in several places. It counts as one document; the others are "copies", reported with whether their bytes are identical.
2. Check
List the folders to check, and pass folders that are only for looking up parents with --context.
# check the measurements downloaded from the ELN; look for their parents (raw-material hubs) on the shared drive and in the public copy
elabftw-maiml check ELN_measurements --context shared_hubs publicWithout --context, parents are looked up only in the checked folders, so a parent in another place gives parent-missing (warning).
3. Draw (graph)
graph writes a Mermaid diagram: one box per folder you pass, arrows from parent to child.
elabftw-maiml graph shared_hubs ELN_measurements public --materials -o graph.md
elabftw-maiml graph <folders…> --focus ELN_measurements/xafs-bl14b2-as-k-111-znas2.maiml # only what links to it
elabftw-maiml graph <folders…> --json graph.json # the links as JSONThe BENTEN raw-material hub of ZnAs₂ and the three measurements that have it as their parent, spread over three places (the hub is both on the shared drive and in the public copy):
flowchart LR
subgraph p0["ELN_measurements"]
d1["BL14B2_XAFS_ZnAs2_As_K-edge_Si111_20231120<br/>xafs-bl14b2-as-k-111-znas2.maiml"]
d2["BL14B2_XAFS_ZnAs2_As_K-edge_Si311_20231121<br/>xafs-bl14b2-as-k-311-znas2.maiml"]
end
subgraph p1["public"]
d3["BL14B2_XAFS_ZnAs2_Zn_K-edge_Si311_20141206<br/>xafs-bl14b2-zn-k-311-znas2.maiml"]
end
subgraph p2["shared_hubs"]
d0["ZnAs2_Q1791<br/>hub-ecdbd503-1bbf-5912-8d47-18c0c8c86488.maiml<br/>ほかに 1 か所(同じ中身)"]
end
d0 -->|"benten:master_sample"| d1
d0 -->|"benten:master_sample"| d2
d0 -->|"benten:master_sample"| d3
m0(["ZnAs2_Q1791"]):::material
m0 -.- d0
m0 -.- d1
m0 -.- d2
m0 -.- d3
m1(["ZnAs2_一覧未記載_Lot3864861"]):::material
m1 -.- d1
m1 -.- d2
classDef missing stroke-dasharray: 5 5,stroke:#c00,color:#c00
classDef material fill:#eef6ee,stroke:#5a5This page shows it as text. To see the diagram, put the -o graph.md file on GitHub / GitLab, open it in VS Code's Markdown preview (with a Mermaid extension), or paste it into the Mermaid Live Editor. The labels in the diagram are in Japanese ("ほかに 1 か所(同じ中身)" = one more copy elsewhere, identical).
| In the diagram | Meaning |
|---|---|
| Box (subgraph) | A folder (place) you passed, named by the part below the folder all places share |
| Node | A document (name and file name). "ほかに n か所(同じ中身)": n copies with the same uuid elsewhere; "⚠ 中身が違う": the copies differ, one of them is old |
| Solid arrow | Parent → child; the parent was found and its SHA-256 matches. The label is the <parent> key |
| Arrow with "⚠ hash" | The parent changed after the child was made (parent-hash in check); export the child again |
| Dotted arrow | The parent has no SHA-256 ("hash なし") or was not found (red dashed node "見つからない") |
Green rounded node (--materials) | A material (same uuid) found in two or more documents, joined to them by dotted lines |
With many files the diagram becomes unreadable (graph itself takes a few seconds even for BENTEN's 3,045 public files). Look at the whole set through the numbers in --json (documents, links by status, copies) and narrow the diagram down with --focus.
From Python:
from elabftw_toolkit import maiml
g = maiml.graph(["shared_hubs", "ELN_measurements", "public"], focus=None)
g["places"] # the places (folders)
g["documents"] # [{uuid, name, file, place, copies: [{file, place, same}]}]
g["links"] # [{child, parent, key, status}] status: ok / hash-differs / no-hash / missing
g["materials"] # materials found in two or more documents: [{uuid, name, documents}]
print(maiml.to_mermaid(g, materials=True))The MCP server answers the same questions with check_maiml and maiml_graph (chapter 16).
Checking in VS Code
Combine two things.
| With | Finds | When |
|---|---|---|
The XML extension (Red Hat XML, redhat.vscode-xml) + the MaiML XSD | XSD problems (structure, required parts, reference targets) | all the time while the file is open |
A task that runs check | everything in the table above, including links between files | when you run the task |
1. Associate the XSD with the XML extension: elabftw-maiml xsd prints where it is (inside pymaiml). Put this in .vscode/settings.json in the working folder. VS Code does not read it in a folder it does not trust (Restricted Mode at the bottom left); click that and choose Trust.
{
"files.associations": { "*.maiml": "xml" },
"xml.fileAssociations": [
{ "pattern": "**/*.maiml",
"systemId": "C:/Users/<you>/miniconda3/envs/elabftw/Lib/site-packages/pymaiml/schema/MaiML-Schema-1_0/maiml.xsd" }
]
}2. Add a task in .vscode/tasks.json and run it with Ctrl+Shift+P → "Tasks: Run Test Task".
{
"version": "2.0.0",
"tasks": [
{
"label": "MaiML: check links",
"type": "process",
"command": "C:/Users/<you>/miniconda3/envs/elabftw/python.exe",
"args": ["-m", "elabftw_toolkit.maiml", "check", "${workspaceFolder}"],
"problemMatcher": {
"owner": "maiml",
"fileLocation": "absolute",
"pattern": {
"regexp": "^(.+?):(\\d+):(\\d+): (error|warning|info): (.*)$",
"file": 1, "line": 2, "column": 3, "severity": 4, "message": 5
}
},
"group": { "kind": "test", "isDefault": true },
"presentation": { "reveal": "silent" }
}
]
}This is the broken-example folder after running it. The file list gets counts, and the Problems list shows the XSD error (cvc-id.1, from the XML extension) next to the link problems (from the task; messages are in Japanese).

- The XML extension reports
cvc-id.1(no such reference target) on the last line of the file; the task'sREF-01gives the actual line (180 here). - Task results stay until you run it again; run it again after fixing.
- No editor extension of your own is needed for this. If you want cross-file checks while typing,
checkcould later become a language server.
Notes
- The bundled MaiML-Schema XSD is a work of JAIMA and must not be modified.
- Without pymaiml,
tests/test_maiml.pyis skipped. - Example use: SPring-8 BENTEN XAFS / HAXPES reference samples (
benten-cloud/eln/maiml_export.py).
Next: 11. Recipes.