# ==========================================================================
#  W06  Inspecting the records
# ==========================================================================
#
#  FROM      Who Owns the Glen?, "Inspecting the records"
#            https://www.semantechs.co.uk/articles/who-owns-the-glen/
#
#  CHECKS
#    Four of the article's checks. Every title must have a proprietor.
#    Every parcel must have a boundary and an area. A holding's stated area
#    should be roughly the sum of its parcels. Two sole owners of the same
#    title cannot overlap in time.
#
#  HOW IT WORKS
#    land:TitleShape uses an inverse path: a proprietorship points at its
#    title, so "a title has a proprietor" is [ sh:inversePath land:title ]
#    with sh:minCount 1. land:ParcelShape is plain Core. The other two are
#    SPARQL constraints. land:HoldingAreaShape sums the areas of the
#    parcels the holding's titles cover and warns when the stated area is
#    more than 5% away from the sum; the arithmetic is kept to integers
#    (20 x difference > stated), which every engine does exactly.
#    land:SoleOwnerShape looks for two sole proprietorships of one title
#    where each starts before the other ends, treating a missing end date
#    as "still the owner". The dates compare as xsd:date values.
#
#  DIAGRAM
#       TitleQED00007    <-- land:title -- (nothing)                      -> violation
#       Parcel21         no geo:hasGeometry                               -> violation
#       Balnacraig       stated 1,800 ha; parcels 900 + 620 = 1,520       -> warning (18%)
#       TitleQED00004    Lochan Ltd       2010-04-01 .. 2024-05-01
#                        Strathbeag Sporting 2024-04-01 ..                 -> violation (a month)
#
#  WHAT TO TAKE AWAY
#    - An inverse path checks a relationship from the other end, so the
#      data can be modelled the natural way round.
#    - "Roughly" is a warning, not a violation. Severity is how a shape
#      says how sure it is.
#    - The missing proprietor is a gap in the records, not proof the land
#      is ownerless: it may simply not be in the Land Register yet. The
#      message says so.
#
#  TRY IT
#    In the data tab, change Balnacraig's stated area from 1800 to 1540
#    and validate again. The warning goes; the three violations stay.
#
#  DATA      glen-titles.ttl
#  LOAD IT   https://semantechs.co.uk/turtle-editor-viewer/?dot=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F02-who-owns-the-glen%2Fglen-titles.ttl&shapes=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F02-who-owns-the-glen%2Fw06-inspecting-the-records.ttl
#  SPEC      SHACL 2.3.1.4 Inverse Paths; 5 SPARQL-based Constraints
#            https://www.w3.org/TR/shacl/#property-path-inverse
#  REPORTS   does not conform -- 3 violations, 1 warnings, 0 info; 8 shapes
# ==========================================================================

@prefix land: <https://example.org/land/> .
@prefix sh:   <http://www.w3.org/ns/shacl#> .
@prefix owl:  <http://www.w3.org/2002/07/owl#> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .
@prefix geo:  <http://www.opengis.net/ont/geosparql#> .

land:prefixes
    a  owl:Ontology ;
    sh:declare [ sh:prefix "land" ; sh:namespace "https://example.org/land/"^^xsd:anyURI ] ;
    sh:declare [ sh:prefix "rdfs" ; sh:namespace "http://www.w3.org/2000/01/rdf-schema#"^^xsd:anyURI ] .

land:TitleShape
    a              sh:NodeShape ;
    sh:targetClass land:Title ;
    sh:property [
        sh:path     [ sh:inversePath land:title ] ;
        sh:minCount 1 ;
        sh:message  "No proprietor is recorded for this title. It may not be in the Land Register yet; that is not the same as having no owner." ;
    ] .

land:ParcelShape
    a              sh:NodeShape ;
    sh:targetClass land:Parcel ;
    sh:property [ sh:path geo:hasGeometry ; sh:minCount 1 ; sh:message "Every parcel must have a boundary." ] ;
    sh:property [ sh:path land:areaHa ;     sh:minCount 1 ; sh:message "Every parcel must have an area." ] .

land:HoldingAreaShape
    a              sh:NodeShape ;
    sh:targetClass land:Holding ;
    sh:sparql [
        sh:prefixes  land:prefixes ;
        sh:severity  sh:Warning ;
        sh:message   "{?name} is stated as {?stated} ha, but its parcels add up to {?sum} ha." ;
        sh:select    """
            SELECT $this ?name ?stated ?sum WHERE {
                {
                    SELECT $this (SUM(?a) AS ?sum) WHERE {
                        SELECT DISTINCT $this ?parcel ?a WHERE {
                            $this land:includesTitle ?t . ?t land:covers ?parcel . ?parcel land:areaHa ?a .
                        }
                    }
                    GROUP BY $this
                }
                $this land:statedAreaHa ?stated ; rdfs:label ?name .
                FILTER (20 * ABS(?stated - ?sum) > ?stated)
            }
        """ ;
    ] .

land:SoleOwnerShape
    a              sh:NodeShape ;
    sh:targetClass land:Title ;
    sh:sparql [
        sh:prefixes  land:prefixes ;
        sh:message   "Title {?number} has two sole proprietors at once: {?first} and {?second}." ;
        sh:select    """
            SELECT $this ?number ?first ?second WHERE {
                ?p1 land:title $this ; land:sole true ; land:proprietor ?o1 ; land:from ?f1 .
                ?p2 land:title $this ; land:sole true ; land:proprietor ?o2 ; land:from ?f2 .
                OPTIONAL { ?p1 land:until ?u1 }
                OPTIONAL { ?p2 land:until ?u2 }
                FILTER (STR(?p1) < STR(?p2))
                FILTER ((!BOUND(?u2) || ?f1 < ?u2) && (!BOUND(?u1) || ?f2 < ?u1))
                $this land:titleNumber ?number .
                ?o1 rdfs:label ?first . ?o2 rdfs:label ?second .
            }
        """ ;
    ] .
