Module 6: Prove it is right: XSD and SHACL¶
Learning objectives
By the end of this module, you can:
- O1. Check a DDI file against its official XSD with
ddigraph validate, and read its flavor, schema, issues and exit code. - O2. Run the same XSD check from Python with
ddigraph.validation.validate, and use its result in a script. - O3. Write SHACL shapes with
ddigraph shapes, and check an RDF export against them with pyshacl orddigraph validate. - O4. Explain why
--flavormatters when you check a graph against the shapes. - O5. Say which check answers which question: the XSD for the file you read, SHACL for the graph you made.
Prerequisites: Module 5
Time: 45 min self-paced / 60 min instructor-led.
Needs: No server. The SHACL part needs the shacl extra: pip install "ddigraph[shacl]".
New in this module: ddigraph validate, ddigraph.validation.validate, validate_shapes, ddigraph shapes, shapes_graph, ddigraph export, pyshacl, --flavor, --shapes
1. Two questions, two tools¶
There are two moments when "is this right?" is worth asking, and they need different tools.
- Before you load. Is this file valid DDI? That is a question about the XML. The answer comes from the XSD, the XML Schema that the DDI Alliance publishes for each flavor and version. A schema lists which elements may appear, where, and how often.
- After you build the graph. Does the graph have the classes and the properties it promises? That is a question about the graph. The answer comes from SHACL shapes. SHACL is a W3C language that describes what an RDF graph must look like.
Neither replaces the other. A valid DDI file can still produce a broken graph if the converter has a bug. A perfect graph can come from a file that never followed the schema.
2. Before: the XSD¶
ddigraph ships the official schemas: Codebook 2.6, Lifecycle 3.1 to 3.3,
and CDI 1.0. ddigraph validate picks the right one by itself. Check the
Labour Force Survey's DDI-L file:
ddigraph validate tests/fixtures/lfs_lifecycle.xml
Expected output (your paths will differ):
File: .../tests/fixtures/lfs_lifecycle.xml
Flavor: lifecycle 3.3
Schema: .../schemas/ddi/v3_3/instance_3_3.xsd
Result: valid
- Flavor and version. The flavor comes from the root element, as in
Module 1. The version,
3.3, comes from the namespaces the file declares, such asddi:datacollection:3_3. Checking a 3.3 file against the 3.1 schema would give a page of nonsense, so ddigraph does not leave that choice to you. - Result. The file follows the schema, so the command exits with 0.
A file that breaks the schema gets a list of issues. fragment_instance.xml
is a small test file, made to break the DDI 3.3 schema. It is not a real
survey:
ddigraph validate tests/fixtures/fragment_instance.xml --max-issues 3 || echo "exit code $?"
Expected output:
File: .../tests/fixtures/fragment_instance.xml
Flavor: lifecycle 3.3
Schema: .../schemas/ddi/v3_3/instance_3_3.xsd
Result: invalid (22 issue(s), showing 3)
line 8: Element '{ddi:datacollection:3_3}Instrument', attribute 'id': The attribute 'id' is not allowed.
line 8: Element '{ddi:datacollection:3_3}Instrument', attribute 'agency': The attribute 'agency' is not allowed.
line 8: Element '{ddi:datacollection:3_3}Instrument', attribute 'version': The attribute 'version' is not allowed.
exit code 1
- Issues. Each issue gives a line and the schema's message. In DDI
3.3, the agency, ID and version are child elements, not attributes, so
the schema refuses these three attributes. The result line counts every
issue, 22 here;
--max-issues 3shows the first three, and0shows them all. - Exit code. The command exits with 1 when the file is invalid, and 0
when it is valid. The
|| echoshows it. So a check in a build script is one line:ddigraph validate survey.xml || exit 1.
The test files fail on purpose
The four survey files, lfs_*.xml, are valid. Most of the other files
in tests/fixtures/ fail the XSD. They are test files, written to test
the readers, not to follow the schema.
Much published DDI is in the same position: it reads, it loads, and
it does not strictly validate. That is why ddigraph load does not
check the XSD unless you ask. Refusing files that work would make the
tool less useful. Ask with ddigraph load survey.xml --validate, which
refuses a file that does not conform.
3. The same check from Python¶
ddigraph.validation.validate returns the result as an object, so a script
can act on it. Here it checks the test file of section 2:
from ddigraph.validation import validate
result = validate("tests/fixtures/fragment_instance.xml", max_issues=1)
print("valid: ", result.valid)
print("flavor: ", result.flavor, result.version)
print("schema: ", result.schema.name)
for issue in result.issues:
print("issue: ", issue.line, issue.message)
Expected output:
valid: False
flavor: lifecycle 3_3
schema: instance_3_3.xsd
issue: 8 Element '{ddi:datacollection:3_3}Instrument', attribute 'id': The attribute 'id' is not allowed.
result.valid is a boolean. result.issues is a list of issues, each with
a line and a message. max_issues=1 keeps the first one only: an
invalid file can give thousands, and one is enough to say "no".
4. After: SHACL¶
A shape says what the nodes of one class must hold. ddigraph writes its shapes from the same mapping that gives the Neo4j schema and the RDF vocabulary, so the shapes cannot drift from what the exporter writes. Write them to a file, for any SHACL tool:
ddigraph shapes -o shapes.ttl --flavor lifecycle
Expected output:
Wrote shapes.ttl
Flavor: lifecycle
Triples: 19095
SHACL checks RDF, the graph format of the web of data, which
Module 8 covers. ddigraph export writes a DDI
file as RDF, here in the Turtle syntax. Then ddigraph validate checks an
RDF file against the shapes:
ddigraph export tests/fixtures/lfs_lifecycle.xml --format turtle -o survey.ttl
ddigraph validate survey.ttl --flavor lifecycle
Expected output:
Wrote survey.ttl
Format: turtle
Nodes: 87 Relationships: 108
Triples: 2106
File: .../survey.ttl
Shapes: lifecycle (2106 triples)
Shapes result: conforms
The graph conforms: it has the shape it promises. Here the two checks agree, since the survey file passed the XSD in section 2 too. They need not. The two checks answer different questions, and the reader is forgiving: it reads a file that bends the schema and still builds a well-formed graph. Export the test file of section 2, and its graph conforms too. Exercise 1 looks at such a case.
Any SHACL tool can run the check. Here it is with pyshacl, the Python SHACL
validator, and the same shapes from shapes_graph:
import pyshacl
import rdflib
import ddigraph
from ddigraph.rdf.shacl import shapes_graph
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
data = rdflib.Graph().parse("survey.ttl", format="turtle")
conforms, _report, _text = pyshacl.validate(data, shacl_graph=shapes_graph(flavor="lifecycle"))
print("conforms:", conforms)
Expected output:
conforms: True
5. What the shapes check¶
There is one shape for each type of each flavor, such as the Lifecycle
QuestionItem. It applies to every node of that class, and it checks:
- The key. Each node has exactly one
ddigraph:key. - One value. Each property has at most one value. A text has at most one value per language, and at most one with no language.
- The type of the value. A string, a number or a boolean, as the mapping says. Text may carry a language tag.
- Required properties. A property the mapping requires must be there,
such as a Lifecycle node's agency, ID and version. A stub, which carries
ddigraph:unresolvedReason, is let off: it holds only what the reference said. - The Dataset node. It has one
ddigraph:sourceand oneddigraph:flavor.
The shapes do not check where an edge points. To see a failure, break an
export on purpose, as a faulty converter might. This removes the key of
the question WORK, and gives it a second name, WORKED:
import pyshacl
import rdflib
import ddigraph
from ddigraph.rdf.shacl import shapes_graph
from ddigraph.rdf.vocabulary import DDIGRAPH
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
data = rdflib.Graph().parse("survey.ttl", format="turtle")
question = rdflib.URIRef("urn:ddi:example.nso:q-work:1")
data.remove((question, rdflib.URIRef(DDIGRAPH + "key"), None))
data.add((question, rdflib.URIRef(DDIGRAPH + "name"), rdflib.Literal("WORKED")))
conforms, report, _text = pyshacl.validate(data, shacl_graph=shapes_graph(flavor="lifecycle"))
print("conforms:", conforms)
SH = rdflib.Namespace("http://www.w3.org/ns/shacl#")
for message in sorted(str(m) for m in report.objects(None, SH.resultMessage)):
print(" ", message)
Expected output:
conforms: False
Less than 1 values on <urn:ddi:example.nso:q-work:1>->ddigraph:key
Each message names the node, the property and the rule it broke.
ddigraph validate reports the same two results for such a file, and
exits with 1.
6. Why --flavor matters¶
Codebook and Lifecycle share 21 type names, such as Category, CodeList
and QuestionItem, and give them different rules. A Lifecycle node must
have an agency, an ID and a version. A Codebook node need not.
ddigraph validate cannot read the flavor from an RDF file. Without
--flavor, it uses the shapes of all three flavors, and a node of a shared
type passes if it matches either flavor's shape. That is a looser check.
validate_shapes shows the difference on the export of the survey's
codebook:
import ddigraph
from ddigraph.validation import validate_shapes
ddigraph.export("tests/fixtures/lfs_codebook.xml", "codebook.ttl", format="turtle")
for flavor in (None, "codebook", "lifecycle"):
result = validate_shapes("codebook.ttl", flavor=flavor)
print(f"{flavor or 'all flavors':12} conforms={result.valid} results={result.total}")
Expected output:
all flavors conforms=True results=0
codebook conforms=True results=0
lifecycle conforms=False results=109
The export is correct Codebook, so it passes its own flavor's shapes. With the Lifecycle shapes, 109 results say that 39 of its nodes, such as its categories, concepts and variables, lack the agency, ID or version a Lifecycle node must have. Now suppose this graph was meant to be Lifecycle. The check with no flavor would still say "conforms", and let those 109 problems through. Pass the file's own flavor, and the check is as strict as it should be.
You met the same clash in Module 3: DDI-CDI avoids it by putting CDI in
front of every type name.
For a DDI XML file, --shapes runs both checks in one go. It builds the
graph, as ddigraph export would, and uses the flavor it detected:
ddigraph validate tests/fixtures/lfs_codebook.xml --shapes
Expected output:
File: .../tests/fixtures/lfs_codebook.xml
Flavor: codebook
Schema: .../schemas/ddi-c/codebook.xsd
Result: valid
Shapes: codebook (1343 triples)
Shapes result: conforms
The file follows the schema, and its graph has the right shape. Both checks pass, so the command exits with 0, and a build step goes on. The CLI reference lists every option.
Exercises¶
Scenario
Your archive accepts DDI files from partners, and wants a check before each file goes into the catalog. You try both checks on a few files and decide what each one can tell you.
Exercise 1 (O1, O5). tests/fixtures/cdi_sample.xml is a small test
file, not a survey, made with an odd namespace. Check it against its XSD.
Then export it as Turtle to cdi.ttl, and check the export against the
CDI shapes. Do the two checks agree? What does that tell you?
Expected output: the XSD result, then the SHACL result.
Answer
ddigraph validate tests/fixtures/cdi_sample.xml || echo "exit code $?"
ddigraph export tests/fixtures/cdi_sample.xml --format turtle -o cdi.ttl
ddigraph validate cdi.ttl --flavor cdi
File: .../tests/fixtures/cdi_sample.xml
Flavor: cdi
Schema: .../schemas/ddi-cdi/xml-schema/ddi-cdi.xsd
Result: invalid (1 issue(s))
line 10: Element '{http://ddi-cdi/1.0}Wrapper': No matching global declaration available for the validation root.
exit code 1
Wrote cdi.ttl
Format: turtle
Nodes: 9 Relationships: 3
Triples: 149
File: .../cdi.ttl
Shapes: cdi (149 triples)
Shapes result: conforms
They disagree: the XSD says no, SHACL says yes. The file declares the
namespace http://ddi-cdi/1.0, which is not the one the published
schema uses, so the schema has nothing to match its root element. The
reader does not mind, and builds a correct graph. A disagreement like
this points at the input file, not at what you built from it.
Exercise 2 (O2). Write a script that checks every XML file in
tests/fixtures/ against its XSD, and prints its name and valid or
invalid, in name order.
Expected output:
cdi_correspondence.xml invalid
cdi_inherited_endpoints.xml invalid
cdi_sample.xml invalid
cdi_valid_minimal.xml valid
codebook_sample.xml invalid
fragment_instance.xml invalid
ir_cdi_valid.xml valid
lfs_cdi.xml valid
lfs_codebook.xml valid
lfs_correspondence.xml valid
lfs_lifecycle.xml valid
reusable_fragments.xml invalid
Answer
from pathlib import Path
from ddigraph.validation import validate
for path in sorted(Path("tests/fixtures").glob("*.xml")):
result = validate(path, max_issues=1)
print(path.name, "valid" if result.valid else "invalid")
cdi_correspondence.xml invalid
cdi_inherited_endpoints.xml invalid
cdi_sample.xml invalid
cdi_valid_minimal.xml valid
codebook_sample.xml invalid
fragment_instance.xml invalid
ir_cdi_valid.xml valid
lfs_cdi.xml valid
lfs_codebook.xml valid
lfs_correspondence.xml valid
lfs_lifecycle.xml valid
reusable_fragments.xml invalid
max_issues=1 stops counting after the first issue: to sort files
into valid and invalid, one is enough. The four survey files pass, and
so do two CDI test files. The other test files fail on purpose, as
section 2 said.
Exercise 3 (O3). Export tests/fixtures/lfs_lifecycle.xml as Turtle.
Remove the version of the code list "Highest level of education"
(owl:versionInfo on urn:ddi:example.nso:cl-education:1), save the graph
as broken.ttl, and check it against the Lifecycle shapes. Print whether
it conforms, how many results there are, and the node and the constraint of
each.
Expected output:
conforms: False results: 1
urn:ddi:example.nso:cl-education:1 OrConstraintComponent
Answer
import rdflib
import ddigraph
from ddigraph.validation import validate_shapes
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
data = rdflib.Graph().parse("survey.ttl", format="turtle")
code_list = rdflib.URIRef("urn:ddi:example.nso:cl-education:1")
data.remove((code_list, rdflib.OWL.versionInfo, None))
data.serialize("broken.ttl", format="turtle")
result = validate_shapes("broken.ttl", flavor="lifecycle")
print("conforms:", result.valid, "results:", result.total)
for issue in result.issues:
print(issue.focus_node, issue.constraint)
conforms: False results: 1
urn:ddi:example.nso:cl-education:1 OrConstraintComponent
A required property is written as an "or": the node must have the
version, or be a stub with an unresolvedReason. This node is
neither, so the "or" fails. The full message lists both choices.
Exercise 4 (O4). Export tests/fixtures/lfs_lifecycle.xml, a
correct Lifecycle file, and check the export against the Codebook shapes,
then against the Lifecycle shapes. Print the flavor, whether it conforms
and the number of results. Which result do you trust?
Expected output:
codebook conforms=False results=51
lifecycle conforms=True results=0
Answer
import ddigraph
from ddigraph.validation import validate_shapes
ddigraph.export("tests/fixtures/lfs_lifecycle.xml", "survey.ttl", format="turtle")
for flavor in ("codebook", "lifecycle"):
result = validate_shapes("survey.ttl", flavor=flavor)
print(f"{flavor:10} conforms={result.valid} results={result.total}")
codebook conforms=False results=51
lifecycle conforms=True results=0
Trust the Lifecycle result: it uses the file's own flavor. The
Codebook shapes expect a dataset_id on each Category, CodeList,
Concept, QuestionItem, Universe and Variable, because Codebook
IDs are scoped to a dataset. A DDI-L node has a URN instead. So the
wrong flavor raises 51 false alarms, one for each node of those six
types: 23 categories, 6 code lists, 5 concepts, 8 questions, 2
universes and 7 variables.
Quiz¶
Question 1 (O1): In a build script, ddigraph validate survey.xml finds two issues. What happens next?
A. Nothing: it only prints the issues.
B. It exits with code 1, so a step such as ddigraph validate survey.xml || exit 1 stops the build.
C. It fixes the file.
D. It loads the file into Neo4j anyway.
Answer
B. The exit code is 1 for an invalid file and 0 for a valid one, which is all a build step needs. The command never changes the file (C).
Question 2 (O5): A partner's file has a typo in an element name, <r:Agnecy>. Which check catches it?
A. The XSD, because the schema does not allow that element there.
B. SHACL, because the agency is a required property.
C. Neither: ddigraph fixes typos.
D. Both, in the same way.
Answer
A. A wrong element is a question about the XML, so the schema answers it. B is tempting, but SHACL sees only the graph, never the XML, so it cannot point at the element that was misspelled.
Question 3 (O5): A bug in a converter writes a node with no ddigraph:key. Which check catches it?
A. The XSD of the source file.
B. The SHACL shapes, which require exactly one key on each node.
C. ddigraph detect.
D. None: keys are optional.
Answer
B. The source file can be perfect while the graph is wrong. Only a check on the graph sees what the converter made.
Question 4 (O1): Why does ddigraph load not check the XSD unless you pass --validate?
A. Checking is too slow to be useful.
B. Much real DDI reads and loads well but does not strictly follow the schema, and refusing it would help no one.
C. The schemas are not shipped with ddigraph.
D. Neo4j checks the XSD itself.
Answer
B. You choose when to be strict. The schemas do ship with
ddigraph (C): ddigraph validate uses them.
Question 5 (O4): A Codebook export passes with no --flavor, and fails with --flavor lifecycle. What should you conclude?
A. The export is broken.
B. Nothing useful: check it with --flavor codebook, its own flavor.
C. The XSD is wrong.
D. Always use no flavor, since it passes.
Answer
B. The Lifecycle shapes expect an agency, an ID and a version that Codebook nodes need not have. With no flavor, a shared type passes if it matches any flavor's shape, which is looser (D). The file's own flavor gives the right check.
Question 6 (O3): What does ddigraph shapes -o shapes.ttl --flavor lifecycle write?
A. The Lifecycle XSD.
B. SHACL shapes in Turtle, made from ddigraph's mapping, that any SHACL tool can use.
C. An RDF export of a DDI file.
D. A report of the issues in a file.
Answer
B. The shapes are a graph themselves. Pass them to pyshacl,
or to another SHACL tool, to check an export. C is what
ddigraph export writes.
Question 7 (O2): validate(path, max_issues=1) returns one issue. Does the file have only one problem?
A. Yes: issues lists every problem.
B. Not necessarily: max_issues=1 keeps only the first one.
C. No: it always has at least two.
D. Yes, because the file is valid.
Answer
B. max_issues caps the list. Use max_issues=0 to keep them
all. A file with an issue is invalid (D): result.valid is
False.
Check yourself¶
- I can check a DDI file against its XSD with
ddigraph validate, and read its flavor, schema, issues and exit code. (O1) - I can run the XSD check from Python with
ddigraph.validation.validateand use its result. (O2) - I can write SHACL shapes with
ddigraph shapes, and check an export with pyshacl orddigraph validate. (O3) - I can explain why
--flavormatters when checking a graph against the shapes. (O4) - I can say which check answers which question: the XSD for the file, SHACL for the graph. (O5)