# ==========================================================================
#  W19  Peaks as shapes
# ==========================================================================
#
#  FROM      Ebb and Flow, "Peaks as shapes"
#            https://www.semantechs.co.uk/articles/ebb-and-flow/
#
#  CHECKS
#    Every figure says what it measures, in a unit that can measure it, and
#    where it came from; two sources agree on a plant's capacity to within a
#    tenth; a plant's load stays below 80% of its capacity; a region's busiest
#    month has no more than twice the guest nights of its average month; a
#    digester's feed stays within 30% of its average month.
#
#  HOW IT WORKS
#    ce:FigureShape checks each magnitude against gist's reference data: the
#    unit must belong to a unit group that the aspect names, so tonnes cannot
#    count people. The other four are SPARQL constraints, with every
#    comparison multiplied out into whole numbers -- 10 x (high - low) > low
#    rather than (high - low) / low > 0.1 -- so that no engine has to divide
#    long decimals. Seasonality is a warning, because seasons are not against
#    the law.
#
#  DIAGRAM
#    Dingle   capacity 12,000 (2016 report) vs 8,600 (2022 return)        -> violation
#    Dingle   load 10,608 of 12,000 = 88% (2016 report)                   -> violation
#    Southern region 2.31 x, Northern and Western 2.49 x the average month -> 2 warnings
#    Plan A   food waste alone: six months outside 30% of the average     -> 6 violations
#    Plan B   food waste and slurry: within range every month             ok
#
#  WHAT TO TAKE AWAY
#    - Units are data. A unit group in the reference data turns "is this the
#      right kind of unit?" into a join.
#    - Integer arithmetic is a portability choice: the same shapes give the
#      same ten results in the SHACL engine and in HOLOS.
#
#  TRY IT
#    In the data tab, take the slurry out of plan B (its ce:feedstock becomes
#    food waste alone) and validate again. Plan B now fails in the same six
#    months as plan A: fourteen violations.
#
#  DATA      dingle-year.ttl
#  LOAD IT   https://semantechs.co.uk/turtle-editor-viewer/?dot=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F08-ebb-and-flow%2Fdingle-year.ttl&shapes=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F08-ebb-and-flow%2Fw19-peaks-as-shapes.ttl
#  SPEC      SHACL 5 SPARQL-based Constraints
#            https://www.w3.org/TR/shacl/#sparql-constraints
#  REPORTS   does not conform -- 8 violations, 2 warnings, 0 info; 8 shapes
# ==========================================================================

@prefix ce:    <https://example.org/circular/> .
@prefix gist:  <https://w3id.org/semanticarts/ns/ontology/gist/> .
@prefix gistd: <https://w3id.org/semanticarts/ns/data/gist/> .
@prefix rdfs:  <http://www.w3.org/2000/01/rdf-schema#> .
@prefix dct:   <http://purl.org/dc/terms/> .
@prefix sh:    <http://www.w3.org/ns/shacl#> .
@prefix xsd:   <http://www.w3.org/2001/XMLSchema#> .

ce:FigureShape a sh:NodeShape ;
    sh:targetClass gist:Magnitude ;
    sh:property [ sh:path gist:hasAspect ; sh:minCount 1 ; sh:message "A figure must say what it measures" ] ;
    sh:property [ sh:path gist:numericValue ; sh:minCount 1 ; sh:maxCount 1 ; sh:message "A figure must have one value" ] ;
    sh:property [ sh:path gist:hasUnitOfMeasure ; sh:minCount 1 ; sh:message "A figure must give its unit" ] ;
    sh:property [ sh:path dct:source ; sh:minCount 1 ; sh:message "A figure must say where it came from" ] ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes ce:prefixes ;
        sh:message "The unit {?unit} cannot measure {?aspect}" ;
        sh:select """
            SELECT $this ?unit ?aspect WHERE {
                $this gist:hasAspect ?aspect ; gist:hasUnitOfMeasure ?unit .
                FILTER NOT EXISTS { ?aspect gist:hasUnitGroup ?group . ?unit gist:isMemberOf ?group }
            }
        """ ;
    ] ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes ce:prefixes ;
        sh:message "A load must say how it was measured" ;
        sh:select """
            SELECT $this WHERE {
                $this gist:hasAspect ce:_Aspect_organic_load .
                FILTER NOT EXISTS { $this ce:basis ?basis }
            }
        """ ;
    ] .

