# ==========================================================================
#  W15  Connections as shapes
# ==========================================================================
#
#  FROM      Across the Water, "Connections as shapes"
#            https://www.semantechs.co.uk/articles/across-the-water/
#
#  CHECKS
#    Every leg says where, when and who; every stop has one code and names
#    tagged by language; every connection leaves at least the time the next
#    leg needs, measured from the actual arrival where one has been recorded.
#
#  HOW IT WORKS
#    tr:LegShape and tr:StopShape are Core. tr:ConnectionShape is a SPARQL
#    constraint on every leg that follows another. COALESCE takes the previous
#    leg's actual arrival if there is one and its planned arrival if not, and
#    the gap is worked out in minutes from DAY, HOURS and MINUTES -- SPARQL
#    1.1 has no subtraction for dateTimes that every engine supports, so the
#    arithmetic is done by hand.
#
#  DIAGRAM
#    leg 4  walk across Glasgow     arrives 10:57
#    leg 5  train to Ayr            leaves  11:00     3 min,  needs 5   -> violation
#    leg 6  coach to Cairnryan      planned 13:10, actual 13:28 (held up on the A77)
#    leg 7  ferry to Belfast        leaves  14:00    32 min,  needs 45  -> violation
#
#  WHAT TO TAKE AWAY
#    - Planned and actual are both kept, and the rule chooses between them.
#      That is the difference between a timetable and a journey.
#    - A late coach is a fact about one leg that breaks a rule about the next.
#      Only a graph that holds both can see it.
#
#  TRY IT
#    In the data tab, change leg 6's actual arrival from 13:28 to 13:10 and
#    validate again. The ferry connection is safe again: one violation, the
#    walk across Glasgow.
#
#  DATA      journey.ttl
#  LOAD IT   https://semantechs.co.uk/turtle-editor-viewer/?dot=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F06-across-the-water%2Fjourney.ttl&shapes=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F06-across-the-water%2Fw15-connections-as-shapes.ttl
#  SPEC      SPARQL 1.1 Query 17.4.5 Functions on Dates and Times
#            https://www.w3.org/TR/sparql11-query/#func-date-time
#  REPORTS   does not conform -- 2 violations, 0 warnings, 0 info; 10 shapes
# ==========================================================================

@prefix tr:     <https://example.org/travel/> .
@prefix gist:   <https://w3id.org/semanticarts/ns/ontology/gist/> .
@prefix schema: <https://schema.org/> .
@prefix sh:     <http://www.w3.org/ns/shacl#> .
@prefix xsd:    <http://www.w3.org/2001/XMLSchema#> .

tr:LegShape a sh:NodeShape ;
    sh:targetClass gist:ScheduledEvent ;
    sh:property [ sh:path tr:from ; sh:minCount 1 ; sh:class tr:Stop ] ;
    sh:property [ sh:path tr:to ; sh:minCount 1 ; sh:class tr:Stop ] ;
    sh:property [ sh:path tr:operator ; sh:minCount 1 ] ;
    sh:property [ sh:path gist:plannedStartDateTime ; sh:minCount 1 ; sh:datatype xsd:dateTime ] ;
    sh:property [ sh:path gist:plannedEndDateTime ; sh:minCount 1 ; sh:datatype xsd:dateTime ] .

tr:StopShape a sh:NodeShape ;
    sh:targetClass tr:Stop ;
    sh:property [ sh:path tr:stopCode ; sh:minCount 1 ; sh:maxCount 1 ] ;
    sh:property [ sh:path schema:name ; sh:languageIn ( "en" "gd" "ga" ) ; sh:minCount 1 ] .

tr:ConnectionShape a sh:NodeShape ;
    sh:targetSubjectsOf tr:after ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes tr:prefixes ;
        sh:message "Only {?slack} minutes after the previous leg arrives; this connection needs {?need}" ;
        sh:select """
            SELECT $this ?slack ?need WHERE {
                $this tr:after ?prev ;
                      tr:minConnectionMinutes ?need ;
                      gist:plannedStartDateTime ?start .
                ?prev gist:plannedEndDateTime ?planned .
                OPTIONAL { ?prev gist:actualEndDateTime ?actual }
                BIND (COALESCE(?actual, ?planned) AS ?end)
                BIND ((DAY(?start) * 1440 + HOURS(?start) * 60 + MINUTES(?start))
                    - (DAY(?end) * 1440 + HOURS(?end) * 60 + MINUTES(?end)) AS ?slack)
                FILTER (?slack < ?need)
            }
        """ ;
    ] .

tr:prefixes
    sh:declare [ sh:prefix "tr" ; sh:namespace "https://example.org/travel/"^^xsd:anyURI ] ;
    sh:declare [ sh:prefix "gist" ; sh:namespace "https://w3id.org/semanticarts/ns/ontology/gist/"^^xsd:anyURI ] .
