Skip to content

ontocast.tool.facts_validation.date_values

Date values for nodes that stand for a date, read from their labels.

A node standing for a date (an instant, a day, a month, a year) must say which date it is with a typed ISO 8601 literal: a label alone is text no query can compare or order. The render is told so; this pass makes it hold in code. A node is taken to stand for a date when it is the object of a temporal property, is typed with an OWL-Time class, or carries a label that is a whole calendar date or month. When its label parses as a date and it carries no date-typed literal, the parsed value is added: through the one catalog property whose domain fits the node and whose range is the value's datatype, else OWL-Time's inXSD* property for a time:Instant, else rdf:value. Nothing is removed, and a label that does not parse is left as it is. Month names are read in English.

Attributes

DATE_DATATYPES = CALENDAR_DATATYPES module-attribute

__all__ = ['DATE_DATATYPES', 'add_date_values', 'parse_date_label'] module-attribute

Classes

Functions:

add_date_values(graph, ontology_graph, fact_namespaces)

Give every undated node that stands for a date the value its label names.

Parameters:

Name Type Description Default
graph RDFGraph

The aggregated facts graph; edited in place.

required
ontology_graph RDFGraph

The ontology context the facts were validated against.

required
fact_namespaces Sequence[str]

Namespaces holding minted instances.

required

Returns:

Type Description
list[GraphRepairRecord]

list[GraphRepairRecord]: One date_value_added record per node, its

list[GraphRepairRecord]

target the added literal.

Source code in ontocast/tool/facts_validation/date_values.py
def add_date_values(
    graph: RDFGraph,
    ontology_graph: RDFGraph,
    fact_namespaces: Sequence[str],
) -> list[GraphRepairRecord]:
    """Give every undated node that stands for a date the value its label names.

    Args:
        graph: The aggregated facts graph; edited in place.
        ontology_graph: The ontology context the facts were validated against.
        fact_namespaces: Namespaces holding minted instances.

    Returns:
        list[GraphRepairRecord]: One ``date_value_added`` record per node, its
        target the added literal.
    """
    temporal_properties = _temporal_properties(ontology_graph)
    in_position: set[Node] = {
        obj
        for predicate in temporal_properties
        for obj in graph.objects(None, predicate)
        if isinstance(obj, BNode | URIRef)
    }
    instances = fact_instances(graph, fact_namespaces)
    # A structured value under a temporal property is a blank node.
    candidates = instances | {node for node in in_position if isinstance(node, BNode)}
    records: list[GraphRepairRecord] = []
    for node in sorted(candidates, key=str):
        if _is_dated(node, graph):
            continue
        temporal, instant = _temporal_type(node, graph, ontology_graph)
        positioned = node in in_position or temporal
        labels = sorted(
            str(label)
            for label in graph.objects(node, RDFS.label)
            if isinstance(label, Literal)
        )
        value = next(
            (
                parsed
                for label in labels
                if (parsed := parse_date_label(label, allow_year=positioned))
                is not None
            ),
            None,
        )
        if value is None:
            continue
        datatype = URIRef(str(value.datatype))
        predicate = (
            _date_property(node, datatype, graph, ontology_graph)
            or (_INSTANT_PROPERTY.get(datatype) if instant else None)
            or RDF.value
        )
        graph.add((node, predicate, value))
        records.append(
            GraphRepairRecord(
                kind=FactsGateRepairKind.DATE_VALUE_ADDED,
                source=str(node),
                target=f'"{value}"^^<{value.datatype}>',
            )
        )
    return records

parse_date_label(label, *, allow_year)

The typed ISO 8601 literal a label names as a whole, or None.

Reads ISO forms (2021, 2021-06, 2021-06-27, a date-time) and English calendar forms (June 2021, 27 June 2021, June 27, 2021, abbreviated months too). The whole label must be the date: mid-June 2021 or summer 2021 name no single value and give None.

Parameters:

Name Type Description Default
label str

The node's label.

required
allow_year bool

Whether a bare four-digit year counts; it is a date only where the node's position already says it stands for a time.

required

Returns:

Type Description
Literal | None

Literal | None: An xsd:gYear, xsd:gYearMonth, xsd:date or

Literal | None

xsd:dateTime literal.

Source code in ontocast/tool/facts_validation/date_values.py
def parse_date_label(label: str, *, allow_year: bool) -> Literal | None:
    """The typed ISO 8601 literal a label names as a whole, or ``None``.

    Reads ISO forms (``2021``, ``2021-06``, ``2021-06-27``, a date-time) and
    English calendar forms (``June 2021``, ``27 June 2021``, ``June 27, 2021``,
    abbreviated months too). The whole label must be the date: ``mid-June
    2021`` or ``summer 2021`` name no single value and give ``None``.

    Args:
        label: The node's label.
        allow_year: Whether a bare four-digit year counts; it is a date only
            where the node's position already says it stands for a time.

    Returns:
        Literal | None: An ``xsd:gYear``, ``xsd:gYearMonth``, ``xsd:date`` or
        ``xsd:dateTime`` literal.
    """
    text = " ".join(label.split()).strip().lower()
    if _ISO_YEAR.fullmatch(text):
        return Literal(text, datatype=XSD.gYear) if allow_year else None
    if match := _ISO_YEAR_MONTH.fullmatch(text):
        if 1 <= int(match.group(2)) <= 12:
            return Literal(text, datatype=XSD.gYearMonth)
        return None
    if _ISO_DATE.fullmatch(text):
        try:
            return Literal(date.fromisoformat(text).isoformat(), datatype=XSD.date)
        except ValueError:
            return None
    if _ISO_DATE_TIME.fullmatch(text):
        try:
            return Literal(
                datetime.fromisoformat(text.upper()).isoformat(),
                datatype=XSD.dateTime,
            )
        except ValueError:
            pass
    if match := _MONTH_YEAR.fullmatch(text):
        month = _MONTHS.get(match.group("month"))
        if month is not None:
            return Literal(
                f"{match.group('year')}-{month:02d}", datatype=XSD.gYearMonth
            )
        return None
    for pattern in (_DAY_MONTH_YEAR, _MONTH_DAY_YEAR):
        if match := pattern.fullmatch(text):
            month = _MONTHS.get(match.group("month"))
            if month is None:
                return None
            try:
                day = date(int(match.group("year")), month, int(match.group("day")))
            except ValueError:
                return None
            return Literal(day.isoformat(), datatype=XSD.date)
    return None