# ==========================================================================
#  W12  Certification as shapes
# ==========================================================================
#
#  FROM      The Wood and the Trees, "Certification as shapes"
#            https://www.semantechs.co.uk/articles/the-wood-and-the-trees/
#
#  CHECKS
#    Record-level rules for compartments and felling permissions, and UKWAS
#    5.0's requirement 2.11.1: at least 15% of the woodland management unit
#    managed with biodiversity as the primary objective.
#
#  HOW IT WORKS
#    fs:CompartmentShape and fs:FellingPermissionShape look at one record at a
#    time: a compartment belongs to a unit, has one area, a main species and
#    exactly one primary objective; a felling permission covers a compartment
#    and says when the land will be restocked. fs:BiodiversityShareShape needs
#    arithmetic across the whole unit, so it is a SPARQL constraint. The inner
#    SELECT DISTINCT lists each compartment once, so no area is counted twice
#    however many paths lead to it; the sums are taken over that list; the
#    share is computed as ROUND(1000 x nature / total) / 10.
#
#  DIAGRAM
#    Compartment 7    42.0 ha   Sitka spruce   timber
#    Compartment 8    30.0 ha   Sitka spruce   timber
#    Compartment 9     9.5 ha   Scots pine     biodiversity
#    Compartment 10    3.0 ha   downy birch    biodiversity
#                     84.5 ha                  12.5 ha = 14.8%   < 15%  -> violation
#
#    FP-2026-0412   covers Compartment 7   restock by 2029-03-31
#    FP-2026-0413   covers Compartment 8   restock by ?            -> violation
#
#  WHAT TO TAKE AWAY
#    - Some rules look at one record; some need the whole. The first kind can
#      run on every change, the second at audit. The article's HOLOS note is
#      about exactly this split.
#    - Counting each thing once is a modelling decision (one primary objective
#      per compartment) checked by one shape and relied on by another.
#
#  TRY IT
#    In the data tab, change Compartment 10's area from 3.0 to 4.0 ha and
#    validate again. The unit reaches 15.8%, and only the restocking date is
#    left: one violation.
#
#  DATA      glenmeadhanach-forest.ttl
#  LOAD IT   https://semantechs.co.uk/turtle-editor-viewer/?dot=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F04-the-wood-and-the-trees%2Fglenmeadhanach-forest.ttl&shapes=https%3A%2F%2Fwww.semantechs.co.uk%2Farticles%2Fshow-your-working%2Fdemos%2F04-the-wood-and-the-trees%2Fw12-certification-as-shapes.ttl
#  SPEC      SHACL 5 SPARQL-based Constraints
#            https://www.w3.org/TR/shacl/#sparql-constraints
#  REPORTS   does not conform -- 2 violations, 0 warnings, 0 info; 9 shapes
# ==========================================================================

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

fs:CompartmentShape a sh:NodeShape ;
    sh:targetClass fs:Compartment ;
    sh:property [ sh:path gist:isPartOf ; sh:minCount 1 ;
                  sh:message "A compartment must belong to a woodland management unit" ] ;
    sh:property [ sh:path fs:areaHa ; sh:minCount 1 ; sh:maxCount 1 ;
                  sh:datatype xsd:decimal ; sh:minExclusive 0 ;
                  sh:message "A compartment must have one area, in hectares" ] ;
    sh:property [ sh:path fs:mainSpecies ; sh:minCount 1 ;
                  sh:message "A compartment must record its main species" ] ;
    sh:property [ sh:path fs:primaryObjective ; sh:minCount 1 ; sh:maxCount 1 ;
                  sh:message "A compartment must have exactly one primary objective" ] .

fs:FellingPermissionShape a sh:NodeShape ;
    sh:targetClass fs:FellingPermission ;
    sh:property [ sh:path fs:covers ; sh:class fs:Compartment ; sh:minCount 1 ] ;
    sh:property [ sh:path fs:restockBy ; sh:datatype xsd:date ; sh:minCount 1 ;
                  sh:message "A felling permission must say when the land will be restocked" ] .

# UKWAS 5.0, 2.11.1: at least 15% of the woodland management unit managed with
# biodiversity as the primary objective. Each compartment is counted once, because
# each has exactly one primary objective (checked above) and is summed once below.
fs:BiodiversityShareShape a sh:NodeShape ;
    sh:targetClass fs:WoodlandManagementUnit ;
    sh:sparql [
        a sh:SPARQLConstraint ;
        sh:prefixes fs:prefixes ;
        sh:message "Less than 15% of the unit is managed with biodiversity as the primary objective ({?share}%)" ;
        sh:select """
            SELECT $this ?share WHERE {
                {
                    SELECT $this (SUM(?area) AS ?total)
                                 (SUM(IF(?objective = fs:Biodiversity, ?area, 0)) AS ?nature)
                    WHERE {
                        SELECT DISTINCT $this ?compartment ?area ?objective WHERE {
                            ?compartment gist:isPartOf $this ;
                                         fs:areaHa ?area ;
                                         fs:primaryObjective ?objective .
                        }
                    }
                    GROUP BY $this
                }
                BIND (ROUND(1000 * ?nature / ?total) / 10 AS ?share)
                FILTER (?nature < 0.15 * ?total)
            }
        """ ;
    ] .

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