Skip to content

Latest commit

 

History

History
61 lines (51 loc) · 7.62 KB

IMPLEMENTATION.md

File metadata and controls

61 lines (51 loc) · 7.62 KB

Technical Implementation Guide: dartfx-cdif

Architecture Overview

dartfx-cdif provides type-safe Pydantic v2 + RDF models for the Cross-Domain Interoperability Framework (CDIF) profiles, generated directly from the upstream JSON Schemas, JSON-LD contexts, and SKOS vocabularies under git-cdif.

flowchart LR
    Schemas["git-cdif Schemas, @context & .ttl Vocabularies"] --> Codegen["dartfx.cdif.codegen\n(loader -> resolver -> emitter)"]
    Codegen --> Models["dartfx.cdif.models\n(vocabularies, common, profiles/*)"]
    Models --> Base["CdifBaseModel\n(dartfx.rdf.pydantic.RdfBaseModel)"]
    Base --> JSONLD["Framed JSON-LD\n(from_jsonld / to_jsonld_dict)"]
    Base --> RDF["rdflib.Graph\n(from_rdf / to_rdf)"]
    Models --> Registry["ProfileRegistry\n(detect_profiles / load_cdif)"]
Loading

Core Modules

1. Namespaces (src/dartfx/cdif/namespaces.py)

Defines canonical rdflib.Namespace bindings matching validation/CDIF-context-2026.jsonld (SCHEMA, DCTERMS, PROV, DQV, GEOSPARQL, SPDX, TIME, SF, CDI, CDIF, CSVW, DCAT, SKOS, BIOS, CDIFACT, GSBPM, XSD), CDIF_PREFIXES, and CURIE resolution helpers (expand_curie, prefix_expr_for_curie).

2. Base Model (src/dartfx/cdif/models/_base.py)

