# CDIF Models Architecture The CDIF models in `dartfx-cdif` represent the fusion of **Pydantic v2 data validation** and **W3C RDF semantic graphs** powered by `dartfx-rdf`. This document describes the model hierarchy, subject inference mechanisms, dual serialization, and conformance validation. --- ## The `CdifBaseModel` Foundation Every model class in `dartfx-cdif` inherits from `CdifBaseModel`, which in turn extends `dartfx.rdf.pydantic.RdfBaseModel`: ``` +---------------------------------------+ | pydantic.BaseModel | +-------------------+-------------------+ | +-------------------+-------------------+ | dartfx.rdf.pydantic.RdfBaseModel | | - RDF Graph conversion (to_rdf) | | - RDF Graph hydration (from_rdf) | | - RdfProperty annotations | +-------------------+-------------------+ | +-------------------+-------------------+ | dartfx.cdif.models.CdifBaseModel | | - Framed JSON-LD aliases (@id, etc.) | | - Subject inference (_infer_subject) | | - Conformance checks (validate_...) | | - Profile metadata ClassVars | +-------------------+-------------------+ | +-------------------------+-------------------------+ | | v v +-------------------------------+ +-------------------------------+ | Common Sub-Models | | Profile Root Models | | - Person, Organization | | - CdifCoreDataset | | - Identifier, SpatialCoverage| | - CdifDiscoveryDataset | | - VariableMeasured, etc. | | - CdifCompleteDataset, etc. | +-------------------------------+ +-------------------------------+ ``` ### Core Features of `CdifBaseModel` 1. **Standard JSON-LD Aliases**: Fields are annotated with aliases matching CDIF's canonical JSON-LD compact CURIEs (e.g., `schema:name`, `schema:description`, `@id`, `@type`, `@context`). 2. **Configured for Permissive Deserialization**: `extra="allow"` ensures that unexpected extension properties in foreign JSON-LD documents do not crash the parser. 3. **Strict Profile Conformance**: While Pydantic deserialization is permissive, rigorous profile conformance is enforced on-demand via `validate_conformance()`. 4. **Namespace Management**: Automatically pre-binds standard CDIF namespaces (`schema`, `dcterms`, `dcat`, `prov`, `cdi`, `cdif`, `skos`, `xsd`). --- ## Main-Entity Subject Inference A common challenge in CDIF metadata is that a single JSON-LD file or RDF graph often contains multiple top-level or related entities: * A `schema:Dataset` node representing the research data. * A `dcat:CatalogRecord` node representing metadata provenance (`schema:subjectOf`). * Multiple `schema:Person` or `schema:Organization` nodes (`schema:creator`). * Child datasets linked via `schema:hasPart`. When hydrating a model from an `rdflib.Graph` without specifying an explicit `subject` URI, `CdifBaseModel._infer_subject()` executes a deterministic disambiguation strategy: ``` [ Incoming RDF Graph ] | +-----------------------+-----------------------+ | | Check explicitly declared Scan graph for candidate model rdf_type (e.g. schema:Dataset nodes schema:Dataset) | | v | Filter out dcat:CatalogRecord nodes | and schema:hasPart child nodes | | +-----------------------+-----------------------+ | [ Disambiguated Root Node ] | Matches root URI -> Model hydrated successfully! ``` ### Filtering Algorithm 1. **Explicit Type Match**: Finds subjects whose `rdf:type` matches the model's `rdf_type` class attribute. 2. **Catalog Record Exclusion**: If multiple subjects match `schema:Dataset`, nodes that also have type `dcat:CatalogRecord` (or are pointed to by `schema:subjectOf`) are excluded from consideration as the dataset root. 3. **Parent Hierarchy Preference**: If a graph contains parent and child datasets linked via `schema:hasPart`, the parent node (which is not targeted by an incoming `hasPart`) is chosen. 4. **Fallback**: If no unambiguous candidate is found, the first typed subject is returned. --- ## Dual Serialization in Practice ### 1. Framed JSON-LD Serialization `dartfx-cdif` models can be loaded directly from JSON-LD and serialized back to framed dictionaries: ```python from dartfx.cdif.models.profiles.core import CdifCoreDataset # Deserialization from JSON-LD dictionary or file dataset = CdifCoreDataset.from_jsonld("path/to/dataset.jsonld") # Serialization to a clean JSON-LD dictionary doc = dataset.to_jsonld() assert doc["@type"] == ["schema:Dataset"] assert "@context" in doc ``` ### 2. RDF Graph Serialization Because `CdifBaseModel` inherits from `RdfBaseModel`, every property is mapped to an RDF predicate URI using `dartfx.rdf.pydantic.RdfProperty`: ```python from rdflib import Graph, URIRef from dartfx.cdif.models.profiles.core import CdifCoreDataset # Convert model to an rdflib.Graph graph: Graph = dataset.to_rdf() # Query graph using SPARQL query = """ PREFIX schema: SELECT ?name ?desc WHERE { ?s schema:name ?name ; schema:description ?desc . } """ for row in graph.query(query): print(f"Dataset: {row.name}") # Rehydrate model from graph reconstructed = CdifCoreDataset.from_rdf(graph, subject=URIRef(dataset.id)) ``` --- ## Conformance Validation CDIF profiles define strict metadata guidelines beyond raw JSON schema types. `validate_conformance()` validates both instances and raw dictionaries against: 1. **Mandatory Fields (`cdif_required_fields`)**: Checks that required attributes (e.g., `schema:name`, `schema:description`, `schema:identifier`) are present and not empty. 2. **Conditional Group Requirements (`cdif_any_of_required`)**: Checks that at least one field from an `anyOf` tuple is populated (e.g., `schema:license` or `schema:conditionsOfAccess`). 3. **Forbidden Extra Fields (`cdif_forbid_extra`)**: Used in strict profile classes where arbitrary undeclared properties are disallowed. ```python from dartfx.cdif.models._base import ConformanceReport, ConformanceError report: ConformanceReport = dataset.validate_conformance() print(f"Profile: {report.profile_uri}") print(f"Is Conforming: {report.is_valid}") if not report.is_valid: for error in report.errors: print(f"Error on {error.field_name}: {error.message} (Rule: {error.rule_type})") ``` --- ## Common Sub-Models (`dartfx.cdif.models.common`) The `dartfx.cdif.models.common` module contains over 100 reusable components shared across CDIF profiles: | Model Class | RDF Type | Description | | :--- | :--- | :--- | | `Person` | `schema:Person` | An individual researcher, author, or contact. | | `Organization` | `schema:Organization` | A university, research institute, or repository publisher. | | `Identifier` | `schema:PropertyValue` | Persistent identifier (DOI, Handle, ARK, ROR, ORCID). | | `SpatialCoverage` | `schema:Place` | Geographic bounding box, point, or named locality. | | `TemporalCoverage` | `schema:TemporalCoverage` | Date, interval, or ISO 8601 period. | | `DataDownload` | `schema:DataDownload` | Direct file distribution, media type, byte size, URL. | | `DataService` | `schema:DataService` | Web service or API providing data access. | | `VariableMeasured` | `schema:PropertyValue` | Measured observable property or parameter. | | `CatalogRecord` | `dcat:CatalogRecord` | Provenance metadata record documenting the dataset. | | `DefinedTerm` | `schema:DefinedTerm` | Controlled term from an external ontology or authority. | | `ObjectReference` | N/A | Lightweight `@id` pointer referencing external entities. | --- ## Controlled Vocabularies (`dartfx.cdif.models.vocabularies`) The `dartfx.cdif.models.vocabularies` module exports standard enumerations extracted from CDIF schemas and SKOS Turtle ontologies: ### `XsdDataType` Enumerates supported XML Schema datatypes for variable typing: ```python from dartfx.cdif.models.vocabularies import XsdDataType print(XsdDataType.DECIMAL) # "xsd:decimal" print(XsdDataType.DATE_TIME) # "xsd:dateTime" print(XsdDataType.STRING) # "xsd:string" ``` ### `CdifActivityType` Enumerates provenance activity concepts defined by the CDIF provenance vocabulary: ```python from dartfx.cdif.models.vocabularies import CdifActivityType print(CdifActivityType.DATA_COLLECTION) # "cdifact:DataCollection" print(CdifActivityType.DATA_PROCESSING) # "cdifact:DataProcessing" print(CdifActivityType.DATA_ANALYSIS) # "cdifact:DataAnalysis" ```