ce:PlantShape a sh:NodeShape ;
    sh:targetClass ce:TreatmentPlant ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes ce:prefixes ;
        sh:message "Capacity is {?high} p.e. according to {?sourceHigh}, but {?low} p.e. according to {?sourceLow}" ;
        sh:select """
            SELECT $this ?high ?sourceHigh ?low ?sourceLow WHERE {
                $this gist:hasMagnitude ?m1, ?m2 .
                ?m1 gist:hasAspect ce:_Aspect_organic_treatment_capacity ; gist:numericValue ?high ; dct:source ?s1 .
                ?m2 gist:hasAspect ce:_Aspect_organic_treatment_capacity ; gist:numericValue ?low ; dct:source ?s2 .
                ?s1 rdfs:label ?sourceHigh .
                ?s2 rdfs:label ?sourceLow .
                FILTER (?s1 != ?s2 && ?high > ?low && 10 * (?high - ?low) > ?low)
            }
        """ ;
    ] ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes ce:prefixes ;
        sh:message "Load is {?percent}% of capacity according to {?source}; the limit is 80%" ;
        sh:select """
            SELECT $this ?percent ?source WHERE {
                $this gist:hasMagnitude ?c, ?l .
                ?c gist:hasAspect ce:_Aspect_organic_treatment_capacity ; gist:numericValue ?capacity ; dct:source ?s .
                ?l gist:hasAspect ce:_Aspect_organic_load ; gist:numericValue ?load ; dct:source ?s .
                ?s rdfs:label ?source .
                FILTER (10 * ?load > 8 * ?capacity)
                BIND (ROUND(100 * ?load / ?capacity) AS ?percent)
            }
        """ ;
    ] .

ce:SeasonalityShape a sh:NodeShape ;
    sh:targetClass ce:Region ;
    sh:severity sh:Warning ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes ce:prefixes ;
        sh:message "In {?year} the busiest month had {?ratio} times the guest nights of the average month" ;
        sh:select """
            SELECT $this ?year (ROUND(100 * MAX(?n) * COUNT(?n) / SUM(?n)) / 100 AS ?ratio) WHERE {
                $this gist:hasMagnitude ?m .
                ?m gist:hasAspect ce:_Aspect_guest_nights ; gist:numericValue ?n ; ce:month ?month .
                BIND (SUBSTR(STR(?month), 1, 4) AS ?year)
            }
            GROUP BY $this ?year
            HAVING (MAX(?n) * COUNT(?n) > 2 * SUM(?n))
        """ ;
    ] .

ce:DigesterShape a sh:NodeShape ;
    sh:targetClass ce:DigesterPlan ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes ce:prefixes ;
        sh:message "Month {?month} brings {?tonnes} tonnes against an average month of {?average}" ;
        sh:select """
            SELECT $this ?month ?tonnes ?average WHERE {
                {
                    SELECT $this ?month (SUM(?t) AS ?tonnes) WHERE {
                        $this ce:feedstock ?f . ?f gist:hasMagnitude ?e .
                        ?e gist:hasAspect gistd:_Aspect_mass ; ce:month ?month ; gist:numericValue ?t .
                    }
                    GROUP BY $this ?month
                }
                {
                    SELECT $this (SUM(?t) AS ?year) WHERE {
                        $this ce:feedstock ?f . ?f gist:hasMagnitude ?e .
                        ?e gist:hasAspect gistd:_Aspect_mass ; gist:numericValue ?t .
                    }
                    GROUP BY $this
                }
                FILTER (120 * ?tonnes > 13 * ?year || 120 * ?tonnes < 7 * ?year)
                BIND (ROUND(?year / 12) AS ?average)
            }
        """ ;
    ] .

ce:prefixes
    sh:declare [ sh:prefix "ce" ; sh:namespace "https://example.org/circular/"^^xsd:anyURI ] ;
    sh:declare [ sh:prefix "gist" ; sh:namespace "https://w3id.org/semanticarts/ns/ontology/gist/"^^xsd:anyURI ] ;
    sh:declare [ sh:prefix "gistd" ; sh:namespace "https://w3id.org/semanticarts/ns/data/gist/"^^xsd:anyURI ] ;
    sh:declare [ sh:prefix "rdfs" ; sh:namespace "http://www.w3.org/2000/01/rdf-schema#"^^xsd:anyURI ] ;
    sh:declare [ sh:prefix "dct" ; sh:namespace "http://purl.org/dc/terms/"^^xsd:anyURI ] .