CdifBaseModel extends dartfx.rdf.pydantic.RdfBaseModel to support dual JSON-LD and RDF graph usage:

  • Dual Serialization: Uses Field(alias="prefix:term") with ConfigDict(arbitrary_types_allowed=True, populate_by_name=True, extra="allow") alongside Annotated[T, RdfProperty(PREFIX.term)].
    • to_jsonld_dict() / to_jsonld() / from_jsonld() operate directly on framed JSON-LD dictionaries and @graph envelopes.
    • to_rdf() / from_rdf() / to_rdf_graph() / from_rdf_graph() round-trip through rdflib.Graph via dartfx-rdf across Turtle, JSON-LD, RDF/XML, and N-Triples.
  • Main-Entity Disambiguation (_infer_subject): Real CDIF graphs commonly contain multiple schema:Dataset nodes (the root dataset, its schema:subjectOf dcat:CatalogRecord, and schema:hasPart child datasets). CdifBaseModel._infer_subject filters out catalog records and schema:hasPart members before selecting the root entity.
  • Typed Union Discrimination (_resolve_typed_union_fields): A mode="before" model validator resolves JSON-LD dicts in multi-model union fields (e.g., Person | Organization | ObjectReference, DataDownload | WebAPI, DefinedTerm | Concept, DataStructure variants) by matching @type (CURIEs, full URIs including http(s)://schema.org/, and bare local names) against each candidate class's rdf_type, routing @id-only dicts to ObjectReference and falling back gracefully for unrecognized external types.
  • Blank-Node Preservation (DefaultUriGenerator(auto_uuid=False)): Models without an @id serialize to RDF as anonymous BNodes (and explicit _:... IDs as deterministic BNodes) rather than minting ephemeral urn:uuid: IRIs; dartfx-rdf's RdfBaseModel.from_rdf_graph preserves blank-node subjects and keeps id=None on round-trip.
  • Lossless Extra & JSON-LD Value RDF Serialization (_serialise_into_graph & _value_to_node): Propagates active @context prefix/@vocab/@type: @id bindings down nested models, serializes undeclared model_extra properties and additional @type assertions, keeps plain str values as RDF Literals unless typed @type: @id in @context (preventing colon-containing text from becoming invalid URIRefs), converts JSON-LD dicts ({"@id": ...}, {"@value": ..., "@language": ...}, {"@list": [...]}, {"@set": [...]}, and nested node objects) and LanguageTaggedValue models into proper RDF terms/collections, and emits a UserWarning if an extra property key cannot be resolved to a predicate URI.
  • Deferred Profile Conformance (validate_conformance): Models stay ergonomic to construct incrementally, while validate_conformance(strict=False) validates against the combined cdif_required_fields and cdif_any_of_required of the profiles declared in schema:subjectOf.dcterms:conformsTo (falling back to the class's own constraints when no known CDIF profile is declared).

3. Code Generator (src/dartfx/cdif/codegen/)

  • config.py: Declares ProfileSpec entries for all 8 profiles (core, discovery, data_description, data_structure, provenance, manifest, codelist, complete) and resolve_cdif_root() (--cdif-root → CDIF_ROOT env var → sibling git-cdif directory).
  • loader.py: Loads *StructuredSchema.json files, composite schemas (CDIFDiscoverySchema.json, CDIFDataDescriptionSchema.json), CDIF-context-2026.jsonld, and SKOS provenance activity concepts from profile-provenance/vocabularies/CDIF_Activities.ttl.
  • ir.py: Intermediate Representation dataclasses (EnumIR, TypeAliasIR, FieldIR, ClassIR, ModuleIR).
  • resolver.py:
    • Deduplicates $defs across schemas into models/common.py and promotes inline typed sub-objects (CatalogRecord, DataDownload, WebAPI, MonetaryGrant, Place, GeoCoordinates, GeoShape, ProperInterval, Instant, TimePosition, QualityMeasurement, CdifProvActivity, ManifestPart, ArchivePart, DataStructure variants, value domains) into first-class CdifBaseModel classes.
    • Translates @type constraints (const / contains.const / default) into rdf_type declarations and CURIE property names into RdfProperty(...) predicates + JSON-LD aliases.
    • Composes non-overlapping profile mixins (CdifDiscoveryMixin, CdifDataDescriptionMixin, CdifProvenanceMixin, CdifManifestMixin) into profile dataset classes (CdifCoreDataset → CdifDiscoveryDataset → CdifDataDescriptionDataset → CdifCompleteDataset).
  • emitter.py: Emits Ruff-formatted, pyrefly-clean Python modules under src/dartfx/cdif/models/.

4. Profile Registry & CLI (src/dartfx/cdif/registry.py, src/dartfx/cdif/cli.py)

  • ProfileRegistry maps profile keys, aliases, and 2.0 / 1.1 / 1.0 / composite URIs to their corresponding CdifBaseModel root class.
  • detect_profiles() honors explicit schema:subjectOf.dcterms:conformsTo declarations when present and falls back to structural property heuristics aligned with detect_conformance.py (skos:ConceptScheme, cdif:hasPrimaryKey / cdi:InstanceVariable, schema:variableMeasured, dual-typed prov:Activity + schema:Action with schema:instrument / object / actionProcess, schema:hasPart) when absent.
  • load_cdif() parses JSON-LD or RDF files/strings into the most specific matching profile model.
  • cli.py exposes cdif codegen, cdif profiles, and cdif validate.

5. Documentation (docs/)

Sphinx documentation suite with Read the Docs theme and MyST-Parser:

  • overview.md: CDIF background, cross-domain motivation, and dartfx-cdif architecture.
  • quickstart.md: Installation, model hydration, property access, dual serialization, and conformance validation.
  • models.md: CdifBaseModel architecture, main-entity subject inference (_infer_subject), RDF predicate mapping, common sub-models, and controlled vocabularies.
  • profiles.md: Detailed catalog for all 8 profiles (core, discovery, datadescription, datastructure, provenance, manifest, codelist, complete).
  • generator.md: Code generator pipeline (Loader → Resolver → IR → Emitter) and schema drift management.
  • registry.md: Profile registry, detection algorithms, and polymorphic loading via load_cdif().
  • cli.md: Reference for cdif profiles, cdif validate, and cdif codegen.
  • api/: Full Sphinx autodoc API references covering all public modules and classes.
  • Verified build with zero warnings: sphinx-build -W -b html docs/source docs/build/html.