From 0306b2ba2646e795b7547ed46990c4dec0e9244a Mon Sep 17 00:00:00 2001 From: rob-metalinkage Date: Fri, 23 May 2025 18:03:48 +1000 Subject: [PATCH 1/4] moved examples out of band for now and added test case for bug --- .../tests/times-phenomenon-interval.jsonld | 35 +++++++++++++++++++ .../bblock.json | 0 .../closure.ttl | 0 .../description.md | 0 .../examples.yaml | 4 --- 5 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 _sources/properties/observation/tests/times-phenomenon-interval.jsonld rename {_sources/properties/spec-examples => spec-examples}/bblock.json (100%) rename {_sources/properties/spec-examples => spec-examples}/closure.ttl (100%) rename {_sources/properties/spec-examples => spec-examples}/description.md (100%) rename {_sources/properties/spec-examples => spec-examples}/examples.yaml (98%) diff --git a/_sources/properties/observation/tests/times-phenomenon-interval.jsonld b/_sources/properties/observation/tests/times-phenomenon-interval.jsonld new file mode 100644 index 00000000..de68a311 --- /dev/null +++ b/_sources/properties/observation/tests/times-phenomenon-interval.jsonld @@ -0,0 +1,35 @@ +{ + "@context": { + "hasResult": "http://www.w3.org/ns/sosa/hasResult", + "hasSimpleResult": "http://www.w3.org/ns/sosa/hasSimpleResult", + "resultTime": "http://www.w3.org/ns/sosa/resultTime", + "phenomenonTime": "http://www.w3.org/ns/sosa/phenomenonTime", + "hasFeatureOfInterest": "http://www.w3.org/ns/sosa/hasFeatureOfInterest", + "observedProperty": "http://www.w3.org/ns/sosa/observedProperty", + "usedProcedure": "http://www.w3.org/ns/sosa/usedProcedure", + "madeBySensor": "http://www.w3.org/ns/sosa/madeBySensor" + }, + "hasFeatureOfInterest": { + "id": "http://something.org/1" + }, + "observedProperty": "something", + "resultTime": "2016-05-04T02:27:02.0Z", + "phenomenonTime": { "start": "2016-05-04T02:27:02.0Z", "end": "2016-05-04T03:33:33.0Z" }, + "hasResult": { + "@context": { + "resultschema": "http//example.org/resultschema/", + "a": "resultschema:a", + "b": { + "@id": "resultschema:b", + "@context": { + "b1": "resultschema:b1", + "b2": "resultschema:b2" + } + } + }, + "a": -8150858, + "b": false + }, + "hasSimpleResult": "frogginess", + "madeBySensor": "ea est culpa esse" +} \ No newline at end of file diff --git a/_sources/properties/spec-examples/bblock.json b/spec-examples/bblock.json similarity index 100% rename from _sources/properties/spec-examples/bblock.json rename to spec-examples/bblock.json diff --git a/_sources/properties/spec-examples/closure.ttl b/spec-examples/closure.ttl similarity index 100% rename from _sources/properties/spec-examples/closure.ttl rename to spec-examples/closure.ttl diff --git a/_sources/properties/spec-examples/description.md b/spec-examples/description.md similarity index 100% rename from _sources/properties/spec-examples/description.md rename to spec-examples/description.md diff --git a/_sources/properties/spec-examples/examples.yaml b/spec-examples/examples.yaml similarity index 98% rename from _sources/properties/spec-examples/examples.yaml rename to spec-examples/examples.yaml index d8aa078e..beb75a4c 100644 --- a/_sources/properties/spec-examples/examples.yaml +++ b/spec-examples/examples.yaml @@ -10,10 +10,6 @@ prefixes: sosa: http://www.w3.org/ns/sosa/ ssn-system: http://www.w3.org/ns/ssn/systems/ examples: - - title: Example ice-core.ttl - snippets: - - language: ttl - ref: https://w3c.github.io/sdw-sosa-ssn/ssn/rdf/examples/ice-core.ttl - title: Example 2017ex15.ttl snippets: - language: ttl From b61650a558f26ace6f0067d7fb7ab7b8c83348d5 Mon Sep 17 00:00:00 2001 From: rob-metalinkage Date: Fri, 23 May 2025 18:08:43 +1000 Subject: [PATCH 2/4] tests for multiple times --- .../bblocks-config-checkpoint.yaml | 5 + README.md.backup | 100 +++++ .../.ipynb_checkpoints/bblock-checkpoint.json | 29 ++ .../observationCollection/example.json | 23 ++ .../observationCollection/schema.json | 19 + .../times-multipleoptions-present.jsonld | 35 ++ .../tests/times-present-fail.jsonld | 33 ++ _superbblock/description.md.backup | 7 + .../register-checkpoint.json | 363 ++++++++++++++++++ 9 files changed, 614 insertions(+) create mode 100644 .ipynb_checkpoints/bblocks-config-checkpoint.yaml create mode 100644 README.md.backup create mode 100644 _sources/features/observation/.ipynb_checkpoints/bblock-checkpoint.json create mode 100644 _sources/features/observationCollection/example.json create mode 100644 _sources/features/observationCollection/schema.json create mode 100644 _sources/properties/observation/tests/times-multipleoptions-present.jsonld create mode 100644 _sources/properties/observation/tests/times-present-fail.jsonld create mode 100644 _superbblock/description.md.backup create mode 100644 build/.ipynb_checkpoints/register-checkpoint.json diff --git a/.ipynb_checkpoints/bblocks-config-checkpoint.yaml b/.ipynb_checkpoints/bblocks-config-checkpoint.yaml new file mode 100644 index 00000000..14845400 --- /dev/null +++ b/.ipynb_checkpoints/bblocks-config-checkpoint.yaml @@ -0,0 +1,5 @@ +identifier-prefix: ogc.unstable.sosa. + +schema-mapping: + default: https://opengeospatial.github.io/bblocks/annotated-schemas/ + diff --git a/README.md.backup b/README.md.backup new file mode 100644 index 00000000..ffe65e8a --- /dev/null +++ b/README.md.backup @@ -0,0 +1,100 @@ +# OGC Building Blocks for SOSA + +The SOSA ([Sensor, Observation, Sample, and Actuator](https://www.w3.org/TR/vocab-ssn/)) ontology is a realisation of the + Observations, Measurements and Sampling (OMS) Conceptual model. This repository defines: + * JSON schema encoding for each feature type (class) defined by SOSA, compatible with the OGC API Features using the FG-JSON extension to GeoJSON + * JSON-LD contexts for each class to link schema elements to relevant class and properties defined by SOSA + * examples that can be used in documentation + * validation resources for this schema and the JSON-LD RDF binding + + This encoding is defined using the [OGC Building Blocks template](https://opengeospatial.github.io/bblock-template) template, and hence can be combined with other Building Blocks to implement more complete domain models with interoperable encodings and extensible APIs. + +## Status and Compatibility + +This building block is __under construction__ and is undertaken in the context of the update of SOSA to align with OMS V3. + +It is assumed that this will be backwards compatible with the last published SOSA version https://www.w3.org/TR/2017/REC-vocab-ssn-20171019/. Any changes to this status will be noted in this section. + +## General Building block repository structure + + +The `build/` directory contains the **_reusable assets_** for implementing this building block, in full or part, and the rest of the repository contain *sources* to build these assets. *Sources* minimise redundant information and preserve original forms of inputs, such as externally published schemas etc. This allow these to be updated safely, and also allows for alternative forms of original source material to be used whilst preserving uniformity of the reusable assets. + +![Usage](usage.png) + + +* The `build/` directory should never be edited +* Only resources in the `build/` directory should be used by applications + +### Ready to use components + +- `build/`: the available versions of the building block ready for reuse + +Note that the these components will be consistently structured for a given type of building block, and the editable components may vary according to the source material used to derive the building block, and therefore cannot be directly referenced. + +### Editable components + +- `features/`: schemas for the feature types defined by this bb (which is a "super-bb" containing at least oneOf these defined features) +- `datatypes/`: reusable schemas for (potentially complex) datatypes defined by this bb +- `aspects/`: groups of properties that may be included in feature types (equivalent to attribute groups in XML schema) +- `assets/`: Documentation assets (e.g. images) directory. See [Assets](#assets) below. + + +### Individual building block structure + +After building each of the building blocks (including any top-level composite building block) contains the following files: + +- `bblock.json`: Contains the metadata for the building block. +- `description.md`: Human-readable, Markdown document with the description of this building block. +- `examples.yaml`: A list of examples for this building block. See [Examples](#examples) below. +- `schema.yaml`: JSON schema using YAML syntax for this building block, if any. See [JSON schema](#json-schema) below. +- `schema.json`: equivalent JSON schema using JSON syntax. + +Note: some these files may not be present in the **source* - for example a description could be extracted from the model referenced in the schema or bblock.json metadata. + +Note: the top level building block schemas may be generated from the components automatically. + + +## Building Block identifiers + +These are automatically generated in the form: + +``` + +``` + +where: + +- `identifier-prefix` is read from `bblocks-config.yaml`. This will initially be a placeholder value, + but should have an official value eventually (see [How-to](#how-to)). +- `bb-path` is the dot-separated path to the building block inside the repository. + +## Examples + +Each example consists of Markdown `content` and/or a list of `snippets`. `snippets`, in turn, +have a `language` (for highlighting, language tabs in Slate, etc.) and the `code` itself. + +Each class supported by this building block has an +`examples.yaml` file. (`examples.json` may be used as an alternative.) + + +## Postprocessing overview + +*TBD: this section to be automatically inserted from the template.* + +This repository comes with a GitHub workflow that detects, validates and processes its building blocks, +so that their outputs can be tested before inclusion in the main OGC Register: + +![OGC Building Blocks processing](https://raw.githubusercontent.com/avillar/bblocks-postprocess/master/process.png) + +### Output testing + +The outputs can be generated locally by running the following (*Note: Docker must be installed locally*): + +```shell +# Process building blocks +docker run --rm --workdir /workspace -v $(pwd):/workspace ghcr.io/avillar/bblocks-postprocess +# Optional - build Slate docs +docker run --rm -v "$(pwd)/generateddocs/slate:/srv/slate/source" \ + -v "$(pwd)/generateddocs/slate-build:/srv/slate/build" slatedocs/slate build +``` \ No newline at end of file diff --git a/_sources/features/observation/.ipynb_checkpoints/bblock-checkpoint.json b/_sources/features/observation/.ipynb_checkpoints/bblock-checkpoint.json new file mode 100644 index 00000000..ced4852a --- /dev/null +++ b/_sources/features/observation/.ipynb_checkpoints/bblock-checkpoint.json @@ -0,0 +1,29 @@ +{ + "name": "SOSA Observation Feature", + "abstract": "This building blocks defines a GeoJSON feature containing a SOSA Observation", + "status": "under-development", + "dateTimeAddition": "2023-05-18T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-05-18", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + } + ], + "maturity": "development", + "scope": "unstable", + "dependsOn": [ + "ogc.unstable.sosa.properties.observation" + ], + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s" + ], + "group": "SOSA" +} diff --git a/_sources/features/observationCollection/example.json b/_sources/features/observationCollection/example.json new file mode 100644 index 00000000..ee0c5b6d --- /dev/null +++ b/_sources/features/observationCollection/example.json @@ -0,0 +1,23 @@ +{ + "$schema": "schema.json", + "@id": "c1", + "type": "Feature", + "featureType": "sosa:ObservationCollection", + "properties": { + "observedProperty": "http://dbpedia.org/ontology/population", + "resultTime": "1999", + "features": [ + { + "@id": "pop1999", + "comment": "Example of an inline membership - would entail hasMember relations", + "hasFeatureOfInterest": "https://demo.pygeoapi.io/master/collections/utah_city_locations/items/Spanish%20Fork", + "hasSimpleResult": 15555.0 + }, + { + "@id": "pop1999", + "hasFeatureOfInterest": "https://demo.pygeoapi.io/master/collections/utah_city_locations/items/Salem", + "hasSimpleResult": 3275.0 + } + ] + }, +} \ No newline at end of file diff --git a/_sources/features/observationCollection/schema.json b/_sources/features/observationCollection/schema.json new file mode 100644 index 00000000..066132cc --- /dev/null +++ b/_sources/features/observationCollection/schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "description": "SOSA Observation Feature", + "x-jsonld-context": "../../../sosa-ssn.jsonld", + "allOf": [ + { + "$ref": "https://opengeospatial.github.io/bblocks/annotated-schemas/geo/json-fg/featureCollection/schema.yaml", + "x-bblocks-ref": "bblocks://ogc.geo.json-fg.featureCollection" + }, + { + "type": "object", + "properties": { + "properties": { + "$ref": "../../properties/observationCollection/schema.yaml" + } + } + } + ] +} \ No newline at end of file diff --git a/_sources/properties/observation/tests/times-multipleoptions-present.jsonld b/_sources/properties/observation/tests/times-multipleoptions-present.jsonld new file mode 100644 index 00000000..186beb2e --- /dev/null +++ b/_sources/properties/observation/tests/times-multipleoptions-present.jsonld @@ -0,0 +1,35 @@ +{ + "@context": { + "hasResult": "http://www.w3.org/ns/sosa/hasResult", + "hasSimpleResult": "http://www.w3.org/ns/sosa/hasSimpleResult", + "resultTime": "http://www.w3.org/ns/sosa/resultTime", + "phenomenonTime": "http://www.w3.org/ns/sosa/phenomenonTime", + "hasFeatureOfInterest": "http://www.w3.org/ns/sosa/hasFeatureOfInterest", + "observedProperty": "http://www.w3.org/ns/sosa/observedProperty", + "usedProcedure": "http://www.w3.org/ns/sosa/usedProcedure", + "madeBySensor": "http://www.w3.org/ns/sosa/madeBySensor" + }, + "hasFeatureOfInterest": { + "id": "http://something.org/1" + }, + "observedProperty": "something", + "resultTime": "2016-05-04T02:27:02.0Z", + "phenomenonTime": "2016-05-04T02:27:02.0Z", + "hasResult": { + "@context": { + "resultschema": "http//example.org/resultschema/", + "a": "resultschema:a", + "b": { + "@id": "resultschema:b", + "@context": { + "b1": "resultschema:b1", + "b2": "resultschema:b2" + } + } + }, + "a": -8150858, + "b": false + }, + "hasSimpleResult": "frogginess", + "madeBySensor": "ea est culpa esse" +} \ No newline at end of file diff --git a/_sources/properties/observation/tests/times-present-fail.jsonld b/_sources/properties/observation/tests/times-present-fail.jsonld new file mode 100644 index 00000000..52481600 --- /dev/null +++ b/_sources/properties/observation/tests/times-present-fail.jsonld @@ -0,0 +1,33 @@ +{ + "@context": { + "hasResult": "http://www.w3.org/ns/sosa/hasResult", + "hasSimpleResult": "http://www.w3.org/ns/sosa/hasSimpleResult", + "resultTime": "http://www.w3.org/ns/sosa/resultTime", + "phenomenonTime": "http://www.w3.org/ns/sosa/phenomenonTime", + "hasFeatureOfInterest": "http://www.w3.org/ns/sosa/hasFeatureOfInterest", + "observedProperty": "http://www.w3.org/ns/sosa/observedProperty", + "usedProcedure": "http://www.w3.org/ns/sosa/usedProcedure", + "madeBySensor": "http://www.w3.org/ns/sosa/madeBySensor" + }, + "hasFeatureOfInterest": { + "id": "http://something.org/1" + }, + "observedProperty": "something", + "hasResult": { + "@context": { + "resultschema": "http//example.org/resultschema/", + "a": "resultschema:a", + "b": { + "@id": "resultschema:b", + "@context": { + "b1": "resultschema:b1", + "b2": "resultschema:b2" + } + } + }, + "a": -8150858, + "b": false + }, + "hasSimpleResult": "frogginess", + "madeBySensor": "ea est culpa esse" +} \ No newline at end of file diff --git a/_superbblock/description.md.backup b/_superbblock/description.md.backup new file mode 100644 index 00000000..fcaad04f --- /dev/null +++ b/_superbblock/description.md.backup @@ -0,0 +1,7 @@ +Building Blocks for implementing the core classes of the []Observations and Measurements model] + +Each class is implemented using a schema is tied to the equivalent semantic description using the SOSA (Sensor, Observation, Sample, and Actuator) ontology. + +An [aggregate schema](schema.yaml) is provided allowing any of these elements to be combined in a single payload, or each class may be used independently using the relevant schema. + +TBD: Convenience API paths may be defined to support traversal of relationships - such as inverse relationships `hasResult/isResultOf` , `hasSample/isSampleOf` etc. where only one direction is present in the data and the inverse is not otherwise accessible. diff --git a/build/.ipynb_checkpoints/register-checkpoint.json b/build/.ipynb_checkpoints/register-checkpoint.json new file mode 100644 index 00000000..f5ba4f72 --- /dev/null +++ b/build/.ipynb_checkpoints/register-checkpoint.json @@ -0,0 +1,363 @@ +[ + { + "name": "Example SOSA Vector Observation", + "abstract": "This building block defines an example SOSA Vector Observation", + "status": "notAccepted", + "dateTimeAddition": "2023-05-19T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-05-19", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + } + ], + "maturity": "development", + "scope": "unstable", + "dependsOn": [ + "ogc.unstable.sosa.properties.observation" + ], + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s", + "examples" + ], + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa.examples.vectorObservation", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/examples/vectorObservation/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/examples/vectorObservation/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/examples/vectorObservation/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/examples/vectorObservation/", + "validationPassed": true, + "testOutputs": "https://github.com/opengeospatial/ogcapi-sosa/blob/master/build/tests/unstable/sosa/examples/vectorObservation/", + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/examples/vectorObservation/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/examples/vectorObservation/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/examples/vectorObservation/" + } + } + }, + { + "name": "Example SOSA Vector Observation Feature", + "abstract": "This building block defines an example SOSA Observation Feature for a Vector Observation", + "status": "notAccepted", + "dateTimeAddition": "2023-05-19T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-05-19", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + } + ], + "maturity": "development", + "scope": "unstable", + "dependsOn": [ + "ogc.unstable.sosa.properties.observation" + ], + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s", + "examples" + ], + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa.examples.vectorObservationFeature", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/examples/vectorObservationFeature/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/examples/vectorObservationFeature/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/examples/vectorObservationFeature/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/examples/vectorObservationFeature/", + "validationPassed": true, + "testOutputs": "https://github.com/opengeospatial/ogcapi-sosa/blob/master/build/tests/unstable/sosa/examples/vectorObservationFeature/", + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/examples/vectorObservationFeature/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/examples/vectorObservationFeature/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/examples/vectorObservationFeature/" + } + } + }, + { + "name": "SOSA Observation Feature", + "abstract": "This building blocks defines a GeoJSON feature containing a SOSA Observation", + "status": "under-development", + "dateTimeAddition": "2023-05-18T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-05-18", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + } + ], + "maturity": "development", + "scope": "unstable", + "dependsOn": [ + "ogc.unstable.sosa.properties.observation" + ], + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s" + ], + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa.features.observation", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/features/observation/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/features/observation/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/features/observation/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/features/observation/", + "validationPassed": true, + "testOutputs": "https://github.com/opengeospatial/ogcapi-sosa/blob/master/build/tests/unstable/sosa/features/observation/", + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/features/observation/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/features/observation/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/features/observation/" + } + } + }, + { + "name": "SOSA ObservationCollection Feature", + "abstract": "This building blocks defines an ObservationCollection Feature according to the SOSA/SSN v1.1 specification.", + "status": "experimental", + "dateTimeAddition": "2023-04-13T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-04-28", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + }, + { + "title": "Extensions to the Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn-ext/" + } + ], + "maturity": "development", + "scope": "unstable", + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s" + ], + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa.features.observationCollection", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/features/observationCollection/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/features/observationCollection/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/features/observationCollection/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/features/observationCollection/", + "validationPassed": false, + "testOutputs": "https://github.com/opengeospatial/ogcapi-sosa/blob/master/build/tests/unstable/sosa/features/observationCollection/", + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/features/observationCollection/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/features/observationCollection/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/features/observationCollection/" + } + } + }, + { + "name": "SOSA Observation", + "abstract": "This building block defines the set of properties for an observation according to the SOSA/SSN specification. These properties may be directly included into a root element of a JSON object or used in the properties container of a GeoJSON feature.", + "status": "under-development", + "dateTimeAddition": "2023-04-13T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-04-13", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + } + ], + "maturity": "development", + "scope": "unstable", + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s" + ], + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa.properties.observation", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/properties/observation/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/properties/observation/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/properties/observation/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/properties/observation/", + "validationPassed": true, + "testOutputs": "https://github.com/opengeospatial/ogcapi-sosa/blob/master/build/tests/unstable/sosa/properties/observation/", + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/properties/observation/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/properties/observation/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/properties/observation/" + } + } + }, + { + "name": "SOSA ObservationCollection", + "abstract": "This building blocks defines an ObservationCollection according to the SOSA/SSN v1.1 specification.", + "status": "experimental", + "dateTimeAddition": "2023-04-13T00:00:00Z", + "itemClass": "schema", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-04-28", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + }, + { + "title": "Extensions to the Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn-ext/" + } + ], + "maturity": "development", + "scope": "unstable", + "tags": [ + "sosa", + "ssn", + "observations", + "o&m", + "o&m&s" + ], + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa.properties.observationCollection", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/properties/observationCollection/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/properties/observationCollection/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/properties/observationCollection/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/properties/observationCollection/", + "validationPassed": true, + "testOutputs": "https://github.com/opengeospatial/ogcapi-sosa/blob/master/build/tests/unstable/sosa/properties/observationCollection/", + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/properties/observationCollection/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/properties/observationCollection/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/properties/observationCollection/" + } + } + }, + { + "name": "Sensor, Observation, Sample, and Actuator (SOSA)", + "abstract": "The SOSA (Sensor, Observation, Sample, and Actuator) ontology is a realisation of the Observations, Measurements and Sampling (OMS) Conceptual model", + "status": "under-development", + "dateTimeAddition": "2023-04-13T00:00:00Z", + "itemClass": "api", + "register": "ogc-building-block-register", + "version": "1.0", + "dateOfLastChange": "2023-04-13", + "sources": [ + { + "title": "Semantic Sensor Network Ontology", + "link": "https://www.w3.org/TR/vocab-ssn/" + } + ], + "maturity": "development", + "scope": "unstable", + "tags": [ + "sosa", + "ssn", + "o&m", + "o&m&s" + ], + "superBBlock": true, + "group": "SOSA", + "itemIdentifier": "ogc.unstable.sosa", + "schema": { + "application/yaml": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/schema.yaml", + "application/json": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/schema.json" + }, + "ldContext": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/annotated/unstable/sosa/context.jsonld", + "sourceFiles": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/_sources/", + "validationPassed": true, + "documentation": { + "json-full": { + "mediatype": "application/json", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/json-full/unstable/sosa/index.json" + }, + "markdown": { + "mediatype": "text/markdown", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/markdown/unstable/sosa/index.md" + }, + "slate": { + "mediatype": "text/html", + "url": "https://raw.githubusercontent.com/opengeospatial/ogcapi-sosa/master/build/generateddocs/slate-build/unstable/sosa/" + } + } + } +] \ No newline at end of file From 5f29a234a6b969f6158cba2287fb0f22d0dc3028 Mon Sep 17 00:00:00 2001 From: Alejandro Villar Date: Fri, 23 May 2025 13:10:20 +0200 Subject: [PATCH 3/4] Remove multiple result predicates --- .../observation/tests/times-multipleoptions-present.jsonld | 1 - .../observation/tests/times-phenomenon-interval.jsonld | 1 - 2 files changed, 2 deletions(-) diff --git a/_sources/properties/observation/tests/times-multipleoptions-present.jsonld b/_sources/properties/observation/tests/times-multipleoptions-present.jsonld index 186beb2e..36e3e315 100644 --- a/_sources/properties/observation/tests/times-multipleoptions-present.jsonld +++ b/_sources/properties/observation/tests/times-multipleoptions-present.jsonld @@ -30,6 +30,5 @@ "a": -8150858, "b": false }, - "hasSimpleResult": "frogginess", "madeBySensor": "ea est culpa esse" } \ No newline at end of file diff --git a/_sources/properties/observation/tests/times-phenomenon-interval.jsonld b/_sources/properties/observation/tests/times-phenomenon-interval.jsonld index de68a311..d9eed9ef 100644 --- a/_sources/properties/observation/tests/times-phenomenon-interval.jsonld +++ b/_sources/properties/observation/tests/times-phenomenon-interval.jsonld @@ -30,6 +30,5 @@ "a": -8150858, "b": false }, - "hasSimpleResult": "frogginess", "madeBySensor": "ea est culpa esse" } \ No newline at end of file From abf5f14331873dd5fa6c475747fc6ad8beec6307 Mon Sep 17 00:00:00 2001 From: Rob Atkinson Date: Wed, 26 Aug 2026 17:49:18 +1000 Subject: [PATCH 4/4] added nested Collection and transformer for hydrated observation linked data view --- .github/workflows/pr-check.yml | 16 + .../bblocks-config-checkpoint.yaml | 5 - .../semantic-uplift/featureType.shacl | 19 +- .../observationCollection/examples.yaml | 21 +- .../observationCollection-foi-geometry.json | 62 + .../observationCollection/schema.json | 19 - .../observationCollection/schema.yaml | 12 + .../transformers/flatten-observations.py | 126 ++ .../observationCollection/transforms.yaml | 19 + .../properties/observation-owa/examples.yaml | 17 + _sources/properties/observation/rules.shacl | 44 +- .../observationCollection/examples.yaml | 58 + .../observationCollection/schema.yaml | 31 +- build-devel.sh | 3 + build.sh | 15 +- create-clean-pr.sh | 148 ++ scripts/README.md | 6 + scripts/obs_collection_check.py | 1241 +++++++++++++++++ scripts/obs_collection_check_usage.md | 297 ++++ view.sh | 1 + 20 files changed, 2098 insertions(+), 62 deletions(-) create mode 100644 .github/workflows/pr-check.yml delete mode 100644 .ipynb_checkpoints/bblocks-config-checkpoint.yaml create mode 100644 _sources/features/observationCollection/examples/observationCollection-foi-geometry.json delete mode 100644 _sources/features/observationCollection/schema.json create mode 100644 _sources/features/observationCollection/transformers/flatten-observations.py create mode 100644 _sources/features/observationCollection/transforms.yaml create mode 100644 build-devel.sh create mode 100644 create-clean-pr.sh create mode 100644 scripts/README.md create mode 100644 scripts/obs_collection_check.py create mode 100644 scripts/obs_collection_check_usage.md diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml new file mode 100644 index 00000000..164aad6c --- /dev/null +++ b/.github/workflows/pr-check.yml @@ -0,0 +1,16 @@ +name: Validate Building Blocks PR +on: + pull_request: + +# Read-only validation: runs postprocessing against the PR to catch things +# like broken bblock dependencies before merge, but never commits, deploys, +# or pushes anything - see process-bblocks.yml for the workflow that does. +# +# NOTE: if this repo overrides items_dir/register_file/generated_docs_path/ +# annotated_path/test_outputs_path/config_file in process-bblocks.yml below, +# pass the same overrides here, or this check will run against the wrong +# paths. +jobs: + pr-check: + name: Validate PR + uses: opengeospatial/bblocks-postprocess/.github/workflows/pr-check.yml@master \ No newline at end of file diff --git a/.ipynb_checkpoints/bblocks-config-checkpoint.yaml b/.ipynb_checkpoints/bblocks-config-checkpoint.yaml deleted file mode 100644 index 14845400..00000000 --- a/.ipynb_checkpoints/bblocks-config-checkpoint.yaml +++ /dev/null @@ -1,5 +0,0 @@ -identifier-prefix: ogc.unstable.sosa. - -schema-mapping: - default: https://opengeospatial.github.io/bblocks/annotated-schemas/ - diff --git a/_sources/features/observation/semantic-uplift/featureType.shacl b/_sources/features/observation/semantic-uplift/featureType.shacl index d2e110a2..428bb0ee 100644 --- a/_sources/features/observation/semantic-uplift/featureType.shacl +++ b/_sources/features/observation/semantic-uplift/featureType.shacl @@ -14,10 +14,21 @@ sosa:madeBySensor, sosa:phenomenonType ; + # These properties may also be held in common at the ObservationCollection level + # (sosa:hasMember / geojson:features), so only infer sosa:Observation when the + # subject is not itself acting as a collection. sh:rule [ - a sh:TripleRule ; - sh:subject sh:this ; - sh:predicate rdf:type ; - sh:object sosa:Observation ; + a sh:SPARQLRule ; + sh:prefixes [ + sh:declare [ sh:prefix "sosa" ; sh:namespace "http://www.w3.org/ns/sosa/"^^ ] ; + sh:declare [ sh:prefix "geojson" ; sh:namespace "https://purl.org/geojson/vocab#"^^ ] ; + ] ; + sh:construct """ + CONSTRUCT { $this a sosa:Observation . } + WHERE { + FILTER NOT EXISTS { $this sosa:hasMember ?member . } + FILTER NOT EXISTS { $this geojson:features ?feature . } + } + """ ; ] ; . \ No newline at end of file diff --git a/_sources/features/observationCollection/examples.yaml b/_sources/features/observationCollection/examples.yaml index a7306e2c..050260ba 100644 --- a/_sources/features/observationCollection/examples.yaml +++ b/_sources/features/observationCollection/examples.yaml @@ -36,4 +36,23 @@ a skos:Concept; skos:prefLabel "Population"; . - + + +- title: Example of nested SOSA ObservationCollections with an inline Feature of Interest geometry + comment: |- + An ObservationCollection Feature's `features` array can itself contain nested + ObservationCollection Features, not just individual Observations - a + FeatureCollection cannot appear as a `features` member, so each nested + collection is a `Feature` whose members are held in `properties.hasMember` + rather than a further `features` array. Common properties are held at the + level of the collection that shares them, rather than repeated on every + member: the outer collection declares `resultTime` and an inline + `hasFeatureOfInterest` (with a sample `Point` geometry) shared by every + observation in the whole tree; each inner sub-collection declares its own + `observedProperty`, shared only by its own member observations, which in + turn carry nothing but their individual `phenomenonTime` and result. + + snippets: + - language: json + ref: examples/observationCollection-foi-geometry.json + base-uri: http://example.com/ diff --git a/_sources/features/observationCollection/examples/observationCollection-foi-geometry.json b/_sources/features/observationCollection/examples/observationCollection-foi-geometry.json new file mode 100644 index 00000000..06d02904 --- /dev/null +++ b/_sources/features/observationCollection/examples/observationCollection-foi-geometry.json @@ -0,0 +1,62 @@ +{ + "type": "FeatureCollection", + "featureType": "sosa:ObservationCollection", + "properties": { + "resultTime": "2022-05-01T22:33:44Z", + "hasFeatureOfInterest": { + "@id": "https://demo.pygeoapi.io/master/collections/utah_city_locations/items/Salem", + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [-111.6738, 40.0518] + }, + "properties": { + "name": "Salem, Utah" + } + } + }, + "features": [ + { + "@id": "temperature-collection", + "type": "Feature", + "featureType": "sosa:ObservationCollection", + "geometry": null, + "properties": { + "observedProperty": "https://example.org/properties/temperature", + "hasMember": [ + { + "@id": "obs-temp-1", + "phenomenonTime": "2022-05-01T22:33:40Z", + "hasSimpleResult": 21.4 + }, + { + "@id": "obs-temp-2", + "phenomenonTime": "2022-05-01T22:34:10Z", + "hasSimpleResult": 21.6 + } + ] + } + }, + { + "@id": "humidity-collection", + "type": "Feature", + "featureType": "sosa:ObservationCollection", + "geometry": null, + "properties": { + "observedProperty": "https://example.org/properties/humidity", + "hasMember": [ + { + "@id": "obs-hum-1", + "phenomenonTime": "2022-05-01T22:33:40Z", + "hasSimpleResult": 58.2 + }, + { + "@id": "obs-hum-2", + "phenomenonTime": "2022-05-01T22:34:10Z", + "hasSimpleResult": 57.9 + } + ] + } + } + ] +} diff --git a/_sources/features/observationCollection/schema.json b/_sources/features/observationCollection/schema.json deleted file mode 100644 index 066132cc..00000000 --- a/_sources/features/observationCollection/schema.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "description": "SOSA Observation Feature", - "x-jsonld-context": "../../../sosa-ssn.jsonld", - "allOf": [ - { - "$ref": "https://opengeospatial.github.io/bblocks/annotated-schemas/geo/json-fg/featureCollection/schema.yaml", - "x-bblocks-ref": "bblocks://ogc.geo.json-fg.featureCollection" - }, - { - "type": "object", - "properties": { - "properties": { - "$ref": "../../properties/observationCollection/schema.yaml" - } - } - } - ] -} \ No newline at end of file diff --git a/_sources/features/observationCollection/schema.yaml b/_sources/features/observationCollection/schema.yaml index c2014b00..7c4e2f7b 100644 --- a/_sources/features/observationCollection/schema.yaml +++ b/_sources/features/observationCollection/schema.yaml @@ -14,5 +14,17 @@ allOf: oneOf: # Embedded observations - $ref: ../observation/schema.yaml + # Embedded nested ObservationCollection. A FeatureCollection cannot itself + # be a `features` member (json-fg.featureCollection-lenient constrains + # `features` to Features only), so a nested collection is still a plain + # Feature - any further nesting continues via `properties.hasMember` + # (see properties/observationCollection/schema.yaml), not another + # `features` array. + - allOf: + - $ref: bblocks://ogc.geo.json-fg.feature-lenient + - type: object + properties: + properties: + $ref: ../../properties/observationCollection/schema.yaml # Ids/URIs - type: string diff --git a/_sources/features/observationCollection/transformers/flatten-observations.py b/_sources/features/observationCollection/transformers/flatten-observations.py new file mode 100644 index 00000000..92c84a4a --- /dev/null +++ b/_sources/features/observationCollection/transformers/flatten-observations.py @@ -0,0 +1,126 @@ +# Transform: flatten-observations +# +# Flattens a (possibly nested) SOSA ObservationCollection GeoJSON document into a +# plain GeoJSON FeatureCollection of Observation Features. Each output Feature's +# `properties` merges in every property inherited from its containing +# ObservationCollection(s) - the nearest collection wins on conflicting keys. If a +# Feature has no geometry of its own, one is taken from the `geometry` of its own +# `hasFeatureOfInterest`, or - failing that - from the nearest ancestor collection's +# `hasFeatureOfInterest` that carries a geometry. +# +# Executed as a bblocks `python` transform: receives `input_data` (the source JSON +# text) and must assign the result to `output_data`. + +import json + +_MISSING = object() + +_COLLECTION_MARKERS = ("ObservationCollection",) + + +def _has_collection_marker(node): + for key in ("featureType", "@type", "type"): + value = node.get(key) + if isinstance(value, str) and any(m in value for m in _COLLECTION_MARKERS): + return True + if isinstance(value, list) and any( + isinstance(v, str) and any(m in v for m in _COLLECTION_MARKERS) + for v in value + ): + return True + return False + + +def _node_kind(node): + if isinstance(node, str): + return "ref" + if isinstance(node, dict): + if "properties" in node or node.get("type") in ("Feature", "FeatureCollection"): + return "wrapped" + return "raw" + return "unknown" + + +def _own_id(node): + return node.get("@id", node.get("id")) + + +def _decompose(node): + """ + Break a member down into (own_id, own_geometry, own_properties, sub_members, + is_collection). `own_geometry` is `_MISSING` when the node carries no + `geometry` key at all (as opposed to an explicit `null`). + """ + kind = _node_kind(node) + + if kind == "ref": + # A bare IRI/CURIE reference - no embedded data, only inherited properties apply. + return node, _MISSING, {}, [], False + + if kind == "wrapped": + # A GeoJSON Feature (or FeatureCollection): SOSA properties live under `properties`, + # members under `features` and/or `properties.hasMember`. + props = node.get("properties") or {} + sub_members = list(node.get("features") or []) + list(props.get("hasMember") or []) + own_properties = {k: v for k, v in props.items() if k != "hasMember"} + own_geometry = node["geometry"] if "geometry" in node else _MISSING + is_collection = bool(sub_members) or _has_collection_marker(node) + return _own_id(node), own_geometry, own_properties, sub_members, is_collection + + if kind == "raw": + # A bare SOSA property object (no GeoJSON wrapper), as found inside `hasMember`. + sub_members = list(node.get("hasMember") or []) + own_properties = {k: v for k, v in node.items() if k not in ("hasMember", "@id", "id")} + is_collection = bool(sub_members) or _has_collection_marker(node) + return _own_id(node), _MISSING, own_properties, sub_members, is_collection + + return None, _MISSING, {}, [], False + + +def _geometry_from_foi_chain(foi_chain): + """First non-null geometry carried by a featureOfInterest object, nearest first.""" + for foi in foi_chain: + if isinstance(foi, dict): + geometry = foi.get("geometry") + if geometry is not None: + return geometry + return None + + +def _flatten(node, inherited_properties, foi_chain, output_features): + own_id, own_geometry, own_properties, sub_members, is_collection = _decompose(node) + + effective_properties = dict(inherited_properties) + effective_properties.update(own_properties) + + own_foi = own_properties.get("hasFeatureOfInterest") + current_foi_chain = ([own_foi] if own_foi is not None else []) + foi_chain + + if is_collection: + for member in sub_members: + _flatten(member, effective_properties, current_foi_chain, output_features) + return + + geometry = own_geometry + if geometry is _MISSING or geometry is None: + geometry = _geometry_from_foi_chain(current_foi_chain) + + feature = {"type": "Feature"} + if own_id is not None: + feature["@id"] = own_id + feature["geometry"] = geometry + feature["properties"] = effective_properties + output_features.append(feature) + + +_data = json.loads(input_data) + +_flattened_features = [] +_flatten(_data, {}, [], _flattened_features) + +_result = { + "type": "FeatureCollection", + "features": _flattened_features, +} + +output_data = json.dumps(_result, indent=2, ensure_ascii=False) diff --git a/_sources/features/observationCollection/transforms.yaml b/_sources/features/observationCollection/transforms.yaml new file mode 100644 index 00000000..406508da --- /dev/null +++ b/_sources/features/observationCollection/transforms.yaml @@ -0,0 +1,19 @@ +transforms: + - id: flatten-observations + description: | + Flattens a (possibly nested) SOSA ObservationCollection GeoJSON document into a + plain GeoJSON FeatureCollection of Observation Features. Each output Feature's + `properties` merges in every property inherited from its containing + ObservationCollection(s) - the nearest collection wins on conflicting keys. If a + Feature has no geometry of its own, one is taken from the `geometry` of its own + `hasFeatureOfInterest`, or - failing that - from the nearest ancestor collection's + `hasFeatureOfInterest` that carries a geometry. + type: python + inputs: + mediaTypes: + - application/json + outputs: + mediaTypes: + - mimeType: application/geo+json + defaultExtension: geojson + ref: transformers/flatten-observations.py diff --git a/_sources/properties/observation-owa/examples.yaml b/_sources/properties/observation-owa/examples.yaml index c0f07f88..e405332b 100644 --- a/_sources/properties/observation-owa/examples.yaml +++ b/_sources/properties/observation-owa/examples.yaml @@ -38,3 +38,20 @@ }, "resultTime": "2022-05-01T22:33:44Z" } + +- title: Example of SOSA observation with FoI inline + + snippets: + - language: json + code: |- + { + "hasFeatureOfInterest": { + "id": "https://demo.pygeoapi.io/master/collections/utah_city_locations/items/Spanish%20Fork", + "type": "Feature", + "geometry": null, + "properties": {} + }, + "observedProperty": "p1", + "hasSimpleResult": 33, + "resultTime": "2022-05-01T22:33:44Z" + } \ No newline at end of file diff --git a/_sources/properties/observation/rules.shacl b/_sources/properties/observation/rules.shacl index e3b4c3ab..ca8a5c2f 100644 --- a/_sources/properties/observation/rules.shacl +++ b/_sources/properties/observation/rules.shacl @@ -6,48 +6,50 @@ @prefix sosa: . @base . -<#testRequiredTime> +<#SOSA-testRequiredTime> a sh:NodeShape ; sh:targetClass sosa:Observation ; sh:targetSubjectsOf sosa:hasResult, sosa:hasSimpleResult ; - sh:message "sosa:resultTime or sosa:phenomenonTime is required, and no more than 1 of each is allowed" ; + sh:message "SOSA-testRequiredTime: sosa:time sosa:resultTime or sosa:phenomenonTime is required, at Collection or Observation" ; sh:or ( [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath [ sh:inversePath sosa:hasMember ] ] ] sosa:phenomenonTime ) ; sh:minCount 1 ; - sh:maxCount 1 ; ] [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath [ sh:inversePath + ] [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath [ sh:inversePath geojson:features ] ] ] sosa:phenomenonTime ) ; sh:minCount 1 ; - sh:maxCount 1 ; ] [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath + ] [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath [ sh:inversePath sosa:hasMember ] ] ] sosa:resultTime ) ; sh:minCount 1 ; - sh:maxCount 1 ; ] [ sh:path ( [ sh:zeroOrMorePath + ] [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath [ sh:inversePath geojson:features ] ] ] sosa:resultTime ) ; sh:minCount 1 ; - sh:maxCount 1 ; ] ) ; + ] ) ; . -<#testObservedProperty> +<#SOSA-testObservedProperty> a sh:NodeShape ; sh:targetClass sosa:Observation ; sh:targetSubjectsOf sosa:hasResult, sosa:hasSimpleResult ; - sh:message "Exactly 1 of sosa:observedProperty is required" ; + # Note observed properties may be listed in Collections + # 3. Where an individual ObservationCollection has more than one value for a property, each member Observation (direct or transitive) MUST have a value for that property that matches one of the values for the property in the collection. + sh:message "SOSA-testObservedProperty: At least 1 of sosa:observedProperty is required in Observation or parent Collection" ; sh:property [ sh:path ( [ sh:zeroOrMorePath [ sh:oneOrMorePath [ sh:alternativePath ( [ sh:inversePath geojson:features ] [ sh:inversePath sosa:hasMember ] ) ] ] ] sosa:observedProperty ) ; sh:minCount 1 ; - sh:maxCount 1 ; ] ; + ] ; . -<#testFeatureOfInterest> +<#SOSA-testFeatureOfInterestPresent> a sh:NodeShape ; sh:targetClass sosa:Observation ; sh:targetSubjectsOf sosa:hasResult, sosa:hasSimpleResult ; @@ -59,31 +61,39 @@ sosa:isFeatureOfInterestOf ] ) ] ) ; sh:minCount 1 ; sh:maxCount 1 ; ] ; - sh:message "Exactly one feature of interest (sosa:hasFeatureOfInterest/sosa:isFeatureOfInterestOf) is required" ; + sh:message "SOSA-testFeatureOfInterest: Exactly one feature of interest (sosa:hasFeatureOfInterest/sosa:isFeatureOfInterestOf) is required" ; +. + +<#SOSA-testFeatureOfInterestSingular> + a sh:NodeShape ; + sh:targetSubjectsOf sosa:hasFeatureOfInterest ; + sh:property [ sh:path sosa:hasFeatureOfInterest ; + sh:maxCount 1 ; ] ; + sh:message "SOSA-testFeatureOfInterest: Only one feature of interest (sosa:hasFeatureOfInterest/sosa:isFeatureOfInterestOf) is allowed for an Observation" ; . -<#testResult> +<#SOSA-testResult> a sh:NodeShape ; sh:targetClass sosa:Observation ; sh:targetSubjectsOf sosa:hasResult, sosa:hasSimpleResult ; sh:property [ sh:path [ sh:alternativePath ( sosa:hasResult sosa:hasSimpleResult ) ] ; sh:minCount 1 ; sh:maxCount 1 ; ] ; - sh:message "Exactly one of sosa:hasResult or sosa:hasSimpleResult is required per observation" ; + sh:message "SOSA-testResult: Exactly one of sosa:hasResult or sosa:hasSimpleResult is required per observation" ; . -<#testSimpleResultLiteral> +<#SOSA-testSimpleResultLiteral> a sh:NodeShape ; sh:targetObjectsOf sosa:hasSimpleResult ; sh:nodeKind sh:IRIOrLiteral ; - sh:message "sosa:hasSimpleResult is a simple Literal" ; + sh:message "SOSA-testSimpleResultLiteral: sosa:hasSimpleResult is a simple Literal" ; . -<#testResultNotEmptyNode> +<#SOSA-testResultNotEmptyNode> a sh:NodeShape ; sh:targetSubjectsOf sosa:hasResult-Disabled ; - sh:message "sosa:hasResult not a blank node" ; + sh:message "SOSA-testResultNotEmptyNode: sosa:hasResult not a blank node" ; sh:sparql [ sh:select """ PREFIX geojson: SELECT $this (sosa:hasResult as ?path) ?value diff --git a/_sources/properties/observationCollection/examples.yaml b/_sources/properties/observationCollection/examples.yaml index b43525ac..f46f9960 100644 --- a/_sources/properties/observationCollection/examples.yaml +++ b/_sources/properties/observationCollection/examples.yaml @@ -60,3 +60,61 @@ eg:p1 a skos:Concept; skos:prefLabel "Some Observable Property"; . + +- title: Nested SOSA ObservationCollection with differing observed properties per sub-collection + content: |- + An ObservationCollection member can itself be another ObservationCollection. + Here the outer collection shares a common `resultTime` and `hasFeatureOfInterest` + across all descendants, while each inner sub-collection declares its own + `observedProperty`, applied to its own member observations. + snippets: + - language: json + code: |- + { + "resultTime": "2022-05-01T22:33:44Z", + "hasFeatureOfInterest": "https://demo.pygeoapi.io/master/collections/utah_city_locations/items/Salem", + "hasMember": [ + { + "@id": "temperature-collection", + "@type": "sosa:ObservationCollection", + "comment": "Sub-collection of temperature observations", + "observedProperty": "temperature", + "hasMember": [ + { + "@id": "obs-temp-1", + "@type": "sosa:Observation", + "phenomenonTime": "2022-05-01T22:33:40Z", + "hasSimpleResult": 21.4 + }, + { + "@id": "obs-temp-2", + "@type": "sosa:Observation", + "phenomenonTime": "2022-05-01T22:34:10Z", + "hasSimpleResult": 21.6 + } + ] + }, + { + "@id": "humidity-collection", + "@type": "sosa:ObservationCollection", + "comment": "Sub-collection of humidity observations", + "observedProperty": "humidity", + "hasMember": [ + { + "@id": "obs-hum-1", + "@type": "sosa:Observation", + "phenomenonTime": "2022-05-01T22:33:40Z", + "hasSimpleResult": 58.2 + }, + { + "@id": "obs-hum-2", + "@type": "sosa:Observation", + "phenomenonTime": "2022-05-01T22:34:10Z", + "hasSimpleResult": 57.9 + } + ] + } + ] + } + base-uri: http://example.com/ + shacl-closure: ['closure.ttl'] diff --git a/_sources/properties/observationCollection/schema.yaml b/_sources/properties/observationCollection/schema.yaml index 4e2ade5a..8925d6fa 100644 --- a/_sources/properties/observationCollection/schema.yaml +++ b/_sources/properties/observationCollection/schema.yaml @@ -2,32 +2,33 @@ description: 'SOSA ObservationCollection' x-jsonld-context: ../../../sosa-ssn.jsonld $defs: + oneOrMany: + oneOf: + - type: + - object + - string + - type: array + items: + type: + - object + - string collection: type: object properties: resultTime: - type: string - format: date-time - phenomenonTime: type: - object - string + phenomenonTime: + $ref: "#/$defs/oneOrMany" hasFeatureOfInterest: - type: - - object - - string + $ref: "#/$defs/oneOrMany" observedProperty: - type: - - object - - string + $ref: "#/$defs/oneOrMany" usedProcedure: - type: - - object - - string + $ref: "#/$defs/oneOrMany" madeBySensor: - type: - - object - - string + $ref: "#/$defs/oneOrMany" hasMember: type: array items: diff --git a/build-devel.sh b/build-devel.sh new file mode 100644 index 00000000..0fff6f71 --- /dev/null +++ b/build-devel.sh @@ -0,0 +1,3 @@ +#!/bin/bash +# Process building blocks using the development (rolling) image build +BBP_IMAGE_TAG=develop exec "$(dirname "$0")/build.sh" "$@" \ No newline at end of file diff --git a/build.sh b/build.sh index e797fa29..c252d908 100644 --- a/build.sh +++ b/build.sh @@ -1,2 +1,15 @@ +#!/bin/bash # Process building blocks -docker run --pull=always --rm --workdir /workspace -v "$(pwd):/workspace" ghcr.io/opengeospatial/bblocks-postprocess --clean true --base-url http://localhost:9090/register/ \ No newline at end of file +if [ -f '.volumes' ]; then + VOLUMES=$(while read -r line; do + if [[ "${line}" != /* ]]; then + echo -n "-v ${PWD}/${line} " + else + echo -n "-v $line " + fi + done < .volumes) +fi +docker run -it --pull=always --rm --workdir /workspace -v "$(pwd):/workspace" ${VOLUMES} \ + ghcr.io/opengeospatial/bblocks-postprocess:${BBP_IMAGE_TAG:-latest} \ + --clean true --base-url http://localhost:9090/register/ "$@" + diff --git a/create-clean-pr.sh b/create-clean-pr.sh new file mode 100644 index 00000000..ac3592bd --- /dev/null +++ b/create-clean-pr.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash +# Creates a "clean" branch of a Building Blocks register fork, excluding all +# changes in the build/ directory (and fork-only config overrides), so that +# it can be used to open a Pull Request against the upstream register without +# generated-artifact merge conflicts. +# +# See https://opengeospatial.github.io/bblocks-docs/build/contribution for details. + +usage() { + echo "Usage: $0 [-u upstreamRemote] [-f forkRemote] [-b upstreamBranch] [-d buildDirectory] [-t tempBranch] [-P]" + echo + echo "Options:" + echo " -u Upstream remote name (default: 'fork-parent')" + echo " -f Fork remote name (default: 'origin')" + echo " -b Upstream branch (default: 'main' or 'master')" + echo " -d Build directory (default: 'build')" + echo " -t Name for the temporary clean branch (default: randomly generated)" + echo " -P Do not push to remote" + echo " -h Show this help message" + exit 1 +} + +UPSTREAM_REMOTE=fork-parent +BUILD_DIR=build +FORK_REMOTE=origin +UPSTREAM_BRANCH= +PUSH_TO_REMOTE=1 +TMP_BRANCH= + +while getopts "u:f:b:d:t:Ph" opt; do + case $opt in + u) UPSTREAM_REMOTE="$OPTARG" ;; + f) FORK_REMOTE="$OPTARG" ;; + b) UPSTREAM_BRANCH="$OPTARG" ;; + d) BUILD_DIR="$OPTARG" ;; + P) PUSH_TO_REMOTE=;; + t) TMP_BRANCH="$OPTARG";; + h) usage ;; + \?) usage ;; + esac +done + +trap_add() { + local cmd="$1" + # shellcheck disable=SC2064 + trap "${cmd};$(trap -p EXIT | cut -d"'" -f2)" EXIT +} + +if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + echo "This script must be run inside a git directory." + echo "If you are using Docker, check you have mounted the right volumes." + exit 1 +fi + +if ! ( git diff --quiet && git diff --cached --quiet ); then + echo "There are pending changes. Please commit or stash them before continuing." + exit 1 +fi + +# Detect git-filter-repo +if [[ -x "./git-filter-repo" ]]; then + FILTER_REPO_CMD="./git-filter-repo" +elif command -v git-filter-repo >/dev/null 2>&1; then + FILTER_REPO_CMD="git-filter-repo" +elif git filter-repo --help >/dev/null 2>&1; then + FILTER_REPO_CMD="git filter-repo" +else + # Download the latest released version to a temp location + LATEST_TAG=$(curl -sSfL https://api.github.com/repos/newren/git-filter-repo/releases/latest \ + | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p') + if [[ -z "$LATEST_TAG" ]]; then + echo "Could not determine the latest git-filter-repo release." >&2 + exit 1 + fi + TMP_DIR=$(mktemp -d) + FILTER_REPO_CMD="$TMP_DIR/git-filter-repo" + if ! curl -sSfL -o "$FILTER_REPO_CMD" \ + "https://raw.githubusercontent.com/newren/git-filter-repo/${LATEST_TAG}/git-filter-repo"; then + echo "Failed to download git-filter-repo ${LATEST_TAG}." >&2 + rm -rf "$TMP_DIR" + exit 1 + fi + chmod +x "$FILTER_REPO_CMD" + trap_add "rm -rf \"$TMP_DIR\"" +fi +echo "Using git-filter-repo command: $FILTER_REPO_CMD" + +CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) +trap_add "git checkout \"$CURRENT_BRANCH\" >/dev/null 2>/dev/null" + +UPSTREAM_URL=$(git remote get-url "$UPSTREAM_REMOTE" 2>/dev/null) +if [[ $? -ne 0 || -z "$UPSTREAM_URL" ]]; then + echo "Upstream remote '$UPSTREAM_REMOTE' does not exist. Please add it first by running:" + echo " git remote add ${UPSTREAM_REMOTE} git@github.com:username/repo.git" + exit 1 +fi +echo "Using upstream remote: ${UPSTREAM_REMOTE} / ${UPSTREAM_URL}" + +FORK_URL=$(git remote get-url "$FORK_REMOTE" 2>/dev/null) +if [[ $? -ne 0 || -z "$FORK_URL" ]]; then + echo "Fork (local) remote '$FORK_REMOTE' does not exist." + exit 1 +fi +echo "Using fork remote: ${FORK_REMOTE} / ${FORK_URL}" + +set -euo pipefail +git fetch "${UPSTREAM_REMOTE}" + +if [[ -z "$TMP_BRANCH" ]]; then + TMP_BRANCH="clean-pr-$(date +%s).$RANDOM" +fi +git checkout -b "$TMP_BRANCH" + +if [[ -z "${UPSTREAM_BRANCH}" ]]; then + if git rev-parse --verify --quiet "${UPSTREAM_REMOTE}"/main >/dev/null; then + UPSTREAM_BRANCH=main + else + UPSTREAM_BRANCH=master + fi +fi +echo "Using upstream branch: ${UPSTREAM_BRANCH}" + +$FILTER_REPO_CMD --path "${BUILD_DIR}" --path .fork --path bblocks-config-override.yml --path bblocks-config-override.yaml --invert-paths --force \ + --refs "${UPSTREAM_REMOTE}/${UPSTREAM_BRANCH}..HEAD" + +if [[ -n "$PUSH_TO_REMOTE" ]]; then + git push "${FORK_REMOTE}" "${TMP_BRANCH}" + echo "Branch created and changed pushed" + + # Strip a trailing .git suffix, then split "owner/repo" on the last slash/colon. + UPSTREAM_PATH="${UPSTREAM_URL#git@github.com:}" + UPSTREAM_PATH="${UPSTREAM_PATH#https://github.com/}" + UPSTREAM_PATH="${UPSTREAM_PATH%.git}" + + FORK_PATH="${FORK_URL#git@github.com:}" + FORK_PATH="${FORK_PATH#https://github.com/}" + FORK_PATH="${FORK_PATH%.git}" + + PR_URL="https://github.com/${UPSTREAM_PATH}/compare/${UPSTREAM_BRANCH}...${FORK_PATH%%/*}:${FORK_PATH#*/}:${TMP_BRANCH}?expand=1" + echo "" + echo "========" + echo "You can use the following URL to create the Pull Request:" + echo " ${PR_URL}" + echo "========" + echo "" +else + echo "Branch '${TMP_BRANCH}' created - push disabled" +fi diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 00000000..5a9a0192 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,6 @@ +# Support scripts + +This directory contains scripts to support usage of these Building Blocks. + +## Consistency checkers and inference for ObservationCollections. + diff --git a/scripts/obs_collection_check.py b/scripts/obs_collection_check.py new file mode 100644 index 00000000..53e28aed --- /dev/null +++ b/scripts/obs_collection_check.py @@ -0,0 +1,1241 @@ +#!/usr/bin/env python3 +""" +ObservationCollection Consistency Checker +========================================== +Analyses JSON files for SOSA/SSN ObservationCollection consistency per +W3C SSN spec section 5.5.2.2: + https://w3c.github.io/sdw-sosa-ssn/ssn/#SOSAObservationCollection + +Rules (paraphrased from the spec): + If a property from the set {hasFeatureOfInterest, hasUltimateFeatureOfInterest, + madeBySensor, observedProperty, phenomenonTime, resultTime, usedProcedure} + is declared on an ObservationCollection, then ALL member observations must + either (a) NOT declare that property themselves (inheriting from the + collection), or (b) declare the SAME value for that property. + +Input targets (positional arguments): + Omit entirely → all *.json files in the current working directory + One or more paths → files, directories, or shell globs + Directories are searched for *.json (add --recursive + to descend into sub-directories). + Backup files (*.backup_*.json) are always excluded. + +Edit strategies (--strategy): + collection-wins (default) + For "conflict" violations: remove the member-level value so the member + inherits the collection value. The collection is authoritative. + + member-wins + For "conflict" violations: update the collection-level value to reflect + the members. + - If all members agree on a single value, promote it to the collection + and remove it from every member (clean inheritance). + - For time aspects (phenomenonTime, resultTime), if members carry + DIFFERENT values, the collection is set to an ISO 8601 interval dict + spanning the full member time range: + {"interval": ["", ""]} + Use --open-end to produce {"interval": ["", ".."]} instead. + Member values are preserved as-is (they are the detail; the collection + provides the bounding envelope). + - For non-time aspects where members disagree, the violation is flagged + as unresolvable and manual intervention is required. + +Modes (--mode): + report Print violations only (default) + report-edit Print violations, then prompt Y/n for each fix + edit Apply all fixes automatically without prompting + restore Restore a previously backed-up file + (requires exactly one file target) + +Usage: + python obs_collection_check.py [targets ...] [options] + +Options: + --dir DIR Directory to search (repeatable; alternative to + positional directory args) + --recursive Descend into sub-directories when scanning dirs + --mode {report,report-edit,edit,restore} + --strategy {collection-wins,member-wins} + --aspects ASPECTS Comma-separated aspects to check (default: all) + Names: hasFeatureOfInterest, hasUltimateFeatureOfInterest, + madeBySensor, observedProperty, phenomenonTime, + resultTime, usedProcedure + Aliases: time -> phenomenonTime,resultTime + procedure, sensor, property, foi, all + --backup-dir DIR Directory for backup files (default: same as each input) + --restore-from FILE Path to a specific backup to restore + --verbose Show passing checks too + --normalize-tz Treat times differing only in Z/tz-suffix as equal. + E.g. 2022-05-22T00:00:00 == 2022-05-22T00:00:00Z + --open-end Under member-wins, produce open-ended time intervals: + {"interval": ["earliest", ".."]} + --summary Print a one-line-per-file summary table at the end + (automatically enabled when processing multiple files) + +Examples: + # All *.json files in the current directory + python obs_collection_check.py + + # All files in a specific directory + python obs_collection_check.py /path/to/surveys/ + python obs_collection_check.py --dir /path/to/surveys/ + + # Recursive directory scan + python obs_collection_check.py /path/to/surveys/ --recursive + + # Shell glob (quoted to prevent shell expansion; script expands it) + python obs_collection_check.py "surveys/*.json" + + # Multiple explicit files + python obs_collection_check.py a.json b.json c.json + + # Mix of files, directories, and globs + python obs_collection_check.py parcels-angles.json "extra/*.json" --dir archive/ + + # Edit all files in a directory with normalize-tz + python obs_collection_check.py --dir surveys/ --mode edit --normalize-tz + + # Restore one specific file + python obs_collection_check.py survey.json --mode restore +""" + +import argparse +import copy +import glob as glob_module +import json +import os +import re +import shutil +import sys +from datetime import datetime, timezone, timedelta +from pathlib import Path +from typing import Any, Optional + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +ALL_ASPECTS = [ + "hasFeatureOfInterest", + "hasUltimateFeatureOfInterest", + "madeBySensor", + "observedProperty", + "phenomenonTime", + "resultTime", + "usedProcedure", +] + +TIME_ASPECTS = {"phenomenonTime", "resultTime"} + +ASPECT_ALIASES = { + "time": ["phenomenonTime", "resultTime"], + "procedure": ["usedProcedure"], + "sensor": ["madeBySensor"], + "property": ["observedProperty"], + "foi": ["hasFeatureOfInterest"], + "all": ALL_ASPECTS, +} + +OBS_COLLECTION_MARKERS = [ + "ObservationCollection", + "sosa:ObservationCollection", + "ssn:ObservationCollection", +] + +COLLECTION_PROP_CONTAINERS = ["properties"] +MEMBER_KEYS = ["hasMember", "features", "members"] +MEMBER_PROP_CONTAINERS = ["properties"] + +# ISO 8601 datetime: date + optional time + optional tz +_ISO_RE = re.compile( + r'^(\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)?)' + r'(Z|[+-]\d{2}:?\d{2})?$' +) + + +# --------------------------------------------------------------------------- +# Time utilities +# --------------------------------------------------------------------------- + +def _parse_iso(s: str) -> Optional[datetime]: + """Parse ISO 8601 string -> aware datetime (assumed UTC if no tz).""" + if not isinstance(s, str): + return None + m = _ISO_RE.match(s.strip()) + if not m: + return None + naive_str, tz_suffix = m.group(1), m.group(2) + if 'T' not in naive_str and ' ' not in naive_str: + naive_str += 'T00:00:00' + try: + dt = datetime.fromisoformat(naive_str) + except ValueError: + return None + if not tz_suffix: + return dt.replace(tzinfo=timezone.utc) + if tz_suffix.upper() == 'Z': + return dt.replace(tzinfo=timezone.utc) + sign = 1 if tz_suffix[0] == '+' else -1 + tz_str = tz_suffix[1:].replace(':', '') + hh, mm = int(tz_str[:2]), int(tz_str[2:]) + tz = timezone(timedelta(hours=sign * hh, minutes=sign * mm)) + return dt.replace(tzinfo=tz) + + +def _strip_tz(s: str) -> str: + """Strip trailing Z or +hh:mm timezone marker.""" + return re.sub(r'(Z|[+-]\d{2}:?\d{2})$', '', s.strip()) + + +def _canonical_z(s: str) -> str: + """Return the string with a Z suffix, adding one if absent.""" + stripped = _strip_tz(s) + return stripped + 'Z' + + +def extract_time_string(v: Any) -> Optional[str]: + """Extract a time string from a plain ISO string or interval dict.""" + if isinstance(v, str): + return v + if isinstance(v, dict): + iv = v.get('interval') + if isinstance(iv, list) and len(iv) >= 1: + # Return first non-open endpoint + for x in iv: + if x and x != '..': + return x + return None + + +def all_time_strings(v: Any) -> list[str]: + """Return all time strings from a value (handles intervals).""" + if isinstance(v, str): + return [v] + if isinstance(v, dict): + iv = v.get('interval') + if isinstance(iv, list): + return [x for x in iv if x and x != '..'] + return [] + + +def build_interval_value(time_strings: list[str], open_end: bool = False) -> dict: + """ + Given a list of ISO time strings, return an interval dict spanning them. + {"interval": ["earliest", "latest"]} or {"interval": ["earliest", ".."]} + Preserves Z-suffix on whichever representative string had it. + """ + parsed = [] + for t in time_strings: + dt = _parse_iso(t) + if dt is not None: + parsed.append((dt, t)) + if not parsed: + end = '..' if open_end else (time_strings[-1] if time_strings else '..') + return {"interval": [time_strings[0] if time_strings else '..', end]} + parsed.sort(key=lambda x: x[0]) + earliest_str = parsed[0][1] + latest_str = parsed[-1][1] + # Prefer the Z-form for endpoints if available + def prefer_z(candidate, all_strs): + z_version = _canonical_z(candidate) + # if any member already uses that string, prefer it + if z_version in all_strs: + return z_version + return candidate + earliest_str = prefer_z(earliest_str, time_strings) + latest_str = prefer_z(latest_str, time_strings) + end = '..' if open_end else latest_str + return {"interval": [earliest_str, end]} + + +def times_semantically_equal(a: Any, b: Any, normalize_tz: bool) -> bool: + """Check whether two time values are semantically equal.""" + if normalize_tz: + def key(v): + if isinstance(v, str): + return _strip_tz(v) + if isinstance(v, dict): + iv = v.get('interval') + if iv: + return json.dumps( + [_strip_tz(x) if isinstance(x, str) and x != '..' else x + for x in iv] + ) + return str(v) + return key(a) == key(b) + return values_equal(a, b) + + +def time_covered_by_collection(member_val: Any, col_val: Any, + normalize_tz: bool) -> bool: + """ + Return True if col_val logically covers member_val. + An interval covers a point if the point is within [start, end]. + A point covers a point if they are equal. + """ + # Exact equality first + if times_semantically_equal(member_val, col_val, normalize_tz): + return True + # If collection is an interval, check containment + if isinstance(col_val, dict) and 'interval' in col_val: + iv = col_val['interval'] + if isinstance(iv, list) and len(iv) == 2: + start_str, end_str = iv[0], iv[1] + m_strs = all_time_strings(member_val) + for m_str in m_strs: + m_dt = _parse_iso(m_str) + if m_dt is None: + continue + s_dt = _parse_iso(start_str) if start_str and start_str != '..' else None + e_dt = _parse_iso(end_str) if end_str and end_str != '..' else None + start_ok = (s_dt is None) or (m_dt >= s_dt) + end_ok = (e_dt is None) or (m_dt <= e_dt) + if start_ok and end_ok: + return True + return False + + +# --------------------------------------------------------------------------- +# General value helpers +# --------------------------------------------------------------------------- + +def values_equal(a: Any, b: Any) -> bool: + if type(a) != type(b): + return False + if isinstance(a, (dict, list)): + return json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True) + return a == b + + +def _resolve(obj: dict, key: str) -> tuple[Any, bool]: + for ck in COLLECTION_PROP_CONTAINERS: + c = obj.get(ck) + if isinstance(c, dict) and key in c: + return c[key], True + if key in obj: + return obj[key], True + return None, False + + +def _resolve_member(member: dict, key: str) -> tuple[Any, bool]: + for ck in MEMBER_PROP_CONTAINERS: + c = member.get(ck) + if isinstance(c, dict) and key in c: + return c[key], True + if key in member: + return member[key], True + return None, False + + +def _set_col_value(col: dict, key: str, value: Any): + """Set a property on a collection, preferring the 'properties' sub-dict.""" + for ck in COLLECTION_PROP_CONTAINERS: + c = col.get(ck) + if isinstance(c, dict): + c[key] = value + return + if key in col: + col[key] = value + return + col.setdefault('properties', {})[key] = value + + +def _delete_member_key(member: dict, key: str): + for ck in MEMBER_PROP_CONTAINERS: + c = member.get(ck) + if isinstance(c, dict) and key in c: + del c[key] + return + if key in member: + del member[key] + + +# --------------------------------------------------------------------------- +# Collection discovery +# --------------------------------------------------------------------------- + +def is_obs_collection(node: Any) -> bool: + if not isinstance(node, dict): + return False + for type_key in ('featureType', '@type', 'type'): + t = node.get(type_key, '') + if isinstance(t, str) and any(m in t for m in OBS_COLLECTION_MARKERS): + return True + if isinstance(t, list) and any( + any(m in x for m in OBS_COLLECTION_MARKERS) for x in t if isinstance(x, str) + ): + return True + if 'hasMember' in node: + return True + return False + + +def find_collections(node: Any, path: str = 'root') -> list[tuple[str, dict]]: + results = [] + if isinstance(node, dict): + if is_obs_collection(node): + results.append((path, node)) + for k, v in node.items(): + results.extend(find_collections(v, f'{path}.{k}')) + elif isinstance(node, list): + for i, item in enumerate(node): + results.extend(find_collections(item, f'{path}[{i}]')) + return results + + +def get_members(collection: dict) -> list[tuple[str, dict]]: + for mk in MEMBER_KEYS: + members = collection.get(mk) + if isinstance(members, list): + return [(f'{mk}[{i}]', m) for i, m in enumerate(members) + if isinstance(m, dict)] + return [] + + +# --------------------------------------------------------------------------- +# Violation +# --------------------------------------------------------------------------- + +class Violation: + def __init__( + self, + collection_path: str, + aspect: str, + collection_value: Any, + member_index: int, + member_path: str, + member_value: Any, + rule: str, # "conflict" | "missing_from_member" + ): + self.collection_path = collection_path + self.aspect = aspect + self.collection_value = collection_value + self.member_index = member_index + self.member_path = member_path + self.member_value = member_value + self.rule = rule + + def describe(self) -> str: + lines = [ + f' Collection : {self.collection_path}', + f' Aspect : {self.aspect}', + f' Rule : {self.rule}', + f' Member [{self.member_index}] : {self.member_path}', + ] + if self.rule == 'conflict': + lines.append(f' Collection value : {json.dumps(self.collection_value)}') + lines.append(f' Member value : {json.dumps(self.member_value)}') + return '\n'.join(lines) + + +def _group_violations( + violations: list[Violation], +) -> dict[tuple[str, str], list[Violation]]: + groups: dict[tuple[str, str], list[Violation]] = {} + for v in violations: + key = (v.collection_path, v.aspect) + groups.setdefault(key, []).append(v) + return groups + + +# --------------------------------------------------------------------------- +# Analysis +# --------------------------------------------------------------------------- + +def analyse_collection( + collection_path: str, + collection: dict, + aspects: list[str], + verbose: bool, + normalize_tz: bool, +) -> list[Violation]: + violations = [] + members = get_members(collection) + if not members: + if verbose: + print(f' [INFO] {collection_path} – no members found, skipping.') + return violations + + for aspect in aspects: + col_value, col_has = _resolve(collection, aspect) + is_time = aspect in TIME_ASPECTS + + for idx, (member_rel_path, member) in enumerate(members): + member_path = f'{collection_path}.{member_rel_path}' + mem_value, mem_has = _resolve_member(member, aspect) + + if col_has and mem_has: + if is_time: + # An interval on the collection covers a point value on a member + equal = time_covered_by_collection(mem_value, col_value, normalize_tz) + else: + equal = values_equal(col_value, mem_value) + + if not equal: + violations.append(Violation( + collection_path, aspect, col_value, + idx, member_path, mem_value, 'conflict', + )) + else: + if verbose: + if is_time and isinstance(col_value, dict) and 'interval' in col_value: + print(f' [OK] {collection_path} | {aspect} | ' + f'member[{idx}] value covered by collection interval.') + else: + print(f' [OK] {collection_path} | {aspect} | ' + f'member[{idx}] matches collection value.') + elif col_has and not mem_has: + if verbose: + print(f' [OK] {collection_path} | {aspect} | ' + f'member[{idx}] inherits from collection.') + elif not col_has and not mem_has: + if verbose: + print(f' [INFO] {collection_path} | {aspect} | ' + f'absent at both levels for member[{idx}].') + else: + if verbose: + print(f' [OK] {collection_path} | {aspect} | ' + f'member[{idx}] carries its own value (collection absent).') + + return violations + + +def analyse_file( + data: Any, + aspects: list[str], + verbose: bool, + normalize_tz: bool, +) -> tuple[list[tuple[str, dict]], list[Violation]]: + collections = find_collections(data) + all_violations: list[Violation] = [] + for path, col in collections: + if verbose: + print(f'\nChecking collection at: {path}') + violations = analyse_collection(path, col, aspects, verbose, normalize_tz) + all_violations.extend(violations) + return collections, all_violations + + +# --------------------------------------------------------------------------- +# Fix logic +# --------------------------------------------------------------------------- + +def _compute_member_wins_fix( + aspect: str, + col_value: Any, + all_member_values: list[Any], + normalize_tz: bool, + open_end: bool, +) -> tuple[Optional[Any], str, bool]: + """ + Determine the new collection value under member-wins strategy. + Returns (new_col_value, description, can_fix). + """ + is_time = aspect in TIME_ASPECTS + + if is_time: + # Gather all distinct time strings (from members + current collection) + all_time_strs: list[str] = [] + for mv in all_member_values: + all_time_strs.extend(all_time_strings(mv)) + if col_value is not None: + all_time_strs.extend(all_time_strings(col_value)) + + if not all_time_strs: + return None, f"No parseable time values found for '{aspect}'.", False + + # Check if all times are semantically equivalent (ignoring tz) + normed = {_strip_tz(t) for t in all_time_strs} + if len(normed) == 1: + # All the same — pick canonical form (prefer Z) + canonical = ( + next((t for t in all_time_strs if t.endswith('Z')), all_time_strs[0]) + ) + desc = ( + f"Set collection '{aspect}' = {json.dumps(canonical)} " + f"(all members agree; will inherit from collection)" + ) + return canonical, desc, True + else: + interval_val = build_interval_value(all_time_strs, open_end=open_end) + desc = ( + f"Set collection '{aspect}' to interval " + f"{json.dumps(interval_val)} spanning {len(normed)} distinct time(s); " + f"member values retained" + ) + return interval_val, desc, True + else: + # Non-time: members must unanimously agree + normed_vals: dict[str, Any] = {} + for mv in all_member_values: + k = json.dumps(mv, sort_keys=True) if isinstance(mv, (dict, list)) else str(mv) + normed_vals[k] = mv + if len(normed_vals) == 1: + new_val = list(normed_vals.values())[0] + desc = ( + f"Set collection '{aspect}' = {json.dumps(new_val)} " + f"(all members agree; will inherit from collection)" + ) + return new_val, desc, True + else: + desc = ( + f"Cannot auto-fix '{aspect}': members have " + f"{len(normed_vals)} distinct values: " + f"{list(normed_vals.values())!r} — manual resolution required" + ) + return None, desc, False + + +def apply_fixes( + data: Any, + violations: list[Violation], + strategy: str, + interactive: bool, + normalize_tz: bool, + open_end: bool = False, +) -> tuple[Any, list[str]]: + modified = copy.deepcopy(data) + fix_log = [] + + collections_map: dict[str, tuple[dict, list[tuple[str, dict]]]] = {} + for path, col in find_collections(modified): + collections_map[path] = (col, get_members(col)) + + groups = _group_violations(violations) + + for (col_path, aspect), group_violations in groups.items(): + if col_path not in collections_map: + fix_log.append(f'[SKIP] Cannot locate collection {col_path} in data.') + continue + + col_node, members = collections_map[col_path] + col_value, _ = _resolve(col_node, aspect) + is_time = aspect in TIME_ASPECTS + + # ── Collection-wins ─────────────────────────────────────────────── + if strategy == 'collection-wins': + desc = ( + f"Remove '{aspect}' from {len(group_violations)} member(s); " + f"inherit collection value {json.dumps(col_value)}" + ) + + if interactive: + _print_group_header(col_path, aspect, group_violations) + print(f'\nStrategy: collection-wins') + print(f'Proposed fix: {desc}') + ans = input('Apply? [Y/n/skip-all]: ').strip().lower() + if ans == 'skip-all': + fix_log.append('[USER] Remaining fixes skipped.') + break + if ans in ('n', 'no'): + fix_log.append(f'[SKIP] User skipped: {col_path} | {aspect}') + continue + + removed = 0 + for v in group_violations: + if v.member_index < len(members): + _, member_node = members[v.member_index] + _delete_member_key(member_node, aspect) + removed += 1 + fix_log.append( + f'[FIXED][collection-wins] {col_path} | {aspect}: ' + f'removed from {removed} member(s). ' + f'Collection value: {json.dumps(col_value)}' + ) + + # ── Member-wins ─────────────────────────────────────────────────── + elif strategy == 'member-wins': + # Collect all member values (violating ones only; non-violating + # members already agree, so also include their values for full span) + all_member_vals = [] + for v in group_violations: + all_member_vals.append(v.member_value) + # Also include non-violating member values for complete time span + for _, member_node in members: + mv, mh = _resolve_member(member_node, aspect) + if mh: + all_member_vals.append(mv) + + new_col_value, desc, can_fix = _compute_member_wins_fix( + aspect, col_value, all_member_vals, normalize_tz, open_end + ) + + if not can_fix: + fix_log.append(f'[CANNOT FIX][member-wins] {col_path} | {aspect}: {desc}') + continue + + if interactive: + _print_group_header(col_path, aspect, group_violations) + print(f'\nStrategy: member-wins') + print(f'Proposed fix: {desc}') + ans = input('Apply? [Y/n/skip-all]: ').strip().lower() + if ans == 'skip-all': + fix_log.append('[USER] Remaining fixes skipped.') + break + if ans in ('n', 'no'): + fix_log.append(f'[SKIP] User skipped: {col_path} | {aspect}') + continue + + # Update collection + _set_col_value(col_node, aspect, new_col_value) + + # If result is a single point value (not interval), remove from + # all members so they cleanly inherit + is_interval = isinstance(new_col_value, dict) and 'interval' in new_col_value + if not is_interval: + removed = 0 + for _, member_node in members: + mv, mh = _resolve_member(member_node, aspect) + if mh: + _delete_member_key(member_node, aspect) + removed += 1 + fix_log.append( + f'[FIXED][member-wins] {col_path} | {aspect}: ' + f'collection → {json.dumps(new_col_value)}, ' + f'removed from {removed} member(s) (now inherited).' + ) + else: + # Interval: members keep their fine-grained values; collection + # provides the bounding envelope — no member removal needed + fix_log.append( + f'[FIXED][member-wins] {col_path} | {aspect}: ' + f'collection → {json.dumps(new_col_value)}; ' + f'member values retained (covered by interval).' + ) + + return modified, fix_log + + +def _print_group_header(col_path, aspect, group_violations): + print(f'\n{"─"*60}') + print(f'VIOLATIONS ({len(group_violations)}) — {col_path} | {aspect}') + col_val = group_violations[0].collection_value + print(f' Collection: {json.dumps(col_val)}') + member_val_map: dict[str, list[int]] = {} + for v in group_violations: + k = json.dumps(v.member_value) + member_val_map.setdefault(k, []).append(v.member_index) + for val_str, idxs in member_val_map.items(): + idxs_repr = ( + str(idxs) if len(idxs) <= 8 + else f'[{idxs[0]}..{idxs[-1]}] ({len(idxs)} members)' + ) + print(f' Member value {val_str}: members {idxs_repr}') + + +# --------------------------------------------------------------------------- +# Backup / restore +# --------------------------------------------------------------------------- + +def create_backup(source_path: str, backup_dir: Optional[str] = None) -> str: + src = Path(source_path).resolve() + ts = datetime.now().strftime('%Y%m%d_%H%M%S') + backup_name = f'{src.stem}.backup_{ts}{src.suffix}' + dest_dir = Path(backup_dir) if backup_dir else src.parent + dest_dir.mkdir(parents=True, exist_ok=True) + dest = dest_dir / backup_name + shutil.copy2(src, dest) + return str(dest) + + +def list_backups(source_path: str, backup_dir: Optional[str] = None) -> list[str]: + src = Path(source_path).resolve() + search_dir = Path(backup_dir) if backup_dir else src.parent + return sorted(str(m) for m in search_dir.glob(f'{src.stem}.backup_*{src.suffix}')) + + +def restore_backup(backup_path: str, target_path: str) -> str: + shutil.copy2(backup_path, target_path) + return f"Restored '{target_path}' from '{backup_path}'" + + +# --------------------------------------------------------------------------- +# Report +# --------------------------------------------------------------------------- + +def print_report( + input_file: str, + collections: list[tuple[str, dict]], + violations: list[Violation], + aspects: list[str], + strategy: str, + normalize_tz: bool, +): + print('\n' + '=' * 70) + print(' ObservationCollection Consistency Report') + print(f' File : {input_file}') + print(f' Aspects : {", ".join(aspects)}') + print(f' Strategy : {strategy}') + if normalize_tz: + print(' Timezone : normalised (Z-suffix ignored for equality test)') + print(' W3C SSN : §5.5.2.2') + print('=' * 70) + + print(f'\nFound {len(collections)} ObservationCollection(s):') + for path, col in collections: + members = get_members(col) + props = col.get('properties', {}) + print(f' {path} ({len(members)} members)') + # Show which aspects are set at collection level + present = [a for a in aspects if _resolve(col, a)[1]] + if present: + for a in present: + v, _ = _resolve(col, a) + print(f' {a}: {json.dumps(v)}') + + if not violations: + print('\n✓ No consistency violations found.\n') + else: + groups = _group_violations(violations) + print(f'\n✗ {len(violations)} violation(s) across ' + f'{len(groups)} collection×aspect group(s):\n') + for (col_path, aspect), grp in groups.items(): + col_val = grp[0].collection_value + print(f' [{col_path}] | {aspect}') + print(f' Collection : {json.dumps(col_val)}') + member_val_map: dict[str, list[int]] = {} + for v in grp: + k = json.dumps(v.member_value) + member_val_map.setdefault(k, []).append(v.member_index) + for val_str, idxs in member_val_map.items(): + idxs_repr = ( + str(idxs) if len(idxs) <= 8 + else f'[{idxs[0]}..{idxs[-1]}] ({len(idxs)} members)' + ) + print(f' Member {val_str}: {idxs_repr}') + print() + + print('=' * 70 + '\n') + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def parse_aspects(aspects_str: str) -> list[str]: + parts = [p.strip() for p in aspects_str.split(',')] + result = [] + for part in parts: + lower = part.lower() + if lower in ASPECT_ALIASES: + result.extend(ASPECT_ALIASES[lower]) + elif part in ALL_ASPECTS: + result.append(part) + else: + match = next((a for a in ALL_ASPECTS if a.lower() == lower), None) + if match: + result.append(match) + else: + print(f'[WARN] Unknown aspect "{part}", ignoring.') + seen, deduped = set(), [] + for r in result: + if r not in seen: + seen.add(r) + deduped.append(r) + return deduped + + +# --------------------------------------------------------------------------- +# File resolution +# --------------------------------------------------------------------------- + +_BACKUP_RE = re.compile(r'\.backup_\d{8}_\d{6}\.json$') + + +def _is_backup(path: Path) -> bool: + return bool(_BACKUP_RE.search(path.name)) + + +def resolve_targets( + targets: list[str], + extra_dirs: list[str], + recursive: bool, +) -> list[Path]: + """ + Expand targets (files, directories, globs) and --dir entries into a + deduplicated, sorted list of .json Paths, excluding backup files. + + If no targets and no --dir are given, defaults to *.json in cwd. + """ + collected: list[Path] = [] + + def add_dir(d: Path): + pattern = '**/*.json' if recursive else '*.json' + for p in sorted(d.glob(pattern)): + if p.is_file() and not _is_backup(p): + collected.append(p.resolve()) + + def add_glob(pattern: str): + # Use Python's glob so it works cross-platform and with quoted globs + matches = sorted(glob_module.glob(pattern, recursive=recursive)) + if not matches: + print(f'[WARN] No files matched: {pattern}', file=sys.stderr) + for m in matches: + p = Path(m).resolve() + if p.is_dir(): + add_dir(p) + elif p.is_file() and p.suffix.lower() == '.json' and not _is_backup(p): + collected.append(p) + + # --dir entries + for d in extra_dirs: + dp = Path(d) + if not dp.exists(): + print(f'[WARN] Directory not found: {d}', file=sys.stderr) + elif not dp.is_dir(): + print(f'[WARN] Not a directory: {d}', file=sys.stderr) + else: + add_dir(dp) + + # positional targets + if targets: + for t in targets: + p = Path(t) + if p.is_dir(): + add_dir(p) + elif '*' in t or '?' in t or '[' in t: + add_glob(t) + elif p.exists() and p.is_file(): + if p.suffix.lower() == '.json' and not _is_backup(p): + collected.append(p.resolve()) + else: + print(f'[WARN] Skipping non-JSON or backup file: {t}', + file=sys.stderr) + else: + # Might be a glob that the shell didn't expand (quoted) + add_glob(t) + elif not extra_dirs: + # Default: all *.json in cwd + add_dir(Path.cwd()) + + # Deduplicate preserving first-seen order + seen: set[Path] = set() + unique: list[Path] = [] + for p in collected: + if p not in seen: + seen.add(p) + unique.append(p) + return unique + + +# --------------------------------------------------------------------------- +# Per-file processing helpers +# --------------------------------------------------------------------------- + +def process_file( + input_file: Path, + aspects: list[str], + mode: str, + strategy: str, + normalize_tz: bool, + open_end: bool, + backup_dir: Optional[str], + verbose: bool, +) -> dict: + """ + Run analysis (and optionally fixes) on a single file. + Returns a result dict for the multi-file summary. + """ + result = { + 'file': str(input_file), + 'collections': 0, + 'violations': 0, + 'fixed': 0, + 'unresolvable': 0, + 'error': None, + 'skipped': False, + } + + try: + with open(input_file, 'r', encoding='utf-8') as f: + data = json.load(f) + except json.JSONDecodeError as e: + result['error'] = f'Invalid JSON: {e}' + print(f'\n[ERROR] {input_file}: {e}', file=sys.stderr) + return result + except OSError as e: + result['error'] = str(e) + print(f'\n[ERROR] {input_file}: {e}', file=sys.stderr) + return result + + collections, violations = analyse_file(data, aspects, verbose, normalize_tz) + result['collections'] = len(collections) + result['violations'] = len(violations) + + print_report(str(input_file), collections, violations, aspects, + strategy, normalize_tz) + + if not violations or mode not in ('edit', 'report-edit'): + return result + + interactive = (mode == 'report-edit') + modified_data, fix_log = apply_fixes( + data, violations, + strategy=strategy, + interactive=interactive, + normalize_tz=normalize_tz, + open_end=open_end, + ) + + if fix_log: + print('\nFix log:') + for entry in fix_log: + print(f' {entry}') + result['fixed'] = sum(1 for e in fix_log if e.startswith('[FIXED]')) + result['unresolvable'] = sum(1 for e in fix_log if e.startswith('[CANNOT FIX]')) + + if json.dumps(data, sort_keys=True) == json.dumps(modified_data, sort_keys=True): + print('\nNo changes made.') + return result + + backup_path = create_backup(str(input_file), backup_dir) + print(f'\nBackup created: {backup_path}') + + with open(input_file, 'w', encoding='utf-8') as f: + json.dump(modified_data, f, indent=2, ensure_ascii=False) + print(f'Updated file written: {input_file}') + + _, post_violations = analyse_file( + modified_data, aspects, verbose=False, normalize_tz=normalize_tz + ) + if post_violations: + groups = _group_violations(post_violations) + print(f'\n[WARN] {len(post_violations)} violation(s) remain ' + f'in {len(groups)} group(s):') + for (cp, asp), grp in groups.items(): + print(f' {cp} | {asp}: {len(grp)} member(s)') + else: + print('\n✓ All violations resolved.') + + return result + + +def print_summary(results: list[dict], aspects: list[str], strategy: str): + """Print a one-line-per-file summary table.""" + total_files = len(results) + total_cols = sum(r['collections'] for r in results) + total_viols = sum(r['violations'] for r in results) + total_fixed = sum(r['fixed'] for r in results) + total_errors = sum(1 for r in results if r['error']) + clean_files = sum( + 1 for r in results if r['violations'] == 0 and not r['error'] + ) + + print('\n' + '=' * 70) + print(' MULTI-FILE SUMMARY') + print(f' Aspects : {", ".join(aspects)}') + print(f' Strategy : {strategy}') + print('=' * 70) + + # Column widths + max_name = max((len(Path(r['file']).name) for r in results), default=20) + max_name = min(max(max_name, 20), 50) + hdr = (f" {'File':<{max_name}} {'Colls':>5} {'Viols':>5}" + f" {'Fixed':>5} Status") + print(hdr) + print(' ' + '-' * (len(hdr) - 2)) + + for r in results: + name = Path(r['file']).name + if len(name) > max_name: + name = '…' + name[-(max_name - 1):] + cols = r['collections'] + viols = r['violations'] + fixed = r['fixed'] + if r['error']: + status = f'ERROR: {r["error"][:40]}' + elif viols == 0: + status = '✓ clean' + elif fixed > 0 and viols == fixed: + status = '✓ fixed' + elif fixed > 0: + status = f'⚠ partial ({viols - fixed} remain)' + else: + status = f'✗ {viols} violation(s)' + print(f' {name:<{max_name}} {cols:>5} {viols:>5} {fixed:>5} {status}') + + print(' ' + '-' * (len(hdr) - 2)) + print(f' {"TOTAL":<{max_name}} {total_cols:>5} {total_viols:>5} {total_fixed:>5} ' + f'{clean_files}/{total_files} files clean' + + (f', {total_errors} error(s)' if total_errors else '')) + print('=' * 70 + '\n') + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + p.add_argument( + 'targets', + nargs='*', + metavar='TARGET', + help=( + 'Files, directories, or glob patterns to process. ' + 'Omit to process all *.json in the current directory.' + ), + ) + p.add_argument( + '--dir', '-d', + dest='dirs', + action='append', + default=[], + metavar='DIR', + help='Directory to scan for *.json files (repeatable).', + ) + p.add_argument( + '--recursive', '-r', + action='store_true', + help='Descend into sub-directories when scanning directories.', + ) + p.add_argument( + '--mode', + choices=['report', 'report-edit', 'edit', 'restore'], + default='report', + help='Operation mode (default: report)', + ) + p.add_argument( + '--strategy', + choices=['collection-wins', 'member-wins'], + default='collection-wins', + help='Edit strategy when fixing violations (default: collection-wins)', + ) + p.add_argument( + '--aspects', default='all', + help='Comma-separated aspects to check (default: all)', + ) + p.add_argument( + '--backup-dir', + default=None, + help='Directory for backups (default: same directory as each input file)', + ) + p.add_argument( + '--restore-from', + default=None, + help='Specific backup file to restore (use with --mode restore)', + ) + p.add_argument( + '--verbose', action='store_true', + help='Show passing checks too', + ) + p.add_argument( + '--normalize-tz', action='store_true', + help='Treat times differing only in Z/tz-suffix as equal', + ) + p.add_argument( + '--open-end', action='store_true', + help='Under member-wins, produce open-ended time intervals (end="..")', + ) + p.add_argument( + '--summary', action='store_true', + help=( + 'Print a per-file summary table at the end. ' + 'Enabled automatically when processing multiple files.' + ), + ) + return p + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + +def main(): + parser = build_parser() + args = parser.parse_args() + + aspects = parse_aspects(args.aspects) + if not aspects: + print('ERROR: No valid aspects specified.', file=sys.stderr) + sys.exit(1) + + # ── RESTORE MODE — requires a single explicit file ───────────────────── + if args.mode == 'restore': + if len(args.targets) != 1 or args.dirs: + print('ERROR: --mode restore requires exactly one file target.', + file=sys.stderr) + sys.exit(1) + input_file = args.targets[0] + if not os.path.isfile(input_file): + print(f'ERROR: File not found: {input_file}', file=sys.stderr) + sys.exit(1) + if args.restore_from: + if not os.path.isfile(args.restore_from): + print(f'ERROR: Backup not found: {args.restore_from}', + file=sys.stderr) + sys.exit(1) + print(restore_backup(args.restore_from, input_file)) + else: + backups = list_backups(input_file, args.backup_dir) + if not backups: + print(f'No backups found for "{input_file}".') + sys.exit(0) + print(f'\nAvailable backups for "{input_file}":') + for i, b in enumerate(backups, 1): + print(f' [{i}] {b}') + choice = input('\nEnter number to restore (or q to quit): ').strip() + if choice.lower() == 'q': + sys.exit(0) + try: + idx = int(choice) - 1 + assert 0 <= idx < len(backups) + except (ValueError, AssertionError): + print('Invalid choice.') + sys.exit(1) + print(restore_backup(backups[idx], input_file)) + sys.exit(0) + + # ── Resolve target files ─────────────────────────────────────────────── + files = resolve_targets(args.targets, args.dirs, args.recursive) + + if not files: + print('No JSON files found to process.', file=sys.stderr) + sys.exit(1) + + multi = len(files) > 1 + show_summary = args.summary or multi + + if multi: + print(f'\nProcessing {len(files)} file(s)...') + + # ── Process each file ────────────────────────────────────────────────── + results = [] + exit_code = 0 + + for file_path in files: + if multi: + print(f'\n{"━" * 70}') + print(f' {file_path}') + print(f'{"━" * 70}') + + result = process_file( + file_path, + aspects=aspects, + mode=args.mode, + strategy=args.strategy, + normalize_tz=args.normalize_tz, + open_end=args.open_end, + backup_dir=args.backup_dir, + verbose=args.verbose, + ) + results.append(result) + + if result['error']: + exit_code = 1 + elif result['violations'] > 0 and args.mode == 'report': + exit_code = 1 + + # ── Summary table ────────────────────────────────────────────────────── + if show_summary: + print_summary(results, aspects, args.strategy) + + sys.exit(exit_code) + + +if __name__ == '__main__': + main() + diff --git a/scripts/obs_collection_check_usage.md b/scripts/obs_collection_check_usage.md new file mode 100644 index 00000000..7d86f78c --- /dev/null +++ b/scripts/obs_collection_check_usage.md @@ -0,0 +1,297 @@ +# `obs_collection_check.py` — Usage Summary + +Checks JSON files for **SOSA/SSN ObservationCollection consistency** per +[W3C SSN §5.5.2.2](https://w3c.github.io/sdw-sosa-ssn/ssn/#SOSAObservationCollection). + +--- + +## The Rule + +If a property is declared on an `ObservationCollection`, every member observation must either **omit** that property (inheriting the collection value) or declare the **same** value. The seven governed properties are: + +| Property | Alias | +|---|---| +| `hasFeatureOfInterest` | `foi` | +| `hasUltimateFeatureOfInterest` | — | +| `madeBySensor` | `sensor` | +| `observedProperty` | `property` | +| `phenomenonTime` | `time` | +| `resultTime` | `time` | +| `usedProcedure` | `procedure` | + +--- + +## Input Targets + +The script accepts **files, directories, and glob patterns** in any combination as positional arguments. If no targets are given it defaults to all `*.json` files in the current working directory. Backup files (`*.backup_*.json`) are always excluded automatically. + +| Invocation | Files processed | +|---|---| +| *(no arguments)* | All `*.json` in the current directory | +| `data.json` | Single explicit file | +| `a.json b.json c.json` | Multiple explicit files | +| `surveys/` | All `*.json` directly inside `surveys/` | +| `"surveys/**/*.json"` | Glob pattern (quote to prevent shell expansion) | +| `--dir surveys/` | Equivalent to passing `surveys/` positionally | +| `--dir surveys/ --recursive` | Descends into all sub-directories | + +`--dir` is repeatable and can be mixed with positional targets: + +```bash +python obs_collection_check.py a.json --dir extra/ --dir archive/ +``` + +--- + +## Quick Start + +```bash +# Report violations for all *.json in the current directory +python obs_collection_check.py + +# Report violations for all files in a specific directory +python obs_collection_check.py /path/to/surveys/ + +# Recurse into sub-directories +python obs_collection_check.py /path/to/surveys/ --recursive + +# Fix all files in a directory automatically +python obs_collection_check.py /path/to/surveys/ --mode edit + +# Restore one specific file +python obs_collection_check.py data.json --mode restore +``` + +--- + +## Modes + +| `--mode` | Behaviour | +|---|---| +| `report` | Print violations only. No changes. *(default)* | +| `report-edit` | Print violations, then prompt **Y/n** before each fix. | +| `edit` | Apply all fixes automatically. Creates a backup per file first. | +| `restore` | Restore one file from a timestamped backup. Requires exactly one file target. | + +--- + +## Edit Strategies + +Select with `--strategy`. Only relevant for `report-edit` and `edit` modes. + +### `collection-wins` *(default)* + +The collection value is authoritative. Conflicting member values are **removed**; members then inherit from the collection. + +```bash +python obs_collection_check.py surveys/ --mode edit --strategy collection-wins +``` + +Use this when the collection metadata is deliberately set and members should conform to it. + +### `member-wins` + +Member values are promoted upward to the collection. + +- **All members agree** → collection is updated to that single value; the property is removed from all members (clean inheritance). +- **Members have different time values** → collection is set to an **ISO 8601 interval** spanning the full range; member values are kept as-is (the collection provides a bounding envelope). +- **Members have different non-time values** → flagged as unresolvable; manual intervention required. + +```bash +python obs_collection_check.py surveys/ --mode edit --strategy member-wins +``` + +Use this when members are the ground truth and the collection header needs updating to reflect them. + +--- + +## Time Intervals + +Under `member-wins`, when member times differ the collection receives an interval: + +```json +"resultTime": { "interval": ["2014-12-01T09:00:00Z", "2014-12-12T00:00:00Z"] } +``` + +Add `--open-end` to leave the end of the interval unbounded: + +```json +"resultTime": { "interval": ["2014-12-01T09:00:00Z", ".."] } +``` + +Once an interval is set on the collection, member point values that fall **within** the interval are no longer flagged as violations. + +--- + +## Options Reference + +| Option | Description | +|---|---| +| `targets` | Files, directories, or glob patterns (positional, repeatable) | +| `--dir DIR` | Directory to scan; repeatable; combinable with positional targets | +| `--recursive` / `-r` | Descend into sub-directories when scanning directories | +| `--mode` | `report` \| `report-edit` \| `edit` \| `restore` | +| `--strategy` | `collection-wins` \| `member-wins` | +| `--aspects` | Comma-separated properties to check (default: `all`) | +| `--normalize-tz` | Treat times differing only in `Z`/timezone suffix as equal | +| `--open-end` | Under `member-wins`, produce open-ended intervals (`".."`) | +| `--backup-dir DIR` | Directory for backup files (default: same as each input file) | +| `--restore-from FILE` | Restore from a specific backup file path | +| `--summary` | Print summary table; auto-enabled when processing multiple files | +| `--verbose` | Show passing checks as well as violations | + +--- + +## Multi-File Summary Table + +When more than one file is processed a summary table is printed automatically: + +``` +====================================================================== + MULTI-FILE SUMMARY + Aspects : hasFeatureOfInterest, ..., resultTime, usedProcedure + Strategy : collection-wins +====================================================================== + File Colls Viols Fixed Status + ---------------------------------------------------- + extended-example.json 2 0 0 ✓ clean + parcels-angles.json 1 1 0 ✗ 1 violation(s) + secondary-parcel.json 1 34 34 ✓ fixed + topographic-string.json 1 4 4 ✓ fixed + ---------------------------------------------------- + TOTAL 5 39 38 2/4 files clean +====================================================================== +``` + +Force the summary table for a single file with `--summary`. + +--- + +## Aspect Filtering + +Check only a subset of the seven properties: + +```bash +# Only time-related aspects +python obs_collection_check.py surveys/ --aspects time + +# Multiple specific aspects +python obs_collection_check.py surveys/ --aspects resultTime,usedProcedure,madeBySensor + +# All (default) +python obs_collection_check.py surveys/ --aspects all +``` + +**Aliases:** `time` → `phenomenonTime, resultTime` · `procedure` → `usedProcedure` · `sensor` → `madeBySensor` · `property` → `observedProperty` · `foi` → `hasFeatureOfInterest` + +--- + +## Timezone Normalisation + +Times like `2022-05-22T00:00:00` and `2022-05-22T00:00:00Z` are semantically identical but string-different, causing violations under strict comparison. Use `--normalize-tz` to treat them as equal: + +```bash +# Detect real conflicts only, ignoring Z-suffix differences +python obs_collection_check.py surveys/ + +# Fix: have members inherit the collection's Z-form value +python obs_collection_check.py surveys/ --mode edit \ + --strategy collection-wins --normalize-tz +``` + +--- + +## Backups and Restore + +A timestamped backup is created **per file** before any file is modified: + +``` +data.backup_20260323_143022.json +``` + +Backup files are excluded from directory scans and glob expansion so they are never processed as input. + +To restore: + +```bash +# Interactive picker — lists all available backups for this file +python obs_collection_check.py data.json --mode restore + +# Restore from a specific backup +python obs_collection_check.py data.json --mode restore \ + --restore-from data.backup_20260323_143022.json + +# Store all backups in a central directory +python obs_collection_check.py surveys/ --mode edit \ + --backup-dir ./backups/ +``` + +> `--mode restore` requires exactly one file target — it cannot be used with directory or glob targets. + +--- + +## Collection Detection + +ObservationCollections are detected automatically anywhere in the JSON tree by checking: + +- `featureType` containing `ObservationCollection` or `sosa:ObservationCollection` +- `@type` or `type` fields with the same markers +- Presence of a `hasMember` key (structural heuristic) + +Member observations are found under `features`, `hasMember`, or `members` arrays. Collection-level shared properties are resolved from a `properties` sub-object or the collection's top level. + +--- + +## Exit Codes + +| Code | Meaning | +|---|---| +| `0` | All files clean, or all violations fixed | +| `1` | One or more violations found (report mode), or a file could not be read | + +--- + +## Common Recipes + +```bash +# Inspect all files in the current directory +python obs_collection_check.py + +# Inspect a whole project tree +python obs_collection_check.py --dir /path/to/project/ --recursive + +# Fix Z-suffix mismatches across an entire directory +python obs_collection_check.py surveys/ --mode edit \ + --strategy collection-wins --normalize-tz + +# Member times span a range — set collection to a covering interval +python obs_collection_check.py surveys/ --mode edit \ + --strategy member-wins --aspects time + +# Same, but leave the interval end open +python obs_collection_check.py surveys/ --mode edit \ + --strategy member-wins --aspects time --open-end + +# Review each fix interactively before applying +python obs_collection_check.py surveys/ --mode report-edit \ + --strategy member-wins + +# Check only sensor and procedure consistency +python obs_collection_check.py surveys/ --aspects sensor,procedure + +# Mix a specific file with an entire directory +python obs_collection_check.py special.json --dir bulk/ + +# Process a glob of files matching a prefix +python obs_collection_check.py "CSD_2024_*.json" + +# Recursive scan across multiple directories +python obs_collection_check.py --dir surveys/ --dir archive/ --recursive + +# Central backup directory, edit in place +python obs_collection_check.py surveys/ --mode edit \ + --backup-dir /backups/surveys/ + +# Force the summary table even for a single file +python obs_collection_check.py data.json --summary +``` diff --git a/view.sh b/view.sh index 4dbaa8b8..1cbe6ab7 100644 --- a/view.sh +++ b/view.sh @@ -1 +1,2 @@ +#!/bin/bash docker run --rm --pull=always -v "$(pwd):/register" -p 9090:9090 ghcr.io/ogcincubator/bblocks-viewer \ No newline at end of file