diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..bf64c5e --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,41 @@ +name: Pages + +on: + push: + branches: [main] + paths: + - "site/**" + - "examples/*.d2.svg" + - ".github/workflows/pages.yml" + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Copy diagrams + run: bash site/build-assets.sh + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: + path: site + + deploy: + needs: build + runs-on: ubuntu-24.04 + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index e613857..80f6aeb 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ models-java/src/generated/ .agents/ agy-evaluation/ .claude/worktrees/ +site/assets/diagrams/ diff --git a/.security-reports/scan-2026-09-13.md b/.security-reports/scan-2026-09-13.md deleted file mode 100644 index 07dff80..0000000 --- a/.security-reports/scan-2026-09-13.md +++ /dev/null @@ -1,60 +0,0 @@ -# Security Scan Report (Post-Remediation) -**Date**: 2026-09-13 -**Project**: OntoLogic -**Scanned**: 35 source and configuration files (Haskell, Python, Java, Kotlin, Shell, Docker, YAML) -**CVE Database**: not available — run /security-update-cve -**Security Grade**: **A** (98/100) - ---- - -## Executive Summary - -| Category | Count | -|---|---| -| Critical findings | 0 | -| High findings | 0 | -| Medium findings | 0 | -| Low findings | 0 | -| Secure patterns found | 9 | -| CVE matches | 0 (local CVE DB offline) | - -**Risk Assessment**: All identified security findings in example scripts, setup utilities, and container definitions have been fully remediated. The codebase is fully hardened with zero critical/high/medium findings and extensive positive security patterns. - ---- - -## What Your Code Does RIGHT - -> Security strengths found in this codebase. These are good practices to preserve and extend. - -### 1. Environment-Driven Credential Management — `examples/batch_loader.py:6-8` -Credentials and URIs are dynamically sourced from `os.getenv("NEO4J_USER")` and `os.getenv("NEO4J_PASSWORD")`, eliminating secret leakage in source control. - -### 2. Resource Management via Context Managers — `examples/batch_loader.py:11` -File descriptors are wrapped with `with open(..., mode="r", encoding="utf-8") as f:`, ensuring reliable cleanup and preventing resource leaks. - -### 3. Safe Subprocess Execution Without Shell Evaluation — `src/Main.hs:117,126` -Visualizer renderer invocation uses Haskell's `System.Process.callProcess` with an explicit argument vector rather than shell command strings (`callCommand`), completely eliminating command injection risks from arbitrary file paths. - -### 4. Cypher Literal & Identifier Sanitization — `src/Emitters/Neo4j.hs:28-31` -The Neo4j emitter implements `escapeCypherString` escaping single quotes (`\'`) and backslashes (`\\\\`), preventing Cypher injection when emitting ontology names and property values. - -### 5. Parameterized Database Queries — `examples/batch_loader.py:14` -Uses parameterized Cypher execution (`session.run("MERGE (n:Device {id: $id}) SET n += $props", id=..., props=...)`), isolating untrusted CSV input from query syntax. - -### 6. Canonical Path Resolution & Import Cycle Protection — `src/Loader.hs:38-50` -Module loader uses `canonicalizePath`, traversal stack tracking, and visited sets, defending against path traversal exploits and circular import recursion denial-of-service. - -### 7. Runtime Constraint Enforcement via Jakarta, Pydantic, Rust & Go — `src/Emitters/` -Generated code emits strict schema constraints (`@NotNull`, `@Min`, `@DecimalMax`, Pydantic `Field(ge=..., le=...)`, Rust `validate()`, Go `Validate()`) preventing invalid state propagation at runtime. - -### 8. Container Configuration Variable Interpolation — `docker-compose.yml:6` -Environment variables use fallback syntax (`${NEO4J_AUTH:-neo4j/password}`) rather than hardcoded credentials. - -### 9. Secure Script Installation Procedure — `setup.sh:31-36` -Installer uses `mktemp` and inspectable script execution rather than blind `curl | bash` pipelines. - ---- - -## Vulnerabilities Found - -> No open vulnerabilities found. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md deleted file mode 100644 index 1dab202..0000000 --- a/ARCHITECTURE.md +++ /dev/null @@ -1,118 +0,0 @@ -# Project Architecture: OntoLogic - -OntoLogic is a **multi-target formal logic transpiler, SMT verification bridge, and interactive REPL**. It follows a classic decoupled compiler architecture: - -$$\text{Frontend (Megaparsec DSL / REPL)} \longrightarrow \text{Core Registry AST} \longrightarrow \text{Verification (Linter / Solver)} \longrightarrow \text{ModelIR} \longrightarrow \text{Backend Emitters (14 Targets)}$$ - ---- - -## I. Compilation Pipeline - -The transpiler treats formal logic as a strongly typed data structure, guaranteeing that business rules, numerical bounds, and relational constraints defined in `.logic` files are structurally preserved across all targets. - -```mermaid -graph TD - subgraph Frontend - A[".logic File(s)"] --> L["Loader (Graph / Diamond Dedup)"] - L --> P["Megaparsec Parser"] - R["Interactive REPL Shell"] --> P - end - - subgraph "Core Registry & Linter" - P --> AST["FOL AST (OntoLogic.hs)"] - AST --> REG["The Registry"] - REG --> LINT{"Static Linter (Linter.hs)"} - LINT -->|Circular DFS / Contradictions| ERR["Compilation Error"] - end - - subgraph "Intermediate Representation (ModelIR)" - LINT -->|Passed| IR["ModelIR (IR.hs)"] - IR --> C_CLS["CompiledClass"] - IR --> C_PROP["CompiledProperty & Bounds"] - IR --> C_REL["CompiledRelation"] - end - - subgraph "Backend Multi-Target Emitters" - IR --> E_TS["TypeScript / Zod Emitter"] - IR --> E_OAS["OpenAPI 3.1 Emitter"] - IR --> E_GQL["GraphQL SDL Emitter"] - IR --> E_SMT["SMT-LIB2 / Z3 Emitter"] - IR --> E_PY["Python Pydantic v2 Emitter"] - IR --> E_JV["Java Jakarta Bean Emitter"] - IR --> E_RS["Rust Structs Emitter"] - IR --> E_GO["Go Structs Emitter"] - IR --> E_JSON["JSON Schema Emitter"] - IR --> E_SHACL["W3C SHACL Emitter"] - IR --> E_NEO["Neo4j Cypher Emitter"] - IR --> E_OWL["W3C OWL/RDF XML Emitter"] - IR --> E_MMD["Mermaid Visualizer"] - IR --> E_D2["D2 Visualizer"] - end -``` - ---- - -## II. Compiler Components - -### 1. Frontend & Loader (`src/Loader.hs`, `src/Parser.hs`) -- **Megaparsec S-Expression Grammar:** Parses definitions (`def-concept`, `def-property`, `def-relation`, `def-axiom`), quantifiers (`forall`, `exists`), logical connectives (`implies`, `iff`, `and`, `or`, `not`), and numeric literals with sign support. -- **Dependency Graph Loader:** Recursively resolves `(import "...")` directives with cycle detection, diamond import deduplication, and lookup in local and standard library paths (`ontologic-lib/`). - -### 2. Static Semantic Linter (`src/Linter.hs`) -- **Taxonomy DAG Analysis:** Detects circular inheritance using Depth-First Search (DFS). -- **Symbol Table Resolution:** Validates undeclared parent concepts, invalid property domains, and undeclared relation ranges. -- **Intra-Axiom Propositional Contradictions:** Flags formulas containing both $P$ and $\neg P$. -- **Cross-Axiom Numerical Interval Contradictions:** Aggregates all lower and upper bounds across axioms per concept and checks for empty interval intersections ($[x \ge a] \land [x \le b]$ where $a > b$). - -### 3. Intermediate Representation (`src/IR.hs`) -`ModelIR` decouples the AST from backend targets: -- `CompiledClass`: Fully resolved inheritance hierarchy, topological class sort, direct and inherited properties. -- `CompiledProperty`: Strong ADT property types (`PropertyType`) and normalized bound constraints (`BoundConstraint`). -- `CompiledRelation`: Normalized binary relationships across classes. -- `irUnmappedAxioms`: Identifies complex non-ground axioms that cannot be mapped into basic property constraints and raises target-specific warnings. - -### 4. Multi-Prover SMT Solver & Automated Proof-Checking Engine (`src/Solver.hs`) -- **Pluggable Multi-Solver Execution:** Bridges the compiled AST to automated theorem provers (**Z3**, **CVC5**, **Vampire**, or auto-discovery) via stdin streams. -- **Consistency Verification:** Checks whole-ontology satisfiability without full compilation overhead. -- **Taxonomic Subsumption Proofs:** Formulates negated subsumption goals $\neg (A \sqsubseteq B)$ with transitivity and reflexivity axioms, proving theorems when `unsat` and returning concrete counterexamples when `sat`. -- **Empty Concept Detection:** Evaluates isolated concept properties to flag contradictory or unsatisfiable concepts across any supported prover. - -### 5. Language Server Protocol (LSP) Engine (`src/LSP.hs`) & VS Code Extension (`editors/vscode/`) -- **JSON-RPC 2.0 Protocol:** Operates over stdio for editor integration with VS Code, Neovim, Emacs, and Helix. -- **Incremental Document Synchronization:** Processes `textDocument/didOpen`, `didChange`, `didSave`, and publishes real-time diagnostic squiggles. -- **IDE Features:** Provides contextual autocompletions (keywords, types, declared concepts/properties), Markdown hover tooltips, and jump-to-definition resolution. -- **VS Code Extension Packaging:** Standalone `.vsix` extension package bundling TextMate syntax grammar (`syntaxes/ontologic.tmLanguage.json`), code snippets, LSP client lifecycle management, and command palette actions for SMT verification. - -### 6. Interactive REPL Subsystem (`src/REPL.hs`) -- Maintains an in-memory `REPLState` consisting of the active `Registry` and loaded file paths. -- Provides interactive command dispatch (`:load`, `:show`, `:lint`, `:solve`, `:prove`, `:unsat`, `:ir`, `:emit`, `:clear`) and dynamic parsing of live S-expressions into the session registry. - -### 7. Backend Emitters (`src/Emitters/`) -1. **Web & API Formats:** - - `TypeScript.hs`: Emits TypeScript types and Zod schemas (`z.object`, `z.number().int().gte()`, `.extend()`). - - `OpenApi.hs`: Emits OpenAPI 3.1 YAML specifications with `allOf` and numerical bounds. - - `GraphQL.hs`: Emits GraphQL SDL types, scalar fields, and root `Query` fields. -2. **Formal Verification & Theorem Proving:** - - `SMT.hs`: Emits SMT-LIB2 logic definitions (`declare-sort`, `declare-const`, `declare-fun`, `assert`, `check-sat`, `get-model`) for Z3 and CVC5 solvers. -3. **Enterprise Application Languages:** - - `Java.hs`: Jakarta Bean Validation (`@NotNull`, `@Min`, `@Max`, `@DecimalMin`, `@DecimalMax`), typed associations, customizable packages. - - `Python.hs`: Pydantic v2 `BaseModel` classes with topological ordering and `Field` validation. - - `Rust.hs`: Rust structs with derives and runtime `validate()` methods. - - `Go.hs`: Go structs with JSON tags and `Validate()` functions. -4. **Knowledge Graphs & Semantic Web:** - - `Neo4j.hs`: ABox/TBox decoupled schema creation (`:OntologyClass`), typed relationship edges (`-[:REL]->`), and modern audit queries (`elementId(n)`). - - `Owl.hs`: W3C OWL/RDF XML (`owl:Class`, `owl:DatatypeProperty`, `owl:ObjectProperty`). - - `JsonSchema.hs`: JSON Schema Draft 2020-12 with `$defs` and numerical constraints. - - `Shacl.hs`: W3C SHACL Shapes in Turtle syntax (`sh:NodeShape`, `sh:PropertyShape`). -5. **Visual Architecture & Graphing:** - - `Mermaid.hs`: Class diagrams with inheritance and associations. - - `D2.hs`: Modern declarative architecture diagrams. - ---- - -## III. Security Architecture & Threat Mitigation - -- **Zero Shell Command Injection:** CLI rendering calls binaries directly via `System.Process.callProcess` with argument vectors, avoiding `/bin/sh -c` string evaluation. -- **Identifier Sanitization (`sanitizeIdent`):** Safely translates colon-delimited and hyphen-delimited ontology names (e.g. `ocsf:FileActivity`, `nist-ai:AISystem`) to legal identifiers (`ocsf_FileActivity`, `nist_ai_AISystem`). -- **Cypher Literal Escaping:** Sanitizes single quotes and backslashes in Cypher generation to prevent injection vectors. -- **Environment-Driven Secrets:** All integration scripts and Docker configurations leverage environment variables (`NEO4J_AUTH`, `NEO4J_USER`, `NEO4J_PASSWORD`) with secure defaults. diff --git a/HOW_TO_USE.md b/HOW_TO_USE.md deleted file mode 100644 index a7ee778..0000000 --- a/HOW_TO_USE.md +++ /dev/null @@ -1,334 +0,0 @@ -# OntoLogic: User Guide & Manual - -OntoLogic is a formal First-Order Logic (FOL) domain-specific language (DSL), multi-target transpiler, theorem prover bridge, and interactive REPL. - ---- - -## 📦 Installation & Setup - -### 1. Building from Source (Haskell Stack) -```bash -# Clone the repository -git clone https://github.com/bsommers/OntoLogic.git -cd OntoLogic - -# Build the project -stack build --ghc-options="-Wall -Werror" - -# Run the test suite -stack test -``` - -### 2. Standalone Release Archive -```bash -# Package standalone bundle -./scripts/package_release.sh - -# Extract and install binary to PATH -tar -xzf dist/ontologic-v1.0.0-linux-x86_64.tar.gz -sudo cp dist/ontologic-v1.0.0-linux-x86_64/bin/ontologic /usr/local/bin/ -``` - -### 3. Docker Environment -```bash -# Spin up local Neo4j database & sandbox -docker-compose up -d -``` - ---- - -## 💻 CLI Commands & Targets - -### Command Syntax -```bash -ontologic -i -t -o [options] -``` - -### Supported Targets (`-t`) - -| Target | Description | Output File | Sample Command | -| :--- | :--- | :--- | :--- | -| `lint` | Static semantic verification | Console output | `ontologic -i model.logic -t lint` | -| `solve` | Z3 SMT consistency & satisfiability check | Console output | `ontologic -i model.logic -t solve` | -| `lsp` | Language Server Protocol (LSP) stdio server | Stdio stream | `ontologic-lsp` / `ontologic --lsp` | -| `repl` | Interactive Ontology REPL | Interactive shell | `ontologic --repl` | -| `ts` / `typescript` / `zod` | TypeScript interfaces & Zod runtime validation | `models.ts` | `ontologic -i model.logic -t ts -o ./ts` | -| `openapi` | OpenAPI 3.1 YAML component schemas | `openapi.yaml` | `ontologic -i model.logic -t openapi -o ./api` | -| `graphql` / `gql` | GraphQL SDL types & Query schema | `schema.graphql` | `ontologic -i model.logic -t graphql -o ./gql` | -| `smt` / `smtlib` | SMT-LIB2 logic for Z3 / CVC5 theorem provers | `spec.smt2` | `ontologic -i model.logic -t smt -o ./smt` | -| `python` | Python Pydantic v2 data models | `models.py` | `ontologic -i model.logic -t python -o ./py` | -| `java` | Jakarta Bean Validation POJOs | `.java` | `ontologic -i model.logic -t java -o ./java --java-package com.domain` | -| `rust` | Rust structs with validation methods | `models.rs` | `ontologic -i model.logic -t rust -o ./rs` | -| `go` / `golang` | Go structs with JSON tags & validation | `models.go` | `ontologic -i model.logic -t go -o ./go` | -| `jsonschema` / `json`| JSON Schema (Draft 2020-12) | `schema.json` | `ontologic -i model.logic -t jsonschema -o ./schema` | -| `shacl` | W3C SHACL Shapes (Turtle format) | `shapes.ttl` | `ontologic -i model.logic -t shacl -o ./rdf --base-iri https://acme.test/onto` | -| `neo4j` | Cypher taxonomy schema & audit queries | `graph.cypher`, `constraints.cypher` | `ontologic -i model.logic -t neo4j -o ./cypher` | -| `owl` | W3C OWL/RDF XML ontology | `ontology.owl` | `ontologic -i model.logic -t owl -o ./owl --base-iri https://acme.test/onto` | -| `mermaid` | Mermaid class diagram (`--render` for SVG) | `class_diagram.mmd` | `ontologic -i model.logic -t mermaid -o ./diag --render` | -| `d2` | D2 declarative architecture diagram (`--render` for SVG) | `diagram.d2` | `ontologic -i model.logic -t d2 -o ./diag --render` | - -> **Note on Neo4j Cypher Target (`neo4j`)**: -> OntoLogic emits two files for Neo4j: -> - `graph.cypher`: Node taxonomies, relationships, and axiom validation queries. Fully compatible with Neo4j Community Edition. -> - `constraints.cypher`: Property existence constraints (`IS NOT NULL`). These require Neo4j Enterprise Edition and are separated so `graph.cypher` can always load cleanly on Community instances (#48). - ---- - -## ⚡ Interactive Ontology REPL - -Launch the REPL by passing `--repl` or `-t repl`: -```bash -stack exec ontologic-exe -- --repl -``` - -### REPL Commands - -| Command | Action | -| :--- | :--- | -| `:load ` | Ingest an ontology file, resolving all imports and namespaces | -| `:show` | Print active concepts, properties, relations, axioms, and active prover | -| `:lint` | Run the static semantic linter against the in-memory registry | -| `:prover [name]` | Show or switch the active SMT prover (`z3`, `cvc5`, `vampire`, `auto`) | -| `:solve` / `:check` | Run SMT consistency & satisfiability check | -| `:prove ` | Prove subsumption theorem ($A \sqsubseteq B$) | -| `:unsat` | Identify unsatisfiable/contradictory concepts | -| `:ir` | Display the compiled `ModelIR` AST structure | -| `:emit ` | Emit code in any of the 14 supported target formats | -| `:clear` | Reset active in-memory session | -| `:help` / `:?` | Display command help | -| `:quit` / `:q` / `exit` | Exit the REPL | -| `(def-concept ...)` | Interactively evaluate and add DSL statements | - -### Example REPL Session -```text -ontologic> (def-concept Device) -Added to registry. - -ontologic> (def-concept SmartSensor Device) -Added to registry. - -ontologic> (def-property batteryLevel SmartSensor Integer) -Added to registry. - -ontologic> (forall (s) (implies (SmartSensor s) (and (gte batteryLevel 0) (lte batteryLevel 100)))) -Added to registry. - -ontologic> :lint -✅ Semantic Linting Passed (0 errors). - -ontologic> :emit ts -import { z } from "zod"; - -export const DeviceSchema = z.object({ -}); -export type Device = z.infer; - -export const SmartSensorSchema = DeviceSchema.extend({ - batteryLevel: z.number().int().gte(0).lte(100), -}); -export type SmartSensor = z.infer; - -ontologic> :emit smt -; SMT-LIB2 Logic Specification generated by OntoLogic -(set-logic ALL) -(set-option :produce-models true) - -; Sort declarations -(declare-sort Entity 0) - -; Entity Concept Constants -(declare-const Device Entity) -(declare-const SmartSensor Entity) - -; Subclass Hierarchy -(declare-fun subClassOf (Entity Entity) Bool) -(assert (subClassOf SmartSensor Device)) - -; Property Functions and Bound Assertions -(declare-fun SmartSensor_batteryLevel (Entity) Int) -(assert (>= (SmartSensor_batteryLevel SmartSensor) 0)) -(assert (<= (SmartSensor_batteryLevel SmartSensor) 100)) - -; Satisfiability Check -(check-sat) -(get-model) -``` - ---- - -## 📝 First-Order Logic (FOL) DSL Syntax - -### 1. Concepts & Inheritance -```lisp -(def-concept Entity) -(def-concept Asset Entity) -(def-concept Server Asset) -``` - -### 2. Typed Properties -Supported types: `Integer`, `Float`, `Double`, `String`, `Boolean`, or custom concept names. -```lisp -(def-property hostname Server String) -(def-property cpuCores Server Integer) -(def-property cpuUtilization Server Float) -(def-property isActive Server Boolean) -``` - -### 3. Binary Relations -```lisp -(def-relation hosts Server Asset) -(def-relation connectsTo Server Server) -``` - -### 4. Axioms & Quantifiers -```lisp -; Bound assertions on properties -(forall (s) - (implies (Server s) - (and (gte cpuCores 1) - (lte cpuCores 128)))) - -(forall (s) - (implies (Server s) - (and (gte cpuUtilization 0.0) - (lte cpuUtilization 100.0)))) -``` - -### 5. Multi-File Imports & Namespaces -```lisp -(namespace "bfo" "http://purl.obolibrary.org/obo/bfo.owl#") -(namespace "cco" "http://www.ontologyrepository.com/CommonCoreOntologies/") - -(import "ontologic-lib/bfo_2020.logic") -(import "ontologic-lib/cco_core.logic") -``` - -Standard-library imports are resolved without a path (`(import "bfo_2020.logic")`) by searching, in order: -`$ONTOLOGIC_PATH` (a `:`-separated list), the directory next to the installed binary, the package data -directory, `./ontologic-lib`, and finally the current directory. Add your own directories with a repeatable -`--lib-path DIR`. Because the current directory is searched **last**, a stray file there cannot shadow a -standard-library module. - -### Naming the generated output - -Neither the RDF base IRI nor the Java package is hardcoded. - -`--base-iri IRI` sets the base for the `owl` and `shacl` targets. With no flag the base is the -ontology's **first declared namespace URI** (a trailing `#` or `/` is stripped), and if the ontology -declares none it falls back to `http://example.org/ontologic`. - -`--java-package PKG` sets the package for the `java` target; the default is `ontologic.generated`. - -In the REPL both are set with `:set`: - -``` -:set base-iri https://acme.test/onto -:set java-package com.acme.models -``` - -### 6. Repository Ontology Directories - -This repository carries two ontology directories with different owners, both intentional: - -- [`ontology/`](./ontology/README.md) — the component ontology generated by the ecosystem spider. -- [`.ontology/`](./.ontology/README.md) — BFO bindings seeded by the ecosystem pipeline. -- [`ontologic-lib/data/`](./ontologic-lib/data/README.md) — generated instance data in Turtle, for - facts the DSL cannot express (it has no form for declaring an individual). - -The tier-3 library they build on, `ontologic-lib/factory_domain.logic`, is vendored from -`factory-domain`, which owns the source. - ---- - -## 🛡️ Static Semantic Linter - -OntoLogic includes a compile-time static analyzer (`-t lint`) that guarantees logical soundness: -1. **Circular Inheritance Detection:** Prevents cycles in the concept taxonomy via DFS graph analysis. -2. **Symbol Table Integrity:** Ensures all parent concepts, property domains, and relation endpoints are declared. -3. **Duplicate Definitions:** Rejects duplicate concept or property definitions. -4. **Intra-Axiom Contradictions:** Flags direct contradictions ($P \land \neg P$). -5. **Cross-Axiom Interval Contradictions:** Flags disjoint numerical intervals across separate axioms (e.g. `(gt score 10)` and `(lt score 5)` on the same concept). - ---- - -## 🔬 Multi-Prover SMT Theorem Proving & Subsumption Reasoning - -OntoLogic integrates directly with automated SMT theorem provers (**Z3**, **CVC5**, **Vampire**, or auto-discovery) to perform live formal verification on your ontology models. - -### 1. Consistency & Satisfiability Checking -```bash -# Check whole-ontology satisfiability with default auto-discovery -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t solve - -# Specify SMT solver backend explicitly (z3, cvc5, vampire) -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic --solve --prover z3 -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic --solve -p cvc5 -``` - -`--solve` reports two things. **Consistency**: whether the axioms can be satisfied at all. **Coherence**: -which concepts can have no instance, given the axioms, bounds and hierarchy (the same check as the REPL's -`:unsat`). It exits non-zero if either fails, `2` if the solver could not decide. Axioms the SMT encoding -cannot express are listed first. - -`--solve` exit codes: `0` = satisfiable (consistent), `1` = unsatisfiable or solver error, `2` = the solver answered `unknown`. - -### 2. REPL Theorem Proving & Reasoning -In the interactive REPL (`ontologic --repl`): -- `:prover [name]`: View active prover or switch backend (`:prover cvc5`, `:prover z3`, `:prover auto`). -- `:solve` / `:check`: Verify whether the current in-memory ontology is satisfiable and display the satisfying model. -- `:prove `: Proves whether $\text{ConceptA} \sqsubseteq \text{ConceptB}$ is a mathematically necessary consequence of the hierarchy and axioms. -- `:unsat`: Identifies whether any concept has contradictory constraints that make it logically empty. - ---- - -## 🛠️ Language Server Protocol (LSP) & VS Code Extension - -OntoLogic provides both a Language Server Protocol engine (`ontologic-lsp` / `ontologic --lsp`) and a packaged VS Code extension (`.vsix`). - -### Installing the VS Code Extension (.vsix) -```bash -# Package or use prebuilt .vsix -./editors/vscode/scripts/build_extension.sh - -# Install extension into VS Code -code --install-extension dist/ontologic-1.0.0.vsix -``` - -The extension automatically manages `ontologic-lsp`, provides full TextMate syntax highlighting, code snippets, real-time diagnostics, hover types, jump-to-definition, and command palette actions (`OntoLogic: Check SMT Consistency & Satisfiability`, `OntoLogic: Check Concept Satisfiability`). - -### Neovim Integration (`nvim-lspconfig`) -```lua -local lspconfig = require('lspconfig') -local configs = require('lspconfig.configs') - -if not configs.ontologic_lsp then - configs.ontologic_lsp = { - default_config = { - cmd = { 'ontologic-lsp' }, - filetypes = { 'logic', 'lisp' }, - root_dir = lspconfig.util.root_pattern('.git', 'package.yaml'), - settings = {}, - }, - } -end - -lspconfig.ontologic_lsp.setup{} -``` - ---- - -## 🏛️ Standard Library Reference (`ontologic-lib/`) - -- `bfo_2020.logic`: Basic Formal Ontology (BFO ISO/IEC 21838-2). -- `cco_core.logic`: Common Core Ontologies (Agent, Information Entity, Artifact). -- `uco_observables.logic`: Unified Cybersecurity Ontology (Process, Socket, File, IP). -- `stix_cve.logic`: STIX 2.1, CVE, CWE, CVSS score bounds, EPSS probability. -- `mitre_attack.logic`: MITRE ATT&CK Enterprise Matrix (Tactics, Techniques, Sub-techniques). -- `mitre_d3fend.logic`: MITRE D3FEND Countermeasures & Defensive Artifacts. -- `mitre_atlas.logic`: MITRE ATLAS Adversarial Threat Matrix for AI. -- `nist_ai_rmf.logic`: NIST AI Risk Management Framework (Govern, Map, Measure, Manage). -- `iso_42001_eu_ai_act.logic`: ISO/IEC 42001 & EU AI Act Risk Categories. -- `nist_csf.logic`: NIST CSF 2.0 (Govern, Identify, Protect, Detect, Respond, Recover). -- `nist_sp800_53.logic`: NIST SP 800-53 Rev 5 & OSCAL Security Baselines. -- `ocsf_schema.logic`: OCSF v1.1.0 Security Telemetry Schema. -- `sigma_rules.logic`: SIGMA Detection Rules & SIEM Semantics. diff --git a/README.md b/README.md index e37e012..003467d 100644 --- a/README.md +++ b/README.md @@ -15,207 +15,70 @@ $$ $$/ $$ | $$ |$$ |$$ $$/ $$ |$$ $$/ $$ $$ |$$ |$$ | $$$$$$/ ``` -## Logic-as-Code Compiler, Ontology Transpiler & SMT Solver Engine +**Logic-as-Code compiler, ontology transpiler and SMT solver engine.** -OntoLogic is a formal First-Order Logic (FOL) domain-specific language (DSL), multi-target compiler, theorem prover bridge, and interactive REPL implemented in Haskell. It compiles high-integrity formal ontological specifications into production software artifacts, API contracts, graph database schemas, knowledge graphs, SMT-LIB2 theorem prover specifications, and visual architecture diagrams. +OntoLogic is a first-order logic (FOL) domain-specific language, multi-target compiler, theorem-prover bridge and REPL written in Haskell. Write a formal ontology once, check it for consistency with Z3, CVC5 or Vampire, and compile it into code, API contracts, database schemas, knowledge-graph formats and diagrams. -> 💡 **Why OntoLogic?** Read the architectural and strategic manifesto: [**Why OntoLogic? Strategic & Architectural Rationale**](docs/WHY_ONTOLOGIC.md) -> *How Logic-as-Code and automated theorem proving eliminate distributed logic drift, the property graph sloppiness tax, and LLM hallucinations across polyglot enterprise stacks.* +[![CI](https://github.com/bsommers/OntoLogic/actions/workflows/ci.yml/badge.svg)](https://github.com/bsommers/OntoLogic/actions/workflows/ci.yml) +[![License: Apache 2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) ---- +Project site: | Rationale: [docs/purpose.md](docs/purpose.md) -## 🚀 Key Features - -* **Formal FOL DSL & Rich Type System**: First-order logic predicates, quantifiers (`forall`, `exists`), implications (`implies`), boolean operators (`and`, `or`, `not`), typed property constraints (`Integer`, `Float`, `Double`, `String`, `Boolean`, custom object concepts), and binary relations (`def-relation`). -* **Modular Multi-File Namespaces**: Support for `(import "path/file.logic")` and `(namespace "prefix")` with cycle detection, diamond import deduplication, and automatic standard library lookup. -* **Semantic Static Linter**: Compile-time symbol table resolution, circular inheritance detection, duplicate definitions, intra-axiom propositional contradictions ($P \land \neg P$), and cross-axiom numeric interval contradiction analysis. -* **Multi-Prover SMT Solver & Theorem Prover**: Live automated consistency checking, taxonomic subsumption proofs ($A \sqsubseteq B$), empty/unsatisfiable concept detection, and counterexample generation with pluggable SMT/ATP backend support (**Z3**, **CVC5**, **Vampire**, or auto-discovery). -* **Language Server Protocol (LSP) Engine (`ontologic-lsp`)**: Built-in JSON-RPC stdio LSP server with real-time squiggly diagnostics, intelligent autocompletion, hover documentation tooltips, jump-to-definition, and rename refactoring. -* **VS Code Extension (`editors/vscode`)**: Packaged `.vsix` extension providing TextMate syntax highlighting, code snippets, LSP client, and SMT solver commands. -* **Intermediate Representation (IR)**: Decoupled compilation pipeline (`ModelIR`) separating frontend logic ASTs from backend target renderers. -* **Interactive Ontology REPL**: Dynamic command-line REPL (`ontologic --repl` or `-t repl`) supporting incremental DSL evaluation, `:load`, `:show`, `:lint`, `:prover `, `:solve`, `:prove`, `:unsat`, `:ir`, `:emit `, and `:clear`. -* **16 Multi-Target Code & Contract Emitters**: - * **TypeScript / Zod**: TypeScript type definitions and composable Zod validation schemas (`z.infer`, `.extend()`, `.gte()`, `.lte()`). - * **OpenAPI 3.1**: OpenAPI YAML component schemas with `allOf` inheritance composition and JSON Schema validation bounds. - * **GraphQL SDL**: GraphQL types, scalar mappings, and query roots (`type Query`). - * **PostgreSQL / ANSI SQL DDL**: Strongly typed relational tables, foreign key constraints, column-level `CHECK` constraints, and index generation. - * **SMT-LIB2 / Z3**: Automated consistency verification and satisfiability checking (`check-sat`, `get-model`) for Z3 / CVC5 theorem provers. - * **TPTP FOF / Vampire ATP**: First-Order Form problem generation for automated theorem provers (Vampire, E, Prover9). - * **Java POJOs**: Jakarta Bean Validation (`@NotNull`, `@Min`, `@Max`, `@DecimalMin`, `@DecimalMax`), typed association fields, and customizable packages (`--java-package`). - * **Python Pydantic v2**: Pydantic `BaseModel` classes, `Field(ge=..., le=...)` constraints, topological sort for clean runtime resolution, and typed association fields. - * **Rust Structs**: Idiomatic Rust structs with derives (`Debug, Clone, PartialEq`), field composition, and `validate(&self) -> Result<(), Vec>` methods. - * **Go Structs**: Go structs with JSON tags, struct embedding for inheritance, and `Validate() []string` methods. - * **Neo4j Cypher**: ABox/TBox decoupled schema creation (`:OntologyClass`), typed relationship edges (`-[:REL]->`), and modern audit queries (`elementId(n)`). - * **W3C OWL/RDF XML**: Standards-compliant OWL ontologies (`owl:Class`, `owl:DatatypeProperty`, `owl:ObjectProperty`, `rdfs:subClassOf`, `rdfs:domain`, `rdfs:range`). - * **JSON Schema**: Draft 2020-12 / Draft 7 schemas with `$defs`, `allOf` inheritance chains, and numerical bound constraints. - * **W3C SHACL Shapes**: Shapes Constraint Language rules in Turtle syntax (`sh:NodeShape`, `sh:PropertyShape`, `sh:datatype`, `sh:class`, `sh:min/maxInclusive`). - * **Mermaid & D2 Visualizers**: Class diagrams and relation arrows with optional headless CLI rendering (`--render`). - - ---- - -## 🏛️ Standard Library (`ontologic-lib/`) - -OntoLogic includes a rigorous, multi-tier standard library covering foundational ontologies, cyber threat intelligence, AI governance, compliance-as-code, and security telemetry: - -### 1. 3-Tier Foundation -* **Top-Level**: `bfo_2020.logic` — Basic Formal Ontology 2020 (ISO/IEC 21838-2). -* **Middle-Tier**: `cco_core.logic` — Common Core Ontologies (Agents, Artifacts, Information Entities). -* **Cyber Observables**: `uco_observables.logic` — Unified Cybersecurity Ontology (Processes, Network Traffic, Sockets, Files). - -### 2. Cyber Threat Intelligence & Adversarial Defense -* **Vulnerability & Exploit**: `stix_cve.logic` — STIX 2.1, CVE, CWE, CVSS score bounds, EPSS probability. -* **Attack Matrix**: `mitre_attack.logic` — MITRE ATT&CK Enterprise Matrix (all 12 tactics & techniques). -* **Defensive Matrix**: `mitre_d3fend.logic` — MITRE D3FEND Countermeasures and defensive relations. - -### 3. AI Safety, Risk Management & Governance -* **AI Threats**: `mitre_atlas.logic` — MITRE ATLAS Adversarial Threat Matrix for Artificial Intelligence. -* **Risk Management**: `nist_ai_rmf.logic` — NIST AI RMF 1.0 (Govern, Map, Measure, Manage functions). -* **Compliance**: `iso_42001_eu_ai_act.logic` — ISO/IEC 42001 & EU AI Act Risk Categories. - -### 4. Cyber GRC & Automated Compliance -* **Cybersecurity Framework**: `nist_csf.logic` — NIST CSF 2.0 (Govern, Identify, Protect, Detect, Respond, Recover). -* **Control Baselines**: `nist_sp800_53.logic` — NIST SP 800-53 Rev 5 & OSCAL Security Baselines. - -### 5. Security Telemetry & Detection -* **Telemetry Taxonomy**: `ocsf_schema.logic` — OCSF v1.1.0 Security Telemetry Schema. -* **SIEM Detection Rules**: `sigma_rules.logic` — SIGMA Detection Rules with OCSF and ATT&CK correlation. - ---- - -## 💻 CLI Usage +## Quickstart ```bash -# Start Interactive REPL session -stack exec ontologic-exe -- --repl - -# Run SMT consistency and satisfiability verification (Z3, CVC5, or auto) -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t solve --prover z3 -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic --solve -p cvc5 - -# Install VS Code Extension -code --install-extension dist/ontologic-1.0.0.vsix - -# Start Language Server Protocol (LSP) stdio server -stack exec ontologic-lsp -# or -stack exec ontologic-exe -- --lsp - -# Lint ontology model -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t lint - -# Generate TypeScript / Zod validation schemas -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t ts -o ./generated/ts - -# Generate OpenAPI 3.1 specification (YAML) -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t openapi -o ./generated/openapi - -# Generate GraphQL SDL schema -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t graphql -o ./generated/graphql - -# Generate SMT-LIB2 logic for Z3 / CVC5 theorem proving -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t smt -o ./generated/smt - -# Generate Java models with Jakarta Bean Validation -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t java -o ./generated/java --java-package com.soc.telemetry - -# Generate Python Pydantic v2 models -stack exec ontologic-exe -- -i ontologic-lib/sigma_rules.logic -t python -o ./generated/python - -# Generate Rust models with built-in validation methods -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t rust -o ./generated/rust - -# Generate Go models with validation methods -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t go -o ./generated/go - -# Generate JSON Schema (Draft 2020-12) -stack exec ontologic-exe -- -i ontologic-lib/stix_cve.logic -t jsonschema -o ./generated/jsonschema - -# Generate W3C SHACL Shapes (Turtle format) -stack exec ontologic-exe -- -i ontologic-lib/bfo_2020.logic -t shacl -o ./generated/shacl +stack build # 1. build +stack exec ontologic-exe -- -i examples/smart_factory.logic -t lint # 2. lint +stack exec ontologic-exe -- -i examples/smart_factory.logic -t solve # 3. check consistency (SMT) +stack exec ontologic-exe -- -i examples/smart_factory.logic -t ts -o ./generated/ts # 4. emit TypeScript/Zod +stack exec ontologic-exe -- --repl # 5. interactive REPL +``` -# Generate Neo4j Cypher schema & audit scripts -stack exec ontologic-exe -- -i ontologic-lib/mitre_attack.logic -t neo4j -o ./generated/cypher +Full walkthrough: [docs/user-guide/quickstart.md](docs/user-guide/quickstart.md). Install options: [docs/user-guide/installation.md](docs/user-guide/installation.md). -# Generate W3C OWL XML ontology -stack exec ontologic-exe -- -i ontologic-lib/bfo_2020.logic -t owl -o ./generated/owl +## Features -# Generate Mermaid / D2 architecture diagrams -stack exec ontologic-exe -- -i examples/smart_grid_relational.logic -t mermaid -o ./generated/diagrams -stack exec ontologic-exe -- -i examples/smart_grid_relational.logic -t d2 -o ./generated/diagrams --render -``` +- **FOL DSL** with typed properties, binary relations, quantifiers and inheritance. +- **Modular namespaces**: `import`, `namespace`, cycle detection and a standard library lookup path. +- **Semantic linter**: symbol resolution, circular inheritance, duplicates and axiom contradictions. +- **Multi-prover solver**: consistency, subsumption proofs, unsatisfiable-concept detection and counterexamples (Z3, CVC5, Vampire or auto). +- **Language server and VS Code extension** (`ontologic-lsp`, `editors/vscode`). +- **Interactive REPL** with `:load`, `:solve`, `:prove`, `:unsat`, `:emit `. +- **Many emitters** from one shared intermediate representation (`ModelIR`). ---- +## Targets -## ⚡ Interactive REPL & Proof-Checking Session +Select with `-t `; see `--help` for the full list and [docs/user-guide/targets-and-emitters.md](docs/user-guide/targets-and-emitters.md) for details. -```text -$ stack exec ontologic-exe -- --repl -╔════════════════════════════════════════════════════════════╗ -║ OntoLogic Interactive REPL v1.0 ║ -║ Type ':help' for commands or enter DSL expressions ║ -╚════════════════════════════════════════════════════════════╝ -ontologic> :load examples/smart_factory.logic -✅ Loaded examples/smart_factory.logic (4 concepts, 0 lint errors). - -ontologic> :solve -✅ SMT Satisfiable (SAT) — Consistent Model Found: -sat -( - (define-fun RoboticArm () Entity ...) -) - -ontologic> :prove RoboticArm Asset -✅ Theorem Proved: 'RoboticArm' ⊑ 'Asset' (Every instance of RoboticArm is necessarily a Asset). - -ontologic> :unsat -✅ All concepts are satisfiable (0 empty concepts). - -ontologic> :emit ts -import { z } from "zod"; - -export const AssetSchema = z.object({ - id: z.string(), -}); -export type Asset = z.infer; - -export const RoboticArmSchema = AssetSchema.extend({ - maxPayload: z.number().int().gte(1).lte(500), -}); -export type RoboticArm = z.infer; - -ontologic> :quit -Goodbye! -``` +| Category | Targets | +|----------|---------| +| Application code | `ts` (Zod), `java`, `python` (Pydantic v2), `rust`, `go`, `cpp` | +| API and data contracts | `openapi`, `graphql`, `jsonschema`, `protobuf`, `sql` | +| Knowledge graphs | `owl`, `shacl`, `neo4j` | +| Provers | `smt` (SMT-LIB2), `tptp`, `solve` | +| Diagrams | `mermaid`, `d2` (add `--render` for images); see [docs/user-guide/visualization.md](docs/user-guide/visualization.md) | +| Tooling | `lint`, `repl`, `lsp` | ---- +## Documentation -## 📖 Documentation & Architecture +- [Documentation index](docs/README.md) +- [User guide](docs/user-guide/README.md): [quickstart](docs/user-guide/quickstart.md), [installation](docs/user-guide/installation.md), [language reference](docs/user-guide/language-reference.md), [CLI reference](docs/user-guide/cli-reference.md), [targets and emitters](docs/user-guide/targets-and-emitters.md), [visualization](docs/user-guide/visualization.md) +- [Architecture](docs/architecture.md) and [purpose](docs/purpose.md) +- [Using OntoLogic](docs/using.md) +- [Developer guide](docs/dev/README.md) +- [Changelog](CHANGELOG.md) -* **[Why OntoLogic? Strategic & Technical Rationale](docs/WHY_ONTOLOGIC.md)** — Foundational manifesto on distributed logic drift, BFO realism, automated theorem proving, and AI hallucination guardrails. -* **[Documentation Index](docs/README.md)** — Master table of contents for compiler manuals, architecture docs, and design guides. -* **[Comprehensive User Guide](docs/user-guide/README.md)** — In-depth tutorial, syntax specifications, CLI flags, multi-target workflows, and troubleshooting. -* **[User Guide & CLI Reference](docs/using.md)** — Quick command-line manual, flags, syntax rules, and examples. -* **[Compiler Pipeline & Architecture](docs/architecture.md)** — Haskell AST, intermediate representations, linter checks, and emitter design. -* **[Standard Library Catalog](ontologic-lib/README.md)** — 3-Tier foundation (BFO/CCO/UCO), cyber threat intelligence (STIX/ATT&CK/D3FEND), AI safety (ATLAS/NIST AI RMF/EU AI Act), and GRC baselines (NIST CSF/800-53/OSCAL). +## Standard library and domain examples ---- +The bundled libraries live in `ontologic-lib/`; see [docs/standard-library.md](docs/standard-library.md). Worked examples across many domains: [docs/domains/README.md](docs/domains/README.md). -## 🛠️ Building & Testing +## Build and test ```bash -# Compile with all warnings as errors stack build --ghc-options="-Wall -Werror" - -# Run full Hspec test suite (685 examples) stack test - -# Package standalone distribution release -./scripts/package_release.sh ``` ---- - -## 📄 License +## License -Apache License 2.0. See [LICENSE](LICENSE) for details. +Apache License 2.0. See [LICENSE](LICENSE). diff --git a/VISUALIZER.md b/VISUALIZER.md deleted file mode 100644 index a01e29e..0000000 --- a/VISUALIZER.md +++ /dev/null @@ -1,53 +0,0 @@ -# Logic Visualizer & Architecture Diagramming - -OntoLogic includes built-in visualizers that transpile your `.logic` First-Order Logic specifications into standard diagram formats (Mermaid and D2 Lang) and can automatically render them to SVG/PNG images. - ---- - -## 🛠️ Prerequisites - -To render images directly from the CLI, install the rendering toolchains: - -### 1. Mermaid CLI (`mmdc`) -```bash -npm install -g @mermaid-js/mermaid-cli -``` - -### 2. D2 CLI -```bash -curl -fsSL https://d2lang.com/install.sh | sh -s -- -``` - -*Note: If these tools are not installed, OntoLogic will still generate the `.mmd` and `.d2` source files for online visualizer editing.* - ---- - -## 💻 CLI Usage - -### Generate Mermaid Class Diagram -```bash -# Generate .mmd text file -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t mermaid -o ./diagrams - -# Generate .mmd and render to SVG -stack exec ontologic-exe -- -i ontologic-lib/ocsf_schema.logic -t mermaid -o ./diagrams --render -``` - -### Generate D2 Declarative Diagram -```bash -# Generate .d2 text file -stack exec ontologic-exe -- -i ontologic-lib/mitre_attack.logic -t d2 -o ./diagrams - -# Generate .d2 and render to SVG -stack exec ontologic-exe -- -i ontologic-lib/mitre_attack.logic -t d2 -o ./diagrams --render -``` - ---- - -## 📊 Supported Diagram Output Formats - -| Format | File Extension | Features | -| :--- | :--- | :--- | -| **Mermaid** | `.mmd` / `.svg` | Standard UML Class Diagrams showing inheritance (`<|--`), typed fields, and association arrows (`-->`). | -| **D2** | `.d2` / `.svg` | Modern declarative structural diagrams with container nesting, typed properties, and directed relationship links. | -| **Neo4j** | `.cypher` | Graph database schema and relationship graph queries. | diff --git a/class_diagram.mmd b/class_diagram.mmd deleted file mode 100644 index 0b6e18c..0000000 --- a/class_diagram.mmd +++ /dev/null @@ -1,186 +0,0 @@ -classDiagram - class Entity - class Continuant - class IndependentContinuant - class MaterialEntity - class Object - class ObjectAggregate - class GDC - class InformationContentEntity - class SDC - class Quality - class RealizableEntity - class Role - class Function - class Occurrent - class Process - class SpatiotemporalRegion - class Infrastructure - class Equipment - class Machine - class Sensor - class Robot - class WeldingRobot - class PaintingRobot - class AssemblyRobot - class Mixer - class Oven - class PackagingMachine - class Product - class Pipeline - class Refinery - class OffshorePlatform - class Wellhead - class Pump - class Valve - class Compressor - class PLC - class Petroleum - class NaturalGas - class MiningEquipment - class HeavyMachinery - class Excavator - class HaulTruck - class DrillRig - class Crusher - class ConveyorBelt - class ComputeNode - class PhysicalServer - class VirtualMachine - class Container - class KubernetesCluster - class SoftwareComponent - class MQTTBroker - class AcmeEdgeGateway - class AcmeCloudService - class Database - class LoadBalancer - class Microservice - class OperatorRole - class SafetyRole - class MaintenanceRole - class DevOpsRole - class SRERole - class CISORole - class SecurityAnalystRole - class ExecutiveRole - class Software - class ControlLogic - class SensorData - class Contract - class SLA - class SecurityArtifact - class DigitalCertificate - class PrivateKey - class SecurityPolicy - class Alert - class IndustrialProcess - class ManufacturingProcess - class ExtractionProcess - class RefiningProcess - class ComputingProcess - class DeploymentProcess - class ScalingProcess - class BusinessProcess - class SalesCycleProcess - class SecurityProcess - class AuthenticationProcess - class EncryptionProcess - class TrustedEntity - Entity <|-- Continuant - Continuant <|-- IndependentContinuant - IndependentContinuant <|-- MaterialEntity - MaterialEntity <|-- Object - MaterialEntity <|-- ObjectAggregate - Continuant <|-- GDC - GDC <|-- InformationContentEntity - Continuant <|-- SDC - SDC <|-- Quality - SDC <|-- RealizableEntity - RealizableEntity <|-- Role - RealizableEntity <|-- Function - Entity <|-- Occurrent - Occurrent <|-- Process - Occurrent <|-- SpatiotemporalRegion - Object <|-- Infrastructure - Object <|-- Equipment - Equipment <|-- Machine - Equipment <|-- Sensor - Machine <|-- Robot - Robot <|-- WeldingRobot - Robot <|-- PaintingRobot - Robot <|-- AssemblyRobot - Machine <|-- Mixer - Machine <|-- Oven - Machine <|-- PackagingMachine - Object <|-- Product - Infrastructure <|-- Pipeline - Infrastructure <|-- Refinery - Infrastructure <|-- OffshorePlatform - Infrastructure <|-- Wellhead - Equipment <|-- Pump - Equipment <|-- Valve - Equipment <|-- Compressor - Equipment <|-- PLC - MaterialEntity <|-- Petroleum - MaterialEntity <|-- NaturalGas - Equipment <|-- MiningEquipment - MiningEquipment <|-- HeavyMachinery - HeavyMachinery <|-- Excavator - HeavyMachinery <|-- HaulTruck - HeavyMachinery <|-- DrillRig - MiningEquipment <|-- Crusher - MiningEquipment <|-- ConveyorBelt - Object <|-- ComputeNode - ComputeNode <|-- PhysicalServer - ComputeNode <|-- VirtualMachine - ComputeNode <|-- Container - Object <|-- KubernetesCluster - Object <|-- SoftwareComponent - SoftwareComponent <|-- MQTTBroker - SoftwareComponent <|-- AcmeEdgeGateway - SoftwareComponent <|-- AcmeCloudService - SoftwareComponent <|-- Database - SoftwareComponent <|-- LoadBalancer - SoftwareComponent <|-- Microservice - Role <|-- OperatorRole - Role <|-- SafetyRole - Role <|-- MaintenanceRole - Role <|-- DevOpsRole - Role <|-- SRERole - Role <|-- CISORole - Role <|-- SecurityAnalystRole - Role <|-- ExecutiveRole - InformationContentEntity <|-- Software - Software <|-- ControlLogic - InformationContentEntity <|-- SensorData - InformationContentEntity <|-- Contract - InformationContentEntity <|-- SLA - InformationContentEntity <|-- SecurityArtifact - SecurityArtifact <|-- DigitalCertificate - SecurityArtifact <|-- PrivateKey - SecurityArtifact <|-- SecurityPolicy - InformationContentEntity <|-- Alert - Process <|-- IndustrialProcess - IndustrialProcess <|-- ManufacturingProcess - IndustrialProcess <|-- ExtractionProcess - IndustrialProcess <|-- RefiningProcess - Process <|-- ComputingProcess - ComputingProcess <|-- DeploymentProcess - ComputingProcess <|-- ScalingProcess - Process <|-- BusinessProcess - BusinessProcess <|-- SalesCycleProcess - Process <|-- SecurityProcess - SecurityProcess <|-- AuthenticationProcess - SecurityProcess <|-- EncryptionProcess - Object <|-- TrustedEntity - Equipment : +Boolean is_active - Equipment : +Integer temperature - MaterialEntity : +Integer has_pressure - Mixer : +Integer rpm - ComputeNode : +Integer cpu_usage - MQTTBroker : +Integer active_connections - SoftwareComponent : +Boolean is_healthy - SecurityArtifact : +Boolean encryption_enabled - Contract : +Integer contract_value - DigitalCertificate : +Boolean is_valid diff --git a/docs/RATIONALE.md b/docs/RATIONALE.md deleted file mode 100644 index de1b57b..0000000 --- a/docs/RATIONALE.md +++ /dev/null @@ -1,100 +0,0 @@ -# The Case for Rigorous Ontology in AI Systems - -**Author:** [OntoLogic Team / Persona: AI reviewer, BFO perspective] -**Date:** February 12, 2026 -**Subject:** Rationale for adopting Basic Formal Ontology (BFO), First-Order Logic (FOL), and Haskell in Industrial AI - -## Executive Summary - -The prevailing approach to AI knowledge representation—relying on loosely defined "knowledge graphs," property graphs, or vector embeddings—is fundamentally insufficient for safety-critical and high-reliability industrial systems. These approaches suffer from semantic ambiguity, lack of interoperability, and the inability to distinguish between what *is* (reality) and what is *recorded about* reality (information). - -This project adopts a rigorous stance: - -1. **Basic Formal Ontology (BFO)** as the upper-level realism-based framework. -2. **First-Order Logic (FOL)** as the unambiguous language of definition. -3. **Haskell** as the purely functional implementation substrate for correctness. - -This document serves as the defense of this architectural choice. - ---- - -## 1. Why BFO? The Necessity of Realism - -### The Problem with "Concepts" - -Most AI systems model "concepts." A concept is a cognitive artifact—an idea in a mind. If your industrial safety system models the *concept* of a high-pressure valve rather than the *universal* HighPressureValve (the actual physical class of entities), you introduce a dangerous layer of indirection. - -- **Concept-based Model:** "Valve" is a node with a property "status: open." -- **Realist Model (BFO):** There exists a `Valve` (Object) which bears a `Disposition` (to control flow), and at a specific `TemporalRegion`, a `Process` of `Opening` is occurring, in which the Valve participates. - -### Why Realism Matters for AI - -1. **Hallucination Reduction:** Large Language Models (LLMs) are probabilistic engines of plausibility, not truth. By grounding an AI in a BFO-aligned ontology, we constrain its output to physically possible states of affairs. An LLM might hallucinate that "The software weighs 5kg." A BFO-based reasoner rejects this immediately: `Software` is a Generically Dependent Continuant (GDC); only Material Entities have mass. -2. **Semantic Interoperability:** In a "flat" knowledge graph, `Connection` might mean a TCP socket, a physical cable, or a social relationship. In BFO, these are distinct: - - TCP Socket: `InformationContentEntity` (or Process depending on focus) - - Cable: `MaterialEntity` - - Social Relationship: `RelationalQuality` - Rigorous distinction allows disparate systems (Mining, Cloud, Manufacturing) to merge data without semantic collision. - ---- - -## 2. Why First-Order Logic (FOL) and Haskell? - -### The Inadequacy of Triples - -Resource Description Framework (RDF) triples (`Subject -> Predicate -> Object`) are too weak for complex industrial logic. They struggle to express: - -- **Universal Quantification ("All"):** "All Pumps must have a SafetyValve." -- **Existential Quantification ("Some"):** "If a Pump is running, there exists a VibrationProcess." -- **Negation:** "A Valve cannot be both Open and Closed." - -### The Power of FOL - -We use FOL because it allows us to define **axioms**. -> `(forall (p) (implies (MiningProcess p) (exists (e) (Excavator e))))` - - This axiom is a constraint on reality. It allows the AI to *deduce* missing information. If we see a `MiningProcess`, we *know* there must be an `Excavator`, even if the sensor didn't report one. This is reasoning, not just retrieval. - -### Why Haskell? - -Implementing an ontology compiler in Python or JavaScript is playing with fire. - -1. **Algebraic Data Types (ADTs):** Haskell's type system allows us to structurally guarantee valid logic. `data FOL = ForAll Var FOL | And FOL FOL` matches the mathematical definition 1:1. -2. **Purity:** A reasoner must be deterministic. Haskell's pure functions ensure that `verify(ontology)` always returns the same result for the same input, crucial for certification. -3. **Parser Combinators:** Parsec/Megaparsec allows us to build a parser that is formally verifiable against the grammar, reducing the attack surface for injection attacks in logic files. - ---- - -## 3. Complexity vs. Rigor: A Trade-off Analysis - -**Critique:** "This is too complex. Why not just use a Neo4j Property Graph?" - -**Response:** -Complexity is conserved. You either handle it in the **Foundational Layer** (Ontology) or you push it to the **Application Layer** (Spaghetti Code). - -| Approach | Setup Cost | Maintenance Cost | Risk of Ambiguity | AI Interpretability | -| :--- | :--- | :--- | :--- | :--- | -| **Ad-Hoc Graph** | Low | **Extreme** | High | Low | -| **BFO + FOL** | High | Low | **Zero** | **High** | - -### The "Sloppiness Tax" - -In a non-rigorous system, every developer defines "Active" differently. One means "Powered On," another means "Connected," a third means "Not Broken." Over 5 years, this semantic debt cripples the system. -By paying the upfront cost of BFO alignment ("Is this a Disposition or a Quality?"), we eliminate this ambiguity forever. - ---- - -## 4. Advantages of this Approach - -1. **Explainable AI (XAI):** When the system flags an alert, it doesn't say "Score 0.98." It says: "Violated Axiom 4: Active Oven must have Temperature > 100." -2. **Safety Logic:** We can mathematically prove that certain dangerous states are impossible in the model. -3. **Universal Integration:** A Pump in a Mining ontology and a Pump in a Cooling ontology are universally compatible because they both inherit from `BFO:Object` and follow standard relations. - -## 5. Conclusion - -We do not build this ontology because we enjoy complexity. We build it because the industrial world is unforgiving. A hallucinated poem is funny; a hallucinated safety valve state is catastrophic. - -**BFO + FOL + Haskell** provides the only bed-rock solid foundation for building Autonomous Industrial AI agents that can be trusted with physical reality. - -*Signed,* -*The OntoLogic Architecture Team* diff --git a/docs/README.md b/docs/README.md index 42320ba..a00505f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,35 +1,55 @@ -# OntoLogic: Documentation Index +# OntoLogic Documentation + +OntoLogic is a Haskell First-Order Logic ontology DSL and toolchain: write a +domain once in a `.logic` file, verify it, and compile it to code, schemas, +proofs and diagrams. Start with the [project README](../README.md), then pick a +path below. + +## Learn and use + +| Document | Read it to | +| :--- | :--- | +| [User guide](user-guide/README.md) | Learn the language and tools in depth | +| [Installation](user-guide/installation.md) | Build or install OntoLogic | +| [Quickstart](user-guide/quickstart.md) | Go from zero to generated output in minutes | +| [Using OntoLogic](using.md) | Follow task-oriented recipes | +| [Language reference](user-guide/language-reference.md) | Look up syntax | +| [Axioms and reasoning](user-guide/axioms-and-reasoning.md) | Write axioms and use the provers | +| [CLI reference](user-guide/cli-reference.md) | Look up every flag and exit code | +| [Targets and emitters](user-guide/targets-and-emitters.md) | See what each of the 18 targets produces | +| [Visualization](user-guide/visualization.md) | Render Mermaid and D2 diagrams | +| [REPL](user-guide/repl.md) | Explore interactively | +| [Editor and LSP](user-guide/editor-and-lsp.md) | Set up VS Code, Neovim and other editors | +| [Troubleshooting](user-guide/troubleshooting.md), [FAQ](user-guide/faq.md) | Fix problems | + +## Understand + +| Document | Read it to | +| :--- | :--- | +| [Purpose](purpose.md) | Know why OntoLogic exists | +| [Architecture](architecture.md) | See how the pipeline, solvers and tooling fit together | + +## Reuse and examples + +| Document | Read it to | +| :--- | :--- | +| [Standard library](standard-library.md) | Find and import ready-made ontologies (BFO, CCO, ATT&CK, NIST, ...) | +| [Domain examples gallery](domains/README.md) | Browse runnable models by sector | + +## Develop and track + +| Document | Read it to | +| :--- | :--- | +| [Developer notes](dev/README.md) | Find plans, reviews, design notes, benchmarks and the coverage audit | +| [Changelog](../CHANGELOG.md) | See what changed in each release | +| [Contributor guide](../AGENTS.md) | Learn the workflow and pre-push gates | + +## Quick start -Welcome to the OntoLogic documentation folder. This directory contains detailed descriptions of the compiler's purpose, design, pipeline internals, and user guides. - ---- - -## 📚 Documents - -1. **[Why OntoLogic? Strategic & Architectural Rationale](WHY_ONTOLOGIC.md)**: The foundational executive and technical manifesto for OntoLogic. Analyzes the 5 fatal anti-patterns of modern polyglot architectures (Distributed Logic Drift, Property Graph Sloppiness Tax, LLM Hallucination Wall, Academic OWL Trap, Data vs. Logic Contracts) and demonstrates how Logic-as-Code, FOL theorem proving, and universal compilation solve them. -2. **[Purpose & Motivation](purpose_and_motivation.md)**: Explains the operational problem of distributed logic drift in IoT fleets and how OntoLogic's "Logic-as-Code" provides a single source of truth. -3. **[Compiler Architecture](architecture.md)**: Details the parser frontend, FOL intermediate representation (AST), validation linter, and multi-target compilation emitters. -4. **[Comprehensive User Guide](user-guide/README.md)**: In-depth user manual, step-by-step tutorial, S-expression syntax specifications, CLI workflows, and troubleshooting. -5. **[User Guide & CLI Reference](using.md)**: Quick reference manual, CLI flags, build configurations, and diagram rendering instructions. -6. **[Suggested Improvements](SUGGESTED_IMPROVEMENTS.md)**: Critical architectural review, bug audits, semantic gaps, and prioritized modernization roadmap. -7. **[Gemini 3.7 Architectural Review & Strategic Recommendations](GEMINI_3_7_REVIEW.md)**: Comprehensive codebase security audit, semantic gap analysis, and phased roadmap by Gemini 3.7 Flash (Medium Reasoning). -8. **[Replay Playbook & Learnings](superpowers/REPLAY_PLAYBOOK.md)**: Complete central manual of architecture learnings, edge cases, and runbook to replay and rebuild the entire compiler and test suite cleanly from scratch. -9. **[Superpowers Plans](superpowers/plans/)**: Formal implementation plans for Milestone 1 (Core Improvements), Milestone 2 (Robust Testing Suite), and Milestone 3 (Security Hardening, Error Handling & CI). -10. **[BFO Critique & Recommendations](AI_BFO_Review.md)**: Formal review of ecosystem ontology against Basic Formal Ontology (BFO) principles (AI-generated). -11. **[Strategic Value of Ontology](ONTOLOGY_VALUE.md)**: Distinguishing taxonomy from ontology, solving IIoT data context issues, and grounding AI. -12. **[Role-Based Organizational Value](COMPANY_ROLES.md)**: Why every role in the organization benefits from formal ontology. -13. **[Case for Rigorous Ontology](RATIONALE.md)**: Technical rationale for BFO, First-Order Logic (FOL), and Haskell in industrial AI systems. - ---- - -## ⚡ Quick Start - -To parse and validate a logic schema, run: ```bash -stack exec ontologic-exe -- -i logic/fleet.logic -t lint -o . +ontologic -i examples/smart_factory.logic -t lint # validate +ontologic -i examples/smart_factory.logic --solve # prove consistency +ontologic -i examples/smart_factory.logic -t python -o out # generate ``` -To transpile a logic schema into Python Pydantic models, run: -```bash -stack exec ontologic-exe -- -i logic/fleet.logic -t python -o generated/ -``` +From a source checkout, replace `ontologic` with `stack exec ontologic-exe --`. diff --git a/docs/WHY_ONTOLOGIC.md b/docs/WHY_ONTOLOGIC.md deleted file mode 100644 index 04d3813..0000000 --- a/docs/WHY_ONTOLOGIC.md +++ /dev/null @@ -1,201 +0,0 @@ -# Why OntoLogic? Strategic & Architectural Rationale - -> **"Complexity is conserved. You either eliminate semantic ambiguity at the mathematical foundation, or you pay an compounding 'sloppiness tax' of distributed bugs, logic drift, and hallucinations in application code."** - ---- - -## Executive Summary - -Modern enterprise software systems are facing an acute **semantics crisis**. As architectures decentralize into microservices, edge devices, polyglot databases, distributed messaging brokers, and autonomous AI agents, the fundamental rules governing domain models, business constraints, and physical reality become dangerously fragmented. - -Today, the same domain concept (e.g., an industrial pump, a cyber vulnerability, or an automated compliance rule) is manually re-implemented across a dozen divergent representations: -- As Java POJOs in an edge gateway or streaming broker -- As Python Pydantic models in an analytics pipeline or ML agent -- As TypeScript interfaces and Zod schemas in a web frontend -- As SQL DDL tables and foreign keys in a relational data warehouse -- As Cypher queries and property graphs in a digital twin database -- As OpenAPI YAML or JSON Schema specs across REST APIs -- As prompt instructions for Large Language Models (LLMs) - -When domain rules evolve or edge conditions change, manual synchronization fails. The result is **Distributed Logic Drift**: silent data corruption, validation bypasses, catastrophic safety failures in cyber-physical systems, and unconstrained AI hallucinations. - -**OntoLogic** solves this structural failure through the paradigm of **Logic-as-Code**: -1. **Single Source of Truth**: Define ontological taxonomies, property constraints, and First-Order Logic (FOL) axioms once in an expressive, declarative s-expression syntax. -2. **Automated Theorem Proving (SMT & ATP)**: Mathematically verify consistency, prove taxonomic subsumptions ($A \sqsubseteq B$), and isolate unsatisfiable or contradictory concepts at compile time using state-of-the-art provers (**Z3**, **CVC5**, **Vampire**). -3. **Universal Multi-Target Compilation**: Transpile the verified model into **15+ native targets** (Java, Python, Rust, Go, TypeScript/Zod, PostgreSQL / ANSI SQL DDL, GraphQL, OpenAPI 3.1, JSON Schema, Neo4j Cypher, W3C OWL, W3C SHACL, SMT-LIB2, TPTP FOF, Mermaid, and D2). -4. **Developer-First Tooling**: Native Language Server Protocol (LSP) engine (`ontologic-lsp`), interactive REPL with live proof checking, and VS Code integration. - ---- - -## 1. The Five Fatal Anti-Patterns in Modern Systems - -### Anti-Pattern 1: Distributed Logic Drift -In large-scale industrial IoT and enterprise architectures, multiple platforms execute different parts of the same operational process: -``` - ┌────────────────────────────────────────┐ - │ The Distributed Logic Drift Problem │ - └────────────────────────────────────────┘ - │ - ┌────────────────────────────────┼────────────────────────────────┐ - ▼ ▼ ▼ - ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ - │ Edge Gateway │ │ IoT Devices │ │ Cloud Twin / DB│ - │ (Java/JVM) │ │ (Python/Rust) │ │ (Neo4j/SQL) │ - │ MaxTemp = 90C │ │ MaxTemp = 100C│ │ MaxTemp = 85C │ - └───────────────┘ └───────────────┘ └───────────────┘ -``` -When a safety threshold or compliance rule changes, developers must manually update Java validation classes, Python parsing scripts, SQL check constraints, and graph schema assertions. Over time, these representations inevitably drift apart. An edge device accepts sensor readings that the cloud rejects, or an edge gateway passes packets that corrupt the downstream digital twin. - -### Anti-Pattern 2: The "Sloppiness Tax" of Flat Property Graphs -Teams frequently reach for property graphs (e.g., Neo4j) or vector databases under the belief that "flexible schemas" reduce development overhead. In reality, schema flexibility is merely deferred debt: -- In a flat property graph, a node labeled `:Asset` has whatever keys a developer happens to insert. One engineer writes `status: "active"`, another writes `is_active: true`, and a third writes `state: 1`. -- A relationship like `CONNECTED_TO` is overloaded to mean a physical ethernet cable, a logical TCP connection, a cryptographic trust relationship, or a corporate reporting structure. - -Without rigorous type constraints and domain/range axioms, querying the graph requires complex, defensive application code filled with null-checks and heuristic string matching. Over 5 years, this **sloppiness tax** cripples data engineering velocity. - -### Anti-Pattern 3: The LLM Hallucination Wall -Large Language Models (LLMs) are probabilistic engines of plausibility, not engines of truth. When an AI agent is tasked with diagnosing an industrial anomaly or executing a safety-critical workflow, prompting alone cannot guarantee physical or logical soundness: -- An LLM may hallucinate that an unpowered sensor is transmitting high temperatures, or that software code possesses physical weight. -- Vector embeddings and vector similarity search (RAG) can retrieve semantically related text, but they cannot perform **deductive reasoning** or enforce **invariants**. - -By grounding AI agents in an OntoLogic model, the agent's action space is strictly bounded by First-Order Logic axioms. If an LLM suggests an operation that violates a physical law or security policy, the ontology compiler/reasoner rejects it deterministically before execution. - -### Anti-Pattern 4: The Academic OWL/RDF Trap -Why not simply use the W3C Semantic Web stack (RDF, OWL, SPARQL, Protégé)? -While theoretically sound, the traditional Semantic Web stack has failed in mainstream industrial software engineering for concrete reasons: -- **Academic Tooling**: Tools like Protégé are desktop GUI artifacts detached from modern CI/CD pipelines, git workflows, and automated testing. -- **Open-World Assumption (OWA) Mismatch**: OWL's Open-World Assumption means that the absence of information is not treated as false. In software engineering and validation, closed-world or bounded validation (e.g., "this field is required") is essential. -- **Runtime Reasoner Latency**: Classical Description Logic reasoners (HermiT, Pellet) are computationally expensive and cannot be embedded in high-throughput microservices or low-power edge gateways. -- **Zero Code Generation**: OWL gives you an XML file; it does not give you idiomatic Python Pydantic classes, Rust structs, Java POJOs, or SQL DDL. - -### Anti-Pattern 5: The Interface Contract Void -Tools like Protocol Buffers, JSON Schema, and OpenAPI solve data serialization, but they cannot express **domain logic**: -- Protobuf can declare that an integer field `risk_score` exists. It cannot declare that `if risk_score > 7, then a mitigation artifact must exist`. -- OpenAPI can declare endpoints and data shapes. It cannot verify that your inheritance taxonomy is free of circular dependencies or contradictory constraints. - -Data contracts without logic contracts are incomplete specifications. - ---- - -## 2. The OntoLogic Solution: Logic-as-Code - -OntoLogic unifies formal ontology, first-order logic, and multi-target code generation into a single pipeline: - -``` - ┌──────────────────────────────┐ - │ Unified .logic File │ - │ - Concepts & Taxonomy │ - │ - Typed Properties & Bounds │ - │ - Relations & Cardinality │ - │ - First-Order Logic Axioms │ - └──────────────────────────────┘ - │ - ▼ - ┌──────────────────────────────┐ - │ OntoLogic Compiler │ - │ 1. Parser (Megaparsec) │ - │ 2. Semantic Linter │ - │ 3. SMT/ATP Reasoner Bridge │ - │ (Z3, CVC5, Vampire) │ - └──────────────────────────────┘ - │ - ┌─────────────────────────┼─────────────────────────┐ - ▼ ▼ ▼ - ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ - │ Polyglot Code │ │ Data & Schema │ │ Verification │ - │ - Java POJOs │ │ - SQL DDL │ │ - SMT-LIB2 │ - │ - Python v2 │ │ - Neo4j Cypher│ │ - TPTP FOF │ - │ - Rust Structs│ │ - OpenAPI 3.1 │ │ - W3C OWL XML │ - │ - Go Structs │ │ - GraphQL SDL │ │ - W3C SHACL │ - │ - TS / Zod │ │ - JSON Schema │ │ - D2 / Mermaid│ - └───────────────┘ └───────────────┘ └───────────────┘ -``` - ---- - -## 3. Core Architectural Pillars - -### Pillar I: Ontological Realism (Basic Formal Ontology - ISO/IEC 21838-2) -OntoLogic adopts **Basic Formal Ontology (BFO)** as its default upper-level architecture: -- **Distinction Between Reality and Information**: Distinguishes between physical entities (`MaterialEntity`), running executions (`Process`, `Occurrent`), and the records describing them (`InformationContentEntity`, GDC). -- **Roles vs. Objects**: Models transient capabilities as roles (`TrustedRole`, `CISORole`) inhering in entities, rather than hardcoding mutable permissions into object types. -- **Cross-Domain Interoperability**: Because manufacturing machines, cyber assets, cloud infrastructure, and organizational actors all inherit from a common realist foundation, disparate enterprise schemas integrate without semantic collisions. - -### Pillar II: First-Order Logic (FOL) Expressiveness -OntoLogic goes far beyond simple taxonomies by providing full first-order logic: -- **Quantifiers**: Universal (`forall`) and existential (`exists`) quantification over individuals and sorted types. -- **Connectives**: Implication (`implies`), biconditional (`iff`), conjunction (`and`), disjunction (`or`), and negation (`not`). -- **Rich Relations & Functions**: Multi-arity relations ($n \ge 3$), function terms ($f(t)$), typed literals, and built-in equality ($=$, $\neq$). - -```lisp -;; Compliance Invariant: High-risk vulnerabilities require an active mitigation artifact -(forall (v) - (implies (and (Vulnerability v) (gt risk_score 7)) - (exists (m) (and (Mitigation m) (mitigates m v))))) -``` - -### Pillar III: Automated Theorem Proving & SMT Solvers -OntoLogic compiles domain axioms into formal logic theories and connects directly to state-of-the-art automated provers: -- **Z3 & CVC5**: Native SMT-LIB2 theory generation for satisfiability checking, unsat core isolation (`:explain`), and satisfying model generation (`:model`). -- **Vampire Theorem Prover**: Native TPTP First-Order Form (FOF) emission with CASC portfolio optimization for deep taxonomic subsumption proofs ($A \sqsubseteq B$) and unsatisfiable concept detection. -- **Embedded Propositional SAT Engine**: Fast compile-time dead-code and contradiction elimination directly in the linter without external dependencies. - -### Pillar IV: Zero-Overhead Polyglot Code Generation -Instead of requiring systems to run heavy reasoning engines in production, OntoLogic compiles verified logical invariants into **lightweight, platform-native validation logic**: -- **Java**: Jakarta Bean Validation (`@NotNull`, `@Min`, `@Max`, `@DecimalMin`, `@DecimalMax`). -- **Python**: Pydantic v2 `BaseModel` classes with `Field(ge=..., le=...)` constraints. -- **TypeScript**: Zod composable schemas with `.extend()`, `.gte()`, `.lte()`, and `.refine()` blocks. -- **Rust & Go**: Native structs with type-safe validation methods (`validate(&self)` / `Validate()`). -- **SQL DDL**: Relational tables with table-per-type inheritance, foreign keys, check constraints, and junction tables. -- **Neo4j**: Cypher DDL with uniqueness constraints and relationship definitions. - -### Pillar V: Developer Ergonomics & Tooling -Ontology engineering should look and feel like modern software engineering: -- **Language Server Protocol (LSP)**: Real-time diagnostics, semantic highlighting, hover cards with docstrings, jump-to-definition, symbol renaming, and automated formatting. -- **Interactive REPL**: Rapid prototyping with `:load`, `:solve`, `:prove`, `:unsat`, `:ir`, and `:emit `. -- **VS Code Extension**: Production syntax highlighting, snippets, and integrated reasoning commands. - ---- - -## 4. Comprehensive Technology Comparison - -| Capability / Dimension | Ad-Hoc Code & DTOs | Pure JSON Schema / OpenAPI | Pure RDF / OWL (Protégé) | Neo4j / Property Graphs | **OntoLogic** | -| :--- | :--- | :--- | :--- | :--- | :--- | -| **Single Source of Truth** | ❌ Fragmented | ⚠️ Data shapes only | ⚠️ Academic ontology | ⚠️ Database only | ✅ **Unified Logic-as-Code** | -| **Logic & Axiom Constraints** | ⚠️ Hand-coded per app | ❌ None | ✅ Description Logic | ❌ None | ✅ **First-Order Logic (FOL)** | -| **Compile-Time Proofs (SMT/ATP)** | ❌ None | ❌ None | ⚠️ Slow DL Reasoners | ❌ None | ✅ **Live Z3, CVC5, Vampire** | -| **Multi-Target Code Generation** | ❌ None | ⚠️ Basic stubs | ❌ None | ❌ None | ✅ **15+ Native Emitters** | -| **Relational DDL Generation** | ⚠️ Manual migrations | ❌ None | ❌ None | ❌ None | ✅ **PostgreSQL / ANSI DDL** | -| **Graph Database Schema** | ⚠️ Manual Cypher | ❌ None | ⚠️ RDF Triple stores | ✅ Native Graph DB | ✅ **Native Cypher DDL** | -| **Realist Upper Ontology (BFO)** | ❌ Unstructured | ❌ Unstructured | ⚠️ Possible in OWL | ❌ Unstructured | ✅ **Built-in BFO/CCO Library** | -| **Developer Ergonomics (LSP/REPL)** | ⚠️ Per-IDE | ⚠️ Basic schema linter | ❌ Java GUI (Protégé) | ⚠️ Browser console | ✅ **Native LSP & CLI REPL** | -| **Runtime Performance** | ⚠️ Variable | ✅ Fast parsing | ❌ Heavy reasoner | ⚠️ Query overhead | ✅ **Zero runtime overhead** | -| **AI Agent Grounding** | ❌ Probabilistic prompt | ⚠️ Shape validation only| ⚠️ Heavy KG query | ⚠️ Vector RAG only | ✅ **Sound FOL Verification** | - ---- - -## 5. Enterprise Use Cases & Impact - -### 1. Industrial IoT, MQTT & Unified Namespace (UNS) -- **Problem**: Industrial equipment publishes millions of telemetry messages per second across MQTT brokers (e.g., Acme). Raw payloads (`temp: 45`) lack context and arrive with conflicting units and semantics across machine vendors. -- **OntoLogic Solution**: Compiles the enterprise ontology into Acme broker plugin validators, edge gateway parsers, and digital twin database schemas. Every sensor payload is validated against physical bounds at the wire level, and semantic context (`TemperatureQuality`, `Celsius`) is attached automatically. - -### 2. Cyber Threat Intelligence & Automated Compliance (GRC) -- **Problem**: Aligning threat intelligence (MITRE ATT&CK, STIX 2.1, CVE), defensive controls (MITRE D3FEND, NIST SP 800-53), and regulatory requirements (EU AI Act, ISO 42001) requires cross-referencing dozens of disconnected spreadsheets and schemas. -- **OntoLogic Solution**: Ships with pre-compiled standard libraries for STIX, ATT&CK, D3FEND, NIST CSF, and the EU AI Act. Security teams define compliance invariants as FOL axioms and verify mathematically that control requirements are satisfied. - -### 3. Autonomous AI Swarms & Deterministic Agent Sandboxes -- **Problem**: Autonomous coding and operations agents hallucinate invalid actions or attempt physically impossible workflows. -- **OntoLogic Solution**: Provides a formal constraint engine that evaluates proposed agent actions against the ontology model before execution. Actions that violate domain invariants are blocked deterministically. - ---- - -## 6. Summary: The Bedrock of High-Integrity Systems - -We do not build with formal ontology because we enjoy theoretical complexity. We build with formal ontology because **the real world is unforgiving**: -- A hallucinated poem from an LLM is humorous. -- A hallucinated valve status in an industrial cooling system or a bypassed constraint in an autonomous security pipeline is catastrophic. - -OntoLogic provides the mathematical rigor of First-Order Logic, the sound ontology of BFO, the speed of automated theorem provers, and the pragmatic utility of multi-target code generation. - -It is **Logic-as-Code** for systems that cannot afford to be wrong. diff --git a/docs/architecture.md b/docs/architecture.md index d2e05a7..e8adff6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,42 +1,238 @@ -# OntoLogic: Compiler Architecture +# Architecture -This document describes the compiler internals, abstract syntax tree (AST), validation linter, and compilation emitter structure of OntoLogic. +OntoLogic is a classic compiler with a verification stage in the middle: a +frontend parses `.logic` files into one `Registry`, a linter and prover check it, +a normalizing step produces `ModelIR`, and a table-driven backend turns it into +18 output formats. The same core serves the CLI, the REPL and the language +server. ---- +- [Pipeline](#pipeline) +- [Module map](#module-map) +- [Frontend and loader](#frontend-and-loader) +- [Core data model](#core-data-model) +- [Linter](#linter) +- [ModelIR](#modelir) +- [Emitters and the target registry](#emitters-and-the-target-registry) +- [Solvers and provers](#solvers-and-provers) +- [REPL](#repl) +- [Language server and editors](#language-server-and-editors) +- [Security design](#security-design) -## ⚙️ The Compilation Pipeline +## Pipeline -OntoLogic follows a classic compiler frontend-to-backend pipeline: +```mermaid +flowchart TD + subgraph Frontend + F[".logic files"] --> LD["Loader.hs
imports, cycle and diamond handling"] + LD --> PA["Parser.hs
Megaparsec S-expressions"] + RP["REPL.hs
live S-expressions"] --> PA + end + PA --> REG["Registry
(OntoLogic.hs)"] + REG --> LI{"Linter.hs
+ Linter/SAT.hs"} + LI -- findings --> ERR["file:line:col diagnostics
exit 1"] + LI -- clean --> BR{"Mode"} + BR -- "-t target" --> IR["IR.hs
ModelIR"] + IR --> TG["Targets.hs
registry of 18 targets"] + TG --> EM["Emitters/*.hs"] + EM --> OUT["generated files"] + BR -- "--solve / REPL" --> SV["Solver.hs"] + SV --> FT["FOLTheory.hs
instance-level theory"] + FT --> EXT["Z3, CVC5, Vampire
(external processes)"] + SV --> CL["IR/Clausify.hs + IR/CNF.hs"] + CL --> NAT["Prover/*
native resolution + tableau"] + BR -- "--cnf" --> CL +``` + +`Main.hs` dispatches in this order: `--lsp`, `--repl`, then load, lint, and +finally `--cnf`, solve, or a target. Lint errors stop everything before any +emitter or solver runs. + +## Module map + +| Module | Role | +| :--- | :--- | +| `src/Main.hs` | CLI parsing (optparse-applicative), mode dispatch, solver report and exit codes | +| `src/OntoLogic.hs` | Core types: `Registry`, `FOL`, `Term`, `PropertyType`, `BoundConstraint`, `Cardinality`, `RelationDef`, namespaces, imports, source positions | +| `src/Parser.hs` | Megaparsec S-expression parser producing a `Registry` plus a `SourceTable` of positions | +| `src/Loader.hs` | Recursive import resolution, search paths, merge of registries and source tables | +| `src/Linter.hs` | Static semantic checks, GCC-style diagnostics | +| `src/Linter/SAT.hs` | Propositional encoding with Horn and DPLL solving for contradiction and concept-coherence checks | +| `src/IR.hs` | `ModelIR`: resolved classes, properties with bounds, relations, unmapped axioms; warning formatting | +| `src/Targets.hs` | The `targets` table and `lookupTarget`, shared by CLI and REPL | +| `src/Emitters/*.hs` | One module per output family (see below) | +| `src/Solver.hs` | Prover selection, process execution with timeouts, consistency, subsumption, unsat concepts, unsat cores | +| `src/FOLTheory.hs` | Builds the instance-level first-order theory used by SMT-LIB and TPTP solver paths | +| `src/IR/Clausify.hs`, `src/IR/CNF.hs` | Negation normal form, Skolemization and clause types for the native provers | +| `src/Prover/Resolution.hs`, `Tableau.hs`, `Unification.hs` | Dependency-free resolution prover, tableau prover with counter-models, unification | +| `src/REPL.hs` | Interactive session state and commands | +| `src/LSP.hs`, `app-lsp/Main.hs` | JSON-RPC language server over stdio, and its standalone executable | +| `editors/vscode/` | VS Code extension: grammar, snippets, LSP client | + +## Frontend and loader + +- **Grammar.** Top-level forms are `def-concept`, `def-property`, `def-relation`, + `def-axiom` (and bare `forall` / `exists` axioms), `namespace` and `import`. + Formulas use `forall`, `exists`, `implies`, `iff`, `and`, `or`, `not`, equality, + comparison operators (`gt`, `gte`, `lt`, `lte`) over signed numeric literals, + and strings. See the [language reference](user-guide/language-reference.md). +- **Positions.** The parser records a `SourceTable` so lint findings can be + reported as `file:line:col: error: ...` and so the language server can place + diagnostics and resolve jump-to-definition. +- **Imports.** `Loader.hs` resolves `(import "...")` recursively. It tracks the + chain of files being visited (a repeat is reported as a circular import with + the cycle spelled out) and a finished set (a diamond import is loaded once). + Search order for a relative import: the importing file's directory first, then + `$ONTOLOGIC_PATH` (`:`-separated), the directory beside the binary, the package + data directory, `./ontologic-lib`, and the current directory last. Extra + directories come from the repeatable `--lib-path DIR`. Searching the current + directory last means a stray local file cannot shadow a standard-library + module. Absolute paths bypass the search. + +## Core data model + +`Registry` (in `OntoLogic.hs`) is the single source of truth after parsing: +concepts with parents, properties with domain and type, relations with domain, +range and cardinality, axioms as `FOL` trees, namespace declarations and import +declarations. Everything downstream reads it; nothing mutates it except the REPL, +which appends parsed forms. +## Linter + +`lintRegistryDiagnosticsWithSource` checks, in order of concern: + +1. Parent concepts, property domains and relation endpoints are declared + (symbol-table integrity). +2. The taxonomy has no cycles (depth-first search). +3. No duplicate concept or property definitions. +4. No direct contradiction inside one axiom (`P and not P`). +5. Cross-axiom numeric intervals per concept and property are not empty. +6. `Linter/SAT.hs` encodes propositional structure and uses Horn propagation or + DPLL to catch contradictions and incoherent concepts that no single check + sees, reporting a derivation chain. + +With `--warn-unmapped`, axioms that cannot become simple property constraints are +listed per target instead of being dropped silently. + +## ModelIR + +`compileRegistry` in `IR.hs` flattens the registry into `ModelIR`: + +```mermaid +flowchart LR + REG["Registry"] --> CC["CompiledClass
topologically sorted,
inherited + direct properties"] + REG --> CP["CompiledProperty
typed, with BoundConstraint"] + REG --> CR["CompiledRelation"] + REG --> UM["irUnmappedAxioms
non-ground axioms with no
simple-constraint mapping"] + CC --> EMIT["Emitters"] + CP --> EMIT + CR --> EMIT + UM --> W["formatUnmappedWarning
(per-target comment style)"] ``` - ┌─────────────────┐ ┌───────────────┐ ┌─────────────┐ ┌──────────────┐ - │ .logic File │ ───> │ Megaparsec │ ───> │ Linter (DFS │ ───> │ Emitters │ - │ (S-expressions) │ │ parser │ │ / Contrad.) │ │ (Java, Py, │ - └─────────────────┘ └───────────────┘ └─────────────┘ │ Neo4j, etc.) │ - └──────────────┘ + +Bounds are normalized and inherited down the hierarchy. Unmapped axioms are +reported in a comment using each target's own comment syntax; JSON has none, so +`jsonschema` reports them on the CLI only. + +## Emitters and the target registry + +`Targets.hs` defines `Target { targetName, targetAliases, targetLabel, +targetWarnAs, targetEmit }` and one `targets` list. The CLI (`-t`), the REPL +(`:emit`) and the help text all read that list, so adding a format is one new +module plus one row. + +| Family | Targets (aliases) | Output | Module | +| :--- | :--- | :--- | :--- | +| Application languages | `java` | one `.java` per concept, plus `package-info.java` for warnings | `Java.hs` | +| | `python` | `models.py` (Pydantic v2) | `Python.hs` | +| | `rust` | `models.rs` | `Rust.hs` | +| | `go` (`golang`) | `models.go` | `Go.hs` | +| | `ts` (`typescript`, `zod`) | `models.ts` | `TypeScript.hs` | +| | `cpp` (`c++`) | `models.hpp` (C++20) | `Cpp.hs` | +| Schemas and contracts | `sql` (`postgres`, `postgresql`, `ddl`) | `schema.sql` | `Sql.hs` | +| | `graphql` (`gql`) | `schema.graphql` | `GraphQL.hs` | +| | `openapi` | `openapi.yaml` (3.1) | `OpenApi.hs` | +| | `jsonschema` (`json`) | `schema.json` (2020-12) | `JsonSchema.hs` | +| | `protobuf` (`proto`, `proto3`) | `schema.proto` | `Protobuf.hs` | +| Knowledge and proof | `owl` | `ontology.owl` | `Owl.hs` | +| | `shacl` | `shapes.ttl` | `Shacl.hs` | +| | `neo4j` | `graph.cypher`, `constraints.cypher` (`--neo4j-edition`) | `Neo4j.hs` | +| | `smt` (`smtlib`) | `spec.smt2` | `SMT.hs` | +| | `tptp` (`p`, `fof`) | `theory.p` | `TPTP.hs` | +| Diagrams | `mermaid` | `class_diagram.mmd` | `Mermaid.hs` | +| | `d2` | `diagram.d2` | `D2.hs` | + +`--render` shells out to `mmdc` or `d2` using argument vectors, never a shell +string. OWL and SHACL take their base IRI from `--base-iri`, otherwise from the +first declared namespace. + +The four non-emitter modes (`lint`, `solve`, `repl`, `lsp`) are handled in +`Main.hs`, not the registry. For per-target details see +[targets and emitters](user-guide/targets-and-emitters.md). + +## Solvers and provers + +```mermaid +flowchart TD + Q["Question
consistent? A subsumed by B? empty concepts? unsat core?"] --> PS["resolveProver
z3, cvc5, vampire, native, auto"] + PS -- "z3 / cvc5" --> SMT["Emitters/SMT.hs + FOLTheory.hs
SMT-LIB2 over stdin"] + PS -- vampire --> TP["Emitters/TPTP.hs
TPTP FOF"] + PS -- native --> NP["Clausify -> CNF ->
Prover.Resolution / Tableau"] + PS -- auto --> AU["try Z3, then CVC5, then Vampire"] + AU -- "none installed" --> NP + SMT --> R["SolverResult:
Sat model, Unsat, Unknown, SolverError"] + TP --> R + NP --> R ``` -### 1. Frontend Parser (Megaparsec) -The parser in [`src/Parser.hs`](src/Parser.hs) scans Lisp-style S-expressions from `.logic` files and processes three main blocks: -- **Taxonomy Concepts**: Declared via `(def-concept Name [Parent])`. -- **Property Schemas**: Declared via `(def-property Name Domain ConceptType)`. -- **Logical Axioms**: Declarative constraints represented in quantified First-Order Logic (FOL). - -### 2. Intermediate Representation (IR) -The intermediate representation is defined in [`src/OntoLogic.hs`](src/OntoLogic.hs): -- `FOL`: Represents first-order logical terms, including variables, constants, quantifiers (`forall`, `exists`), implications (`implies`), double-implications (`iff`), conjunctions (`and`), disjunctions (`or`), and negations (`not`). -- `Property`: Tracks field mappings (name, domain class, and range type). -- `Registry`: Keeps a centralized "Single Source of Truth" repository of concepts, properties, and axioms. - -### 3. Static Linter Validation -The linter in [`src/Linter.hs`](src/Linter.hs) verifies the registry: -- **Circular Inheritance Check**: Employs a Depth-First Search (DFS) on the taxonomy DAG. If any child concept inherits from itself through a parent chain (e.g. `A -> B -> A`), the compile fails. -- **Axiom Contradiction Checker**: Inspects axioms for immediate logical contradictions (such as `P and (Not P)`). - -### 4. Code Generation Emitters -The backend backends reside in `src/Emitters/` and translate the parsed registry into platform-specific structures: -* **Java Emitter**: Writes distinct `.java` files for each concept. Maps properties to private fields and binds range limits to Jakarta validation annotations (`@Min`, `@Max`, `@NotNull`). -* **Python Emitter**: Writes a `models.py` file with Pydantic class structures and binds range constraints to Pydantic `Field` arguments (e.g., `Field(gt=...)`). -* **Neo4j Emitter**: Emits a Cypher script (`graph.cypher`) containing schema indexes, `SUBCLASS_OF` subclass nodes, and validation queries to audit the data. -* **OWL Emitter**: Generates standard RDF/XML ontological specifications mapping concepts to OWL classes and properties. -* **Mermaid / D2 Emitters**: Generates visual diagrams representing the concept hierarchy and properties. +- **Backends.** Z3, CVC5 and Vampire run as external processes fed on stdin. + `NativeProver` runs in-process on the clausified theory and needs no external + binary. `auto` (the default) tries each external prover that is installed and + falls back to native, so `--solve` works on a bare machine. +- **Questions.** Whole-ontology consistency, subsumption (`A` implies `B`, + checked as the unsatisfiability of the negated goal; `sat` yields a + counterexample), empty-concept detection (coherence), unsat-core explanation + and model extraction. +- **Limits.** `--solve-timeout` is enforced on every backend, with a wall-clock + grace period; `--solve-memory` applies to Z3 only and warns otherwise. +- **Coverage honesty.** Axioms the encoding cannot express are listed before the + verdict (`untranslatedAxioms`) rather than skipped silently. +- **Exit codes.** `0` consistent and coherent, `1` unsatisfiable, empty concept + or solver error, `2` the solver answered unknown. + +## REPL + +`REPL.hs` keeps a `Registry`, the loaded file, the active prover and emit +options. Commands: `:load`, `:show`, `:lint`, `:prover`, `:cnf`, `:solve` / +`:check`, `:explain`, `:model`, `:prove A B`, `:unsat`, `:ir`, `:emit `, +`:set`, `:clear`, `:help`, `:quit`. Anything starting with `(` is parsed and +added to the session. It reuses `Targets.targets`, the linter and the solver. + +## Language server and editors + +`LSP.hs` is a JSON-RPC 2.0 server over stdio with incremental document sync. It +re-parses and re-lints on `didOpen` / `didChange`, then publishes diagnostics. It +provides completion, hover, definition (following imports through the loader), +rename with prepare, document formatting, semantic tokens, and code actions. Three +commands (`ontologic.solve`, `ontologic.explainUnsat`, `ontologic.inspectModel`) +run the solver asynchronously so the editor stays responsive. It ships as +`ontologic --lsp` and as the `ontologic-lsp` executable (`app-lsp/Main.hs`). The +VS Code extension in `editors/vscode/` bundles the TextMate grammar, snippets and +the client. See [editor and LSP](user-guide/editor-and-lsp.md). + +## Security design + +- **No shell evaluation.** External tools (`z3`, `cvc5`, `vampire`, `mmdc`, `d2`) + are launched with argument vectors, never `sh -c` strings. +- **Identifier sanitization.** Names such as `ocsf:FileActivity` or + `nist-ai:AISystem` become legal identifiers in each target language. +- **Escaping.** Emitters escape string literals for their target language + (for example Java, Go and Rust strings and Cypher literals). +- **Bounded external work.** Solver runs have timeouts, and the native provers + run under a configurable limit. +- **Secrets from the environment.** Integration scripts and Docker files read + credentials such as `NEO4J_AUTH` from environment variables. + +## Related + +- [Purpose](purpose.md), [Using OntoLogic](using.md), + [Standard library](standard-library.md), [Developer notes](dev/README.md) diff --git a/docs/dev/README.md b/docs/dev/README.md new file mode 100644 index 0000000..fcdb506 --- /dev/null +++ b/docs/dev/README.md @@ -0,0 +1,37 @@ +# Developer and Internal Notes + +Working material for people changing OntoLogic itself: plans, reviews, design +discussion, benchmarks and the test-coverage audit. These are records of how the +project got here, not user documentation; for that see the +[documentation index](../README.md). + +Some documents are snapshots. Check the current code and +[`CHANGELOG.md`](../../CHANGELOG.md) before acting on a recommendation. + +## Index + +| Area | Document | What it is | +| :--- | :--- | :--- | +| Roadmap input | [Suggested Improvements](SUGGESTED_IMPROVEMENTS.md) | Architectural review, bug audit, semantic gaps and a prioritized modernization list | +| Quality | [Test Coverage](TEST_COVERAGE.md) | Test-suite coverage audit and gap list | +| Design notes | [Constraint considerations](design/constraint_considerations.md) | Whether to constrain FOL to Horn clauses; the profile-based architecture | +| | [Constraints and patterns](design/constraints_and_patterned.md) | Logical expressiveness compared with Horn clauses, and how formulas are parsed and linted | +| Reviews | [Gemini review](reviews/GEMINI_3_7_REVIEW.md) | AI-generated codebase, security and semantic-gap review with a phased roadmap | +| | [BFO review](reviews/AI_BFO_Review.md) | AI-generated critique of the ecosystem ontology against BFO principles | +| Benchmarks | [Native prover benchmarks](benchmarks/v1.7.0-native-prover-benchmarks.md) | Measurements for the built-in prover | +| Plans | [`plans/`](plans/) | Dated remediation and tech-debt plans (2026-09) | +| Implementation history | [Replay playbook](superpowers/REPLAY_PLAYBOOK.md) | Milestone-by-milestone learnings and a runbook to rebuild the project | +| | [`superpowers/plans/`](superpowers/plans/) | Formal implementation plans for each milestone | + +## Plans + +- [Codebase-wide review and remediation](plans/2026-09-26-codebase-wide-review-and-remediation.md) +- [FOL completeness and tech-debt plan](plans/2026-09-26-fol-completeness-and-tech-debt-plan.md) +- [v1.5.0 tech-debt remediation](plans/2026-09-27-v1.5.0-tech-debt-remediation.md) +- [v1.5.0 tech-debt implementation plan](plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md) + +## Before you push + +The required verification gates and architecture map for contributors are in +[`AGENTS.md`](../../AGENTS.md). In short, run +`stack test --ghc-options="-Wall -Werror"` locally first. diff --git a/docs/SUGGESTED_IMPROVEMENTS.md b/docs/dev/SUGGESTED_IMPROVEMENTS.md similarity index 86% rename from docs/SUGGESTED_IMPROVEMENTS.md rename to docs/dev/SUGGESTED_IMPROVEMENTS.md index 3b66b8e..ef4d31a 100644 --- a/docs/SUGGESTED_IMPROVEMENTS.md +++ b/docs/dev/SUGGESTED_IMPROVEMENTS.md @@ -7,7 +7,7 @@ This document provides a critical examination of **OntoLogic**, evaluating its a ## 1. Executive Summary & Intent vs. Execution Gap ### 1.1 Stated Intent -OntoLogic articulates a compelling value proposition in [docs/purpose_and_motivation.md](docs/purpose_and_motivation.md): +OntoLogic articulates a compelling value proposition in [docs/purpose.md](../purpose.md): - **Problem**: In distributed IoT/IIoT ecosystems (JVM gateways, Python edge devices, Neo4j digital twins), business rules and safety thresholds drift across platforms, causing silent validation bypasses and hazards. - **Solution**: A declarative "Logic-as-Code" compiler written in Haskell that uses a single First-Order Logic (FOL) specification (`.logic`) to statically verify mathematical consistency and transpile native, zero-overhead validation models across Java, Python, Neo4j, and OWL. @@ -33,7 +33,7 @@ While the project demonstrates a clean end-to-end proof-of-concept pipeline (Lis ``` 1. **The "Illusion of Safety" Antipattern**: - The compiler accepts rich FOL expressions (such as existentials in [examples/bfo_unified.logic](examples/bfo_unified.logic) or access rules in [examples/security_policy.logic](examples/security_policy.logic)), reports `✅ Logic Validated successfully.`, but the emitters silently discard them. The developer believes their safety rules are enforced, but the generated models are empty stubs. + The compiler accepts rich FOL expressions (such as existentials in [examples/bfo_unified.logic](../../examples/bfo_unified.logic) or access rules in [examples/security_policy.logic](../../examples/security_policy.logic)), reports `✅ Logic Validated successfully.`, but the emitters silently discard them. The developer believes their safety rules are enforced, but the generated models are empty stubs. 2. **Premise Stripping / Miscompilation**: When an axiom contains conditional premises—e.g., `(implies (and (Oven o) (is_active)) (gt temperature 100))`—the extractor strips `is_active` and emits `temperature > 100` as an **unconditional** constraint on all `Oven` instances. This turns conditional operational rules into false positives (e.g., flagging an inactive, cold oven as broken). 3. **TBox (Metamodel) vs. ABox (Instance) Confusion in Neo4j**: @@ -88,15 +88,15 @@ flowchart TD | Module | Primary Responsibility | Key Types / Functions | | :--- | :--- | :--- | -| [`src/OntoLogic.hs`](src/OntoLogic.hs) | Core IR, AST definitions, constraint extraction | [`data FOL`](src/OntoLogic.hs#L10-L18), [`data Registry`](src/OntoLogic.hs#L25-L29), [`getLocalConstraints`](src/OntoLogic.hs#L41-L57) | -| [`src/Parser.hs`](src/Parser.hs) | Lexing and recursive descent parsing of S-expressions | [`parseRegistry`](src/Parser.hs#L27-L33), [`parseFOL`](src/Parser.hs#L60-L70), [`parseTerm`](src/Parser.hs#L125-L130) | -| [`src/Linter.hs`](src/Linter.hs) | Static taxonomy cycle checks & formula contradiction audit | [`lintRegistry`](src/Linter.hs#L8-L10), [`checkCircularInheritance`](src/Linter.hs#L12-L23), [`checkRangeContradiction`](src/Linter.hs#L60-L84) | -| [`src/Emitters/Java.hs`](src/Emitters/Java.hs) | Code generator for Java POJOs with Jakarta validation | [`emitJava`](src/Emitters/Java.hs#L7-L9), [`emitFieldOrGetter`](src/Emitters/Java.hs#L26-L47) | -| [`src/Emitters/Python.hs`](src/Emitters/Python.hs) | Code generator for Python Pydantic v2 models | [`emitPython`](src/Emitters/Python.hs#L7-L11), [`mapConstraintToPydantic`](src/Emitters/Python.hs#L39-L50) | -| [`src/Emitters/Neo4j.hs`](src/Emitters/Neo4j.hs) | Cypher script generator (nodes, constraints, audit queries) | [`emitCypher`](src/Emitters/Neo4j.hs#L5-L14), [`emitAuditQuery`](src/Emitters/Neo4j.hs#L29-L35) | -| [`src/Emitters/Owl.hs`](src/Emitters/Owl.hs) | RDF/XML ontology representation | [`emitOwl`](src/Emitters/Owl.hs#L5-L11) | -| [`src/Emitters/Mermaid.hs`](src/Emitters/Mermaid.hs) & [`D2.hs`](src/Emitters/D2.hs) | Architectural diagram generators | [`emitMermaid`](src/Emitters/Mermaid.hs#L6-L12), [`emitD2`](src/Emitters/D2.hs#L6-L11) | -| [`src/Main.hs`](src/Main.hs) | CLI argument parsing, compilation driver, renderer execution | [`main`](src/Main.hs#L37-L50), [`processTarget`](src/Main.hs#L52-L87) | +| [`src/OntoLogic.hs`](../../src/OntoLogic.hs) | Core IR, AST definitions, constraint extraction | [`data FOL`](../../src/OntoLogic.hs#L10-L18), [`data Registry`](../../src/OntoLogic.hs#L25-L29), [`getLocalConstraints`](../../src/OntoLogic.hs#L41-L57) | +| [`src/Parser.hs`](../../src/Parser.hs) | Lexing and recursive descent parsing of S-expressions | [`parseRegistry`](../../src/Parser.hs#L27-L33), [`parseFOL`](../../src/Parser.hs#L60-L70), [`parseTerm`](../../src/Parser.hs#L125-L130) | +| [`src/Linter.hs`](../../src/Linter.hs) | Static taxonomy cycle checks & formula contradiction audit | [`lintRegistry`](../../src/Linter.hs#L8-L10), [`checkCircularInheritance`](../../src/Linter.hs#L12-L23), [`checkRangeContradiction`](../../src/Linter.hs#L60-L84) | +| [`src/Emitters/Java.hs`](../../src/Emitters/Java.hs) | Code generator for Java POJOs with Jakarta validation | [`emitJava`](../../src/Emitters/Java.hs#L7-L9), [`emitFieldOrGetter`](../../src/Emitters/Java.hs#L26-L47) | +| [`src/Emitters/Python.hs`](../../src/Emitters/Python.hs) | Code generator for Python Pydantic v2 models | [`emitPython`](../../src/Emitters/Python.hs#L7-L11), [`mapConstraintToPydantic`](../../src/Emitters/Python.hs#L39-L50) | +| [`src/Emitters/Neo4j.hs`](../../src/Emitters/Neo4j.hs) | Cypher script generator (nodes, constraints, audit queries) | [`emitCypher`](../../src/Emitters/Neo4j.hs#L5-L14), [`emitAuditQuery`](../../src/Emitters/Neo4j.hs#L29-L35) | +| [`src/Emitters/Owl.hs`](../../src/Emitters/Owl.hs) | RDF/XML ontology representation | [`emitOwl`](../../src/Emitters/Owl.hs#L5-L11) | +| [`src/Emitters/Mermaid.hs`](../../src/Emitters/Mermaid.hs) & [`D2.hs`](../../src/Emitters/D2.hs) | Architectural diagram generators | [`emitMermaid`](../../src/Emitters/Mermaid.hs#L6-L12), [`emitD2`](../../src/Emitters/D2.hs#L6-L11) | +| [`src/Main.hs`](../../src/Main.hs) | CLI argument parsing, compilation driver, renderer execution | [`main`](../../src/Main.hs#L37-L50), [`processTarget`](../../src/Main.hs#L52-L87) | --- @@ -107,7 +107,7 @@ flowchart TD > Status of later sections is tracked in `.planning/ROADMAP.md`. ### 3.1 OWL Emitter Produces Malformed XML -- **Location**: [`src/Emitters/Owl.hs:13-20`](src/Emitters/Owl.hs#L13-L20) +- **Location**: [`src/Emitters/Owl.hs:13-20`](../../src/Emitters/Owl.hs#L13-L20) - **Defect**: The root XML tag ``: ```haskell xmlHeader = "\n= 50`, the hierarchy is unsatisfiable, but the linter never aggregates inherited constraints. - **Improvement**: Aggregate all constraints per concept across all axioms and the inheritance chain into an interval map $[min, max]$. Check for empty intervals ($min > max$). diff --git a/docs/TEST_COVERAGE.md b/docs/dev/TEST_COVERAGE.md similarity index 100% rename from docs/TEST_COVERAGE.md rename to docs/dev/TEST_COVERAGE.md diff --git a/docs/benchmarks/v1.7.0-native-prover-benchmarks.md b/docs/dev/benchmarks/v1.7.0-native-prover-benchmarks.md similarity index 100% rename from docs/benchmarks/v1.7.0-native-prover-benchmarks.md rename to docs/dev/benchmarks/v1.7.0-native-prover-benchmarks.md diff --git a/docs/constraint_considerations.md b/docs/dev/design/constraint_considerations.md similarity index 100% rename from docs/constraint_considerations.md rename to docs/dev/design/constraint_considerations.md diff --git a/docs/constraints_and_patterned.md b/docs/dev/design/constraints_and_patterned.md similarity index 93% rename from docs/constraints_and_patterned.md rename to docs/dev/design/constraints_and_patterned.md index 4000695..3fb7915 100644 --- a/docs/constraints_and_patterned.md +++ b/docs/dev/design/constraints_and_patterned.md @@ -8,7 +8,7 @@ This document details the logical expressiveness of OntoLogic, how it differs fr OntoLogic is **not** restricted to Horn clauses (unlike Prolog or Datalog). -In [`src/OntoLogic.hs`](src/OntoLogic.hs), the abstract syntax tree (`FOL`) represents full First-Order Predicate Logic: +In [`src/OntoLogic.hs`](../../../src/OntoLogic.hs), the abstract syntax tree (`FOL`) represents full First-Order Predicate Logic: ```haskell data FOL = Predicate Name [Term] @@ -62,7 +62,7 @@ When a subclass $B$ (where $B \sqsubseteq A$) introduces extra constraints on a ## 4. Static Linter Validation -The static linter in [`src/Linter.hs`](src/Linter.hs) validates logic files before code generation: +The static linter in [`src/Linter.hs`](../../../src/Linter.hs) validates logic files before code generation: 1. **Taxonomy Cycle Check**: Detects circular inheritance chains (e.g., $A \sqsubseteq B \sqsubseteq A$). 2. **Propositional Contradictions**: Detects conjuncts containing $P \land \neg P$. diff --git a/docs/plans/2026-09-26-codebase-wide-review-and-remediation.md b/docs/dev/plans/2026-09-26-codebase-wide-review-and-remediation.md similarity index 100% rename from docs/plans/2026-09-26-codebase-wide-review-and-remediation.md rename to docs/dev/plans/2026-09-26-codebase-wide-review-and-remediation.md diff --git a/docs/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md b/docs/dev/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md similarity index 100% rename from docs/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md rename to docs/dev/plans/2026-09-26-fol-completeness-and-tech-debt-plan.md diff --git a/docs/plans/2026-09-27-v1.5.0-tech-debt-remediation.md b/docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md similarity index 100% rename from docs/plans/2026-09-27-v1.5.0-tech-debt-remediation.md rename to docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md diff --git a/docs/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md b/docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md similarity index 96% rename from docs/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md rename to docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md index 33d02bc..024fdac 100644 --- a/docs/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md +++ b/docs/dev/plans/2026-09-28-v1.5.0-tech-debt-implementation-plan.md @@ -10,7 +10,7 @@ ## Phase 1: Fix DPLL Dead Code Bug (Critical, 3 minutes) ### Problem -[`src/Linter/SAT.hs` lines 364-370](src/Linter/SAT.hs#L364-L370): The DPLL branch always returns `[]` regardless of result — the `else` clause is identical to `then`: +[`src/Linter/SAT.hs` lines 364-370](../../../src/Linter/SAT.hs#L364-L370): The DPLL branch always returns `[]` regardless of result — the `else` clause is identical to `then`: ```haskell -- CURRENT (BROKEN): @@ -170,7 +170,7 @@ perf: replace O(n²) nub with O(n log n) nubOrd across core modules ## Phase 3: Sort-Aware Typed Quantifier Translation (10 minutes) ### Problem -[`src/FOLTheory.hs` line 190](src/FOLTheory.hs#L189-L194): `resolveSort "Tank" → "Entity"` when Tank is a declared concept. This erases sort info. A `TypedForAll v "Tank" body` should emit a guarded quantifier: `(forall ((v Entity)) (=> (is_Tank v) ))`. +[`src/FOLTheory.hs` line 190](../../../src/FOLTheory.hs#L189-L194): `resolveSort "Tank" → "Entity"` when Tank is a declared concept. This erases sort info. A `TypedForAll v "Tank" body` should emit a guarded quantifier: `(forall ((v Entity)) (=> (is_Tank v) ))`. ### File: `src/FOLTheory.hs` @@ -263,7 +263,7 @@ feat(fol): emit guarded quantifiers for concept-sorted typed variables ## Phase 4: Support User-Defined Unary Predicates in FOLTheory (8 minutes) ### Problem -[`src/FOLTheory.hs` line 222-226](src/FOLTheory.hs#L222-L226): `predicate name [Var v]` only succeeds if `name` is a known concept or boolean property. User-defined unary predicates like `(Hazardous x)` where `Hazardous` is not `def-concept` fail with `"unsupported predicate Hazardous/1"`. +[`src/FOLTheory.hs` line 222-226](../../../src/FOLTheory.hs#L222-L226): `predicate name [Var v]` only succeeds if `name` is a known concept or boolean property. User-defined unary predicates like `(Hazardous x)` where `Hazardous` is not `def-concept` fail with `"unsupported predicate Hazardous/1"`. ### File: `src/FOLTheory.hs` @@ -629,7 +629,7 @@ test(lsp): add multi-change and multi-line incremental sync tests version: 1.5.0 ``` -### File: `docs/plans/2026-09-27-v1.5.0-tech-debt-remediation.md` +### File: `docs/dev/plans/2026-09-27-v1.5.0-tech-debt-remediation.md` Create this file with a summary of what was fixed: diff --git a/docs/AI_BFO_Review.md b/docs/dev/reviews/AI_BFO_Review.md similarity index 100% rename from docs/AI_BFO_Review.md rename to docs/dev/reviews/AI_BFO_Review.md diff --git a/docs/GEMINI_3_7_REVIEW.md b/docs/dev/reviews/GEMINI_3_7_REVIEW.md similarity index 96% rename from docs/GEMINI_3_7_REVIEW.md rename to docs/dev/reviews/GEMINI_3_7_REVIEW.md index 36ed588..8ad0c9d 100644 --- a/docs/GEMINI_3_7_REVIEW.md +++ b/docs/dev/reviews/GEMINI_3_7_REVIEW.md @@ -36,7 +36,7 @@ To evolve OntoLogic from an impressive prototype into a production-grade compile ## 2. Critical Security & Soundness Vulnerabilities ### 🔴 SEC-01: Command Injection in CLI Image Rendering -* **Location:** [`src/Main.hs:94`](src/Main.hs#L94), [`src/Main.hs:103`](src/Main.hs#L103) +* **Location:** [`src/Main.hs:94`](../../../src/Main.hs#L94), [`src/Main.hs:103`](../../../src/Main.hs#L103) * **Vulnerability:** `Main.hs` uses `System.Process.callCommand` to invoke external tools (`mmdc` and `d2`). Because `callCommand` passes strings directly to the system shell (`/bin/sh -c`), any unescaped file path, target name, or `--output` argument containing shell metacharacters (`;`, `&&`, `|`, `` ` ``) results in arbitrary command execution: ```haskell -- VULNERABLE: @@ -59,7 +59,7 @@ To evolve OntoLogic from an impressive prototype into a production-grade compile --- ### 🟠 SEC-02: Cypher Injection & Identifier Interpolation -* **Location:** [`src/Emitters/Neo4j.hs:17, 34, 50`](src/Emitters/Neo4j.hs#L17) +* **Location:** [`src/Emitters/Neo4j.hs:17, 34, 50`](../../../src/Emitters/Neo4j.hs#L17) * **Vulnerability:** Concept names, property names, and literal values are concatenated directly into Cypher script blocks without escaping or quoting sanitization: ```haskell -- VULNERABLE: @@ -72,7 +72,7 @@ To evolve OntoLogic from an impressive prototype into a production-grade compile --- ### 🟠 COR-01: Unchecked File IO & Non-Graceful Exits -* **Location:** [`src/Main.hs:49, 56, 60, 64, 68, 73, 81, 87`](src/Main.hs#L49) +* **Location:** [`src/Main.hs:49, 56, 60, 64, 68, 73, 81, 87`](../../../src/Main.hs#L49) * **Issues:** 1. **Runtime `error` vs `exitFailure`:** On lint validation failure, line 49 executes `error "Validation Failed."`. In Haskell, `error` raises an unhandled runtime exception with a call stack trace rather than cleanly exiting with status code 1. 2. **Missing Parent Directory Creation:** When writing output files (`writeFile (out ++ "/models.py") ...`), if directory `out` does not exist, the runtime crashes with an `IOException`. @@ -109,7 +109,7 @@ To evolve OntoLogic from an impressive prototype into a production-grade compile #### Problem Analysis 1. **Premise Stripping Bug:** - In [`src/OntoLogic.hs:51-53`](src/OntoLogic.hs#L51-L53), `matchesConcept` evaluates: + In [`src/OntoLogic.hs:51-53`](../../../src/OntoLogic.hs#L51-L53), `matchesConcept` evaluates: ```haskell matchesConcept (Predicate name [Var _]) = name == conceptName matchesConcept (And p1 p2) = matchesConcept p1 || matchesConcept p2 @@ -142,7 +142,7 @@ Throughout the core compiler, strings are used where strongly-typed algebraic da | `Registry.concepts :: [(Name, Maybe Name)]` | Association list; O(N) lookup; allows duplicate keys | `data ConceptHierarchy = ConceptHierarchy { parents :: Map ConceptName (Maybe ConceptName) }` | #### Concrete Impact: -In [`src/Emitters/Java.hs:68-70`](src/Emitters/Java.hs#L68-L70): +In [`src/Emitters/Java.hs:68-70`](../../../src/Emitters/Java.hs#L68-L70): ```haskell mapType "Integer" = "Integer" mapType "Boolean" = "boolean" @@ -192,7 +192,7 @@ Emitters then become pure, simple rendering views over `CompiledClass`, eliminat --- ### 4.2 Hardcoded Vendor Packaging -In [`src/Emitters/Java.hs:16`](src/Emitters/Java.hs#L16): +In [`src/Emitters/Java.hs:16`](../../../src/Emitters/Java.hs#L16): ```haskell "package com.acme.generated;\n" ``` @@ -254,11 +254,11 @@ gantt ### Phase 1: Security & Immediate Hardening (High Priority) 1. **Fix Command Injection:** - Replace `callCommand` in [`src/Main.hs`](src/Main.hs) with `callProcess` for `mmdc` and `d2`. + Replace `callCommand` in [`src/Main.hs`](../../../src/Main.hs) with `callProcess` for `mmdc` and `d2`. 2. **Directory & Error Handling:** Add `createDirectoryIfMissing True` before file emission; replace `error` with `die` / `exitFailure`. 3. **Sanitize Cypher Generation:** - Escape string literals and sanitize concept/property names in [`src/Emitters/Neo4j.hs`](src/Emitters/Neo4j.hs). + Escape string literals and sanitize concept/property names in [`src/Emitters/Neo4j.hs`](../../../src/Emitters/Neo4j.hs). 4. **Establish GitHub Actions CI:** Add `.github/workflows/ci.yml` running `stack test --ghc-options="-Wall -Werror"` and Gradle verification. diff --git a/docs/superpowers/REPLAY_PLAYBOOK.md b/docs/dev/superpowers/REPLAY_PLAYBOOK.md similarity index 92% rename from docs/superpowers/REPLAY_PLAYBOOK.md rename to docs/dev/superpowers/REPLAY_PLAYBOOK.md index 99a7ebb..ecec234 100644 --- a/docs/superpowers/REPLAY_PLAYBOOK.md +++ b/docs/dev/superpowers/REPLAY_PLAYBOOK.md @@ -6,70 +6,70 @@ This document is the **central master reference** for OntoLogic. It consolidates ## 📑 Central Plans Index -All formal implementation plans are preserved under `docs/superpowers/plans/`: +All formal implementation plans are preserved under `docs/dev/superpowers/plans/`: -1. **[Milestone 1: OntoLogic Core Improvements](docs/superpowers/plans/2026-09-05-ontologic-core-improvements.md)** +1. **[Milestone 1: OntoLogic Core Improvements](plans/2026-09-05-ontologic-core-improvements.md)** *Scope:* Fixes OWL XML emitter syntax, introduces topological sorting for Python class definitions, decouples Neo4j TBox/ABox metamodel nodes, adds signed number Megaparsec support, supports Float/Double constraints in Java & Python, implements semantic symbol table validation in the linter, and adds cross-axiom interval contradiction checking. *Pull Request:* [#2 on GitHub](https://github.com/bsommers/OntoLogic/pull/2) -2. **[Milestone 2: Robust Testing Suite](docs/superpowers/plans/2026-09-05-robust-test-suite.md)** +2. **[Milestone 2: Robust Testing Suite](plans/2026-09-05-robust-test-suite.md)** *Scope:* Fixes latent semantic defects in example domain models, adds unit tests for visualizer emitters (Mermaid & D2), adds an integration test suite validating all 12 example `.logic` models against all emitters, validates target code syntax (Python `ast.parse`, OWL XML well-formedness, `javac`), implements runtime validation behavior tests (Pydantic instantiation, Java Bean validation), and adds CLI ergonomic driver tests. -3. **[Milestone 3: Security Hardening, Error Handling & CI](docs/superpowers/plans/2026-09-07-security-and-hardening-fixes.md)** +3. **[Milestone 3: Security Hardening, Error Handling & CI](plans/2026-09-07-security-and-hardening-fixes.md)** *Scope:* Eliminates shell command injection via `callProcess`, sanitizes Cypher string values and identifiers, exits cleanly on validation failure and unknown targets without call stacks, supports configurable Java packages via `--java-package`, cleans stale binaries and dead dependencies, and establishes GitHub Actions CI. -4. **[Milestone 4: Type System Refactoring & Compiler Intermediate Representation (IR)](docs/superpowers/plans/2026-09-13-type-system-and-model-ir.md)** +4. **[Milestone 4: Type System Refactoring & Compiler Intermediate Representation (IR)](plans/2026-09-13-type-system-and-model-ir.md)** *Scope:* Replaces stringly-typed attributes with formal Haskell ADTs (`PropertyType`, `CompOp`, `Value`), introduces a formal `ModelIR` compilation layer (`src/IR.hs`), decouples emitters into pure rendering views, handles conditional premise rules, and adds property-based fuzz testing. *Pull Request:* [#3 on GitHub](https://github.com/bsommers/OntoLogic/pull/3) -5. **[Milestone 5: Multi-Entity Relational Axioms & Graph Transpilation](docs/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md)** +5. **[Milestone 5: Multi-Entity Relational Axioms & Graph Transpilation](plans/2026-09-13-relational-axioms-and-graph-transpilation.md)** *Scope:* Extends AST and parser to support binary relations `(def-relation ...)` and multi-variable logic, introduces `CompiledRelation` to `ModelIR`, emits rich Neo4j relationship schemas, W3C OWL `owl:ObjectProperty`, OOP association fields, and visualizer relationship arrows. *Pull Request:* [#4 on GitHub](https://github.com/bsommers/OntoLogic/pull/4) -6. **[Milestone 6: Modular Namespacing & Multi-File Imports](docs/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md)** +6. **[Milestone 6: Modular Namespacing & Multi-File Imports](plans/2026-09-14-modular-namespacing-and-imports.md)** *Scope:* Implements `(import "path/to/file.logic")` and `(namespace "prefix")` syntax, recursive file import dependency loader with cycle detection, diamond deduplication, and qualified symbol resolution. *Pull Request:* [#5 on GitHub](https://github.com/bsommers/OntoLogic/pull/5) -7. **[Milestone 7: 3-Tier Foundation: BFO 2020, CCO & UCO Standard Library](docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** +7. **[Milestone 7: 3-Tier Foundation: BFO 2020, CCO & UCO Standard Library](plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** *Scope:* Establishes standard library foundation in `ontologic-lib/` with Basic Formal Ontology (BFO 2020), Common Core Ontologies (CCO Core), and Unified Cybersecurity Ontology (UCO Observables). Adds identifier sanitization (`sanitizeIdent`) across Java and Python emitters for colon and hyphen namespaces. *Pull Request:* [#6 on GitHub](https://github.com/bsommers/OntoLogic/pull/6) -8. **[Milestone 8: Cyber Threat Intelligence & MITRE Integration](docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** +8. **[Milestone 8: Cyber Threat Intelligence & MITRE Integration](plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** *Scope:* Formalizes STIX 2.1 / CVE / CWE vulnerability models (`stix_cve.logic`), MITRE ATT&CK Enterprise matrix (`mitre_attack.logic`), and MITRE D3FEND defensive countermeasures (`mitre_d3fend.logic`) with graph transpilation and CVSS / EPSS range constraints. *Pull Request:* [#7 on GitHub](https://github.com/bsommers/OntoLogic/pull/7) -9. **[Milestone 9: AI Governance, Safety & Adversarial Threat Modeling](docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** +9. **[Milestone 9: AI Governance, Safety & Adversarial Threat Modeling](plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** *Scope:* Implements MITRE ATLAS AI attack vectors (`mitre_atlas.logic`), NIST AI RMF 1.0 governance framework (`nist_ai_rmf.logic`), and ISO/IEC 42001 & EU AI Act compliance ontologies (`iso_42001_eu_ai_act.logic`) with quantitative risk and autonomy level constraints. *Pull Request:* [#8 on GitHub](https://github.com/bsommers/OntoLogic/pull/8) -10. **[Milestone 10: Cyber GRC & Automated Compliance-as-Code](docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** +10. **[Milestone 10: Cyber GRC & Automated Compliance-as-Code](plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** *Scope:* Encodes NIST CSF 2.0 (`nist_csf.logic`) and NIST SP 800-53 Rev 5 / OSCAL Baselines (`nist_sp800_53.logic`) with control hierarchy, implementation status, satisfaction relationships, and graph compliance checking. *Pull Request:* [#9 on GitHub](https://github.com/bsommers/OntoLogic/pull/9) -11. **[Milestone 11: Real-Time Security Telemetry & Monitoring (OCSF & SIGMA)](docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** +11. **[Milestone 11: Real-Time Security Telemetry & Monitoring (OCSF & SIGMA)](plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md)** *Scope:* Encodes OCSF v1.1.0 security telemetry taxonomy (`ocsf_schema.logic`) and SIGMA detection rules with SIEM semantics (`sigma_rules.logic`), enabling full-stack real-time event validation, attack technique correlation, and defensive telemetry graphing. -12. **[Milestone 12: Web/API Emitters, SMT-LIB2 Verification & Interactive REPL](docs/superpowers/REPLAY_PLAYBOOK.md)** +12. **[Milestone 12: Web/API Emitters, SMT-LIB2 Verification & Interactive REPL](REPLAY_PLAYBOOK.md)** *Scope:* Implements TypeScript/Zod runtime schemas, OpenAPI 3.1 YAML component specs, GraphQL SDL types and query schema, SMT-LIB2 / Z3 theorem prover verification backend, interactive command-line REPL (`ontologic --repl`), and patches all security scan findings to achieve Grade A (98/100). *Pull Request:* [#13 on GitHub](https://github.com/bsommers/OntoLogic/pull/13) -13. **[Milestone 13: Live Z3 SMT Theorem Prover & Language Server Protocol (LSP) Engine](docs/superpowers/REPLAY_PLAYBOOK.md)** +13. **[Milestone 13: Live Z3 SMT Theorem Prover & Language Server Protocol (LSP) Engine](REPLAY_PLAYBOOK.md)** *Scope:* Implements live Z3 SMT solver execution (`Solver.hs`), whole-ontology consistency checking, taxonomic subsumption proofs ($A \sqsubseteq B$), empty concept detection, and a full JSON-RPC stdio Language Server Protocol server (`LSP.hs`, `ontologic-lsp`) providing diagnostics, autocompletion, hover docs, and jump-to-definition. *Pull Request:* [#14 on GitHub](https://github.com/bsommers/OntoLogic/pull/14) -14. **[Milestone 14: Official VS Code Extension & Marketplace Packaging](docs/superpowers/REPLAY_PLAYBOOK.md)** +14. **[Milestone 14: Official VS Code Extension & Marketplace Packaging](REPLAY_PLAYBOOK.md)** *Scope:* Implements full Visual Studio Code extension package (`editors/vscode/`) with TextMate syntax grammar (`syntaxes/ontologic.tmLanguage.json`), bracket matching and auto-closing configuration, code snippets for concepts/relations/axioms, Language Server Protocol client activation, and interactive command palette actions for SMT solver checking. Bundles standalone `ontologic-1.0.0.vsix`. -15. **[Milestone 15: Multi-Prover SMT Solver Backend (Z3, CVC5, Vampire, Auto)](docs/superpowers/REPLAY_PLAYBOOK.md)** +15. **[Milestone 15: Multi-Prover SMT Solver Backend (Z3, CVC5, Vampire, Auto)](REPLAY_PLAYBOOK.md)** *Scope:* Enhances `Solver.hs`, CLI (`--prover` / `-p`), and REPL (`:prover `) with pluggable theorem prover backends supporting **Z3**, **CVC5**, **Vampire**, and automated multi-solver discovery with fallback. Validated against live Z3 and CVC5 binaries with 211 passing tests. -16. **[Future Capabilities & Target Emitters Master Plan](docs/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md)** +16. **[Future Capabilities & Target Emitters Master Plan](plans/2026-09-14-future-capabilities-and-target-emitters.md)** *Scope:* Detailed specifications and test plans for SPARQL 1.1 graph query emitter, Protocol Buffers v3 / gRPC contract emitter, SQL DDL relational schema generator with CHECK constraints, and WebAssembly (WASM) interactive browser studio. -17. **[Initial Recommendations Implementation Plan](docs/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md)** +17. **[Initial Recommendations Implementation Plan](plans/2026-07-18-implement-ontologic-recommendations.md)** *Scope:* Baseline implementation of early emitters and architectural recommendations. -18. **[Critical Architectural Audit & Suggested Improvements](docs/SUGGESTED_IMPROVEMENTS.md)** +18. **[Critical Architectural Audit & Suggested Improvements](../SUGGESTED_IMPROVEMENTS.md)** *Scope:* Deep-dive evaluation of the original codebase, analyzing intent versus implementation reality across grammar, AST, linter, emitters, and ecosystem integration. --- diff --git a/docs/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md b/docs/dev/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md similarity index 100% rename from docs/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md rename to docs/dev/superpowers/plans/2026-07-18-implement-ontologic-recommendations.md diff --git a/docs/superpowers/plans/2026-09-05-ontologic-core-improvements.md b/docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md similarity index 99% rename from docs/superpowers/plans/2026-09-05-ontologic-core-improvements.md rename to docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md index 0fd4a7d..6ee841b 100644 --- a/docs/superpowers/plans/2026-09-05-ontologic-core-improvements.md +++ b/docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md @@ -624,7 +624,7 @@ git commit -m "feat(cli): make output flag optional for lint and restore gradle ## Execution Handoff -Plan complete and saved to `docs/superpowers/plans/2026-09-05-ontologic-core-improvements.md`. Two execution options: +Plan complete and saved to `docs/dev/superpowers/plans/2026-09-05-ontologic-core-improvements.md`. Two execution options: **1. Subagent-Driven (recommended)** - I dispatch a fresh subagent per task, review between tasks, fast iteration **2. Inline Execution** - Execute tasks in this session using executing-plans, batch execution with checkpoints diff --git a/docs/superpowers/plans/2026-09-05-robust-test-suite.md b/docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md similarity index 99% rename from docs/superpowers/plans/2026-09-05-robust-test-suite.md rename to docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md index e134284..558e139 100644 --- a/docs/superpowers/plans/2026-09-05-robust-test-suite.md +++ b/docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md @@ -535,6 +535,6 @@ git commit -m "test: add comprehensive CLI driver test suite for arguments, flag ## Execution Handoff -Plan complete and saved to `docs/superpowers/plans/2026-09-05-robust-test-suite.md`. +Plan complete and saved to `docs/dev/superpowers/plans/2026-09-05-robust-test-suite.md`. Execute using Subagent-Driven Development with test-driven development, continuous verification, and final code review. diff --git a/docs/superpowers/plans/2026-09-07-security-and-hardening-fixes.md b/docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md similarity index 98% rename from docs/superpowers/plans/2026-09-07-security-and-hardening-fixes.md rename to docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md index 321ac28..ce79210 100644 --- a/docs/superpowers/plans/2026-09-07-security-and-hardening-fixes.md +++ b/docs/dev/superpowers/plans/2026-09-07-security-and-hardening-fixes.md @@ -227,7 +227,7 @@ Verify zero compiler warnings. ### Task 6: Final Verification, Central Documentation Sync & PR Update **Files:** -- Modify: `docs/superpowers/REPLAY_PLAYBOOK.md` +- Modify: `docs/dev/superpowers/REPLAY_PLAYBOOK.md` - Copy plan to root repo and sync `main` branch if appropriate. - [ ] **Step 1: Run complete verification battery** @@ -235,7 +235,7 @@ Verify zero compiler warnings. - `./gradlew clean build test` (Java build and JUnit 5 pass). - `./gradlew :app-java:run` (run app). -- [ ] **Step 2: Update `docs/superpowers/REPLAY_PLAYBOOK.md`** +- [ ] **Step 2: Update `docs/dev/superpowers/REPLAY_PLAYBOOK.md`** Record security hardening, Cypher sanitization, `callProcess`, and CI setup. - [ ] **Step 3: Commit and push** diff --git a/docs/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md b/docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md similarity index 84% rename from docs/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md rename to docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md index 4667437..6f12994 100644 --- a/docs/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md +++ b/docs/dev/superpowers/plans/2026-09-13-relational-axioms-and-graph-transpilation.md @@ -1,7 +1,7 @@ # Milestone 5 Plan: Multi-Entity Relational Axioms & Graph Transpilation > **Context:** Expands OntoLogic's compiler and intermediate representation to support cross-entity relationships (`(def-relation ...)` and multi-variable First-Order Logic predicates), transpiling them into Neo4j graph relationships, OWL Object Properties, OOP association references, and visualizer relationship arrows. -> **Tracking Document:** [`docs/superpowers/REPLAY_PLAYBOOK.md`](docs/superpowers/REPLAY_PLAYBOOK.md) +> **Tracking Document:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) --- @@ -22,7 +22,7 @@ ## 🧱 Architectural Specification -### 1. AST Extension in [`src/OntoLogic.hs`](src/OntoLogic.hs) +### 1. AST Extension in [`src/OntoLogic.hs`](../../../../src/OntoLogic.hs) ```haskell -- First-class binary relation connecting two concepts @@ -44,7 +44,7 @@ data Registry = Registry --- -### 2. Intermediate Representation Extension in [`src/IR.hs`](src/IR.hs) +### 2. Intermediate Representation Extension in [`src/IR.hs`](../../../../src/IR.hs) ```haskell data CompiledRelation = CompiledRelation @@ -117,12 +117,12 @@ class Sensor(BaseModel): ## 📋 Step-by-Step Execution Tasks ### Task 1: AST & Parser Extension -- [ ] Add `Relation` record to [`src/OntoLogic.hs`](src/OntoLogic.hs) and update `Registry` record with `relations :: [Relation]`. -- [ ] Implement `parseDefRelation :: Parser Item` in [`src/Parser.hs`](src/Parser.hs) matching `(def-relation )`. +- [ ] Add `Relation` record to [`src/OntoLogic.hs`](../../../../src/OntoLogic.hs) and update `Registry` record with `relations :: [Relation]`. +- [ ] Implement `parseDefRelation :: Parser Item` in [`src/Parser.hs`](../../../../src/Parser.hs) matching `(def-relation )`. - [ ] Support multi-variable quantifier parsing `(forall (s g) ...)` in `Parser.hs`. ### Task 2: Relational Semantic Linter -- [ ] Add `checkUndeclaredRelationEndpoints` in [`src/Linter.hs`](src/Linter.hs) ensuring both domain and range concepts are declared. +- [ ] Add `checkUndeclaredRelationEndpoints` in [`src/Linter.hs`](../../../../src/Linter.hs) ensuring both domain and range concepts are declared. - [ ] Add `checkDuplicateRelations` in `Linter.hs`. ### Task 3: Intermediate Representation (`src/IR.hs`) @@ -130,11 +130,11 @@ class Sensor(BaseModel): - [ ] Link relations to class properties for OOP targets (Java/Python) and graph targets (Neo4j/OWL/Mermaid/D2). ### Task 4: Emitter Transpilation -- [ ] **Neo4j:** Emit relationship schema edges between `:OntologyClass` nodes in [`src/Emitters/Neo4j.hs`](src/Emitters/Neo4j.hs). -- [ ] **OWL:** Emit `owl:ObjectProperty` in [`src/Emitters/Owl.hs`](src/Emitters/Owl.hs). -- [ ] **Mermaid & D2:** Emit directional association arrows in [`src/Emitters/Mermaid.hs`](src/Emitters/Mermaid.hs) and [`src/Emitters/D2.hs`](src/Emitters/D2.hs). -- [ ] **Java:** Emit typed reference getters/setters in [`src/Emitters/Java.hs`](src/Emitters/Java.hs). -- [ ] **Python:** Emit forward-referenced optional fields in [`src/Emitters/Python.hs`](src/Emitters/Python.hs). +- [ ] **Neo4j:** Emit relationship schema edges between `:OntologyClass` nodes in [`src/Emitters/Neo4j.hs`](../../../../src/Emitters/Neo4j.hs). +- [ ] **OWL:** Emit `owl:ObjectProperty` in [`src/Emitters/Owl.hs`](../../../../src/Emitters/Owl.hs). +- [ ] **Mermaid & D2:** Emit directional association arrows in [`src/Emitters/Mermaid.hs`](../../../../src/Emitters/Mermaid.hs) and [`src/Emitters/D2.hs`](../../../../src/Emitters/D2.hs). +- [ ] **Java:** Emit typed reference getters/setters in [`src/Emitters/Java.hs`](../../../../src/Emitters/Java.hs). +- [ ] **Python:** Emit forward-referenced optional fields in [`src/Emitters/Python.hs`](../../../../src/Emitters/Python.hs). ### Task 5: Testing & Verification - [ ] Add `test/RelationSpec.hs` testing parsing, linting, and multi-emitter code generation for relations. diff --git a/docs/superpowers/plans/2026-09-13-type-system-and-model-ir.md b/docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md similarity index 75% rename from docs/superpowers/plans/2026-09-13-type-system-and-model-ir.md rename to docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md index a7af12f..af2d2cb 100644 --- a/docs/superpowers/plans/2026-09-13-type-system-and-model-ir.md +++ b/docs/dev/superpowers/plans/2026-09-13-type-system-and-model-ir.md @@ -1,7 +1,7 @@ # Milestone 4 Plan: Type System Refactoring & Compiler Intermediate Representation (IR) > **Context:** Evolution from an ad-hoc pattern-matching emitter pipeline to a strongly typed compiler architecture with an Intermediate Representation (IR), premise-aware axiom extraction, and property-based verification. -> **Tracking Document:** [`docs/superpowers/REPLAY_PLAYBOOK.md`](docs/superpowers/REPLAY_PLAYBOOK.md) +> **Tracking Document:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) --- @@ -17,7 +17,7 @@ ## 🧱 Architectural Specification -### 1. Core ADTs in [`src/OntoLogic.hs`](src/OntoLogic.hs) +### 1. Core ADTs in [`src/OntoLogic.hs`](../../../../src/OntoLogic.hs) ```haskell -- Target-agnostic property types @@ -57,7 +57,7 @@ data BoundConstraint = BoundConstraint --- -### 2. Intermediate Representation in [`src/IR.hs`](src/IR.hs) +### 2. Intermediate Representation in [`src/IR.hs`](../../../../src/IR.hs) ```haskell module IR where @@ -91,35 +91,35 @@ compileRegistry :: Registry -> ModelIR ## 📋 Step-by-Step Execution Tasks ### Task 1: Type System ADT Foundations -- [ ] Add `PropertyType`, `CompOp`, `Value`, and `BoundConstraint` to [`src/OntoLogic.hs`](src/OntoLogic.hs). +- [ ] Add `PropertyType`, `CompOp`, `Value`, and `BoundConstraint` to [`src/OntoLogic.hs`](../../../../src/OntoLogic.hs). - [ ] Derive `Generic`, `Hashable`, `Eq`, `Ord`, and `Show` instances. - [ ] Update `Property` definition in `OntoLogic.hs` to use `rangeType :: PropertyType`. ### Task 2: Megaparsec Parser Type Alignment -- [ ] Update `parseDefProperty` in [`src/Parser.hs`](src/Parser.hs) to parse `PropertyType`. +- [ ] Update `parseDefProperty` in [`src/Parser.hs`](../../../../src/Parser.hs) to parse `PropertyType`. - [ ] Update `parsePredicate` to recognize `CompOp` operators. - [ ] Parse typed literals directly into `Term (ConstantVal Value)`. ### Task 3: Intermediate Representation (`src/IR.hs`) -- [ ] Create [`src/IR.hs`](src/IR.hs) implementing `compileRegistry`. +- [ ] Create [`src/IR.hs`](../../../../src/IR.hs) implementing `compileRegistry`. - [ ] Centralize topological class sorting using `Data.Graph`. - [ ] Resolve direct vs. inherited property sets and merge bound constraints. - [ ] Detect state-conditional axioms (e.g. `(implies (and (Concept c) (Cond c)) ...)`) and preserve them in `irUnmappedAxioms`. ### Task 4: Unified Linter Refactoring -- [ ] Refactor [`src/Linter.hs`](src/Linter.hs) to use typed `CompOp` and `Value`. +- [ ] Refactor [`src/Linter.hs`](../../../../src/Linter.hs) to use typed `CompOp` and `Value`. - [ ] Unify single-axiom and cross-axiom contradiction detection via `evalPairContradiction`. - [ ] Add linter check for unsupported property types and invalid operator-value pairs. ### Task 5: Refactor Code Emitters to Consume `ModelIR` -- [ ] **Java:** Refactor [`src/Emitters/Java.hs`](src/Emitters/Java.hs) to render `CompiledClass` instances with Jakarta `@NotNull`, `@Min`, `@Max`, `@DecimalMin`, `@DecimalMax`. -- [ ] **Python:** Refactor [`src/Emitters/Python.hs`](src/Emitters/Python.hs) to render `CompiledClass` instances with Pydantic `Field`. -- [ ] **Neo4j:** Refactor [`src/Emitters/Neo4j.hs`](src/Emitters/Neo4j.hs) to use `ModelIR`. -- [ ] **OWL:** Refactor [`src/Emitters/Owl.hs`](src/Emitters/Owl.hs) to use `ModelIR`. -- [ ] **Mermaid & D2:** Refactor [`src/Emitters/Mermaid.hs`](src/Emitters/Mermaid.hs) and [`src/Emitters/D2.hs`](src/Emitters/D2.hs). +- [ ] **Java:** Refactor [`src/Emitters/Java.hs`](../../../../src/Emitters/Java.hs) to render `CompiledClass` instances with Jakarta `@NotNull`, `@Min`, `@Max`, `@DecimalMin`, `@DecimalMax`. +- [ ] **Python:** Refactor [`src/Emitters/Python.hs`](../../../../src/Emitters/Python.hs) to render `CompiledClass` instances with Pydantic `Field`. +- [ ] **Neo4j:** Refactor [`src/Emitters/Neo4j.hs`](../../../../src/Emitters/Neo4j.hs) to use `ModelIR`. +- [ ] **OWL:** Refactor [`src/Emitters/Owl.hs`](../../../../src/Emitters/Owl.hs) to use `ModelIR`. +- [ ] **Mermaid & D2:** Refactor [`src/Emitters/Mermaid.hs`](../../../../src/Emitters/Mermaid.hs) and [`src/Emitters/D2.hs`](../../../../src/Emitters/D2.hs). ### Task 6: CLI Warning Reporting -- [ ] In [`src/Main.hs`](src/Main.hs), report compile-time warnings for `irUnmappedAxioms` when targeting OOP models (Java/Python). +- [ ] In [`src/Main.hs`](../../../../src/Main.hs), report compile-time warnings for `irUnmappedAxioms` when targeting OOP models (Java/Python). ### Task 7: Property-Based & Regression Testing - [ ] Add `test/IRSpec.hs` verifying compilation of complex hierarchies and inherited constraints. diff --git a/docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md b/docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md similarity index 99% rename from docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md rename to docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md index 8d24003..cc1bcc5 100644 --- a/docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md +++ b/docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md @@ -1,8 +1,8 @@ # OntoLogic Future Roadmap & Architectural Plan: 3-Tier Cyber, AI Governance, Threat Modeling & GRC Ontologies -> **Document ID:** `docs/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md` +> **Document ID:** `docs/dev/superpowers/plans/2026-09-14-3-tier-cyber-ai-governance-and-grc-roadmap.md` > **Methodology:** OpenGSD (Get Stuff Done) Phased Architecture & Execution -> **Master Reference:** [`docs/superpowers/REPLAY_PLAYBOOK.md`](docs/superpowers/REPLAY_PLAYBOOK.md) +> **Master Reference:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) --- diff --git a/docs/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md b/docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md similarity index 98% rename from docs/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md rename to docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md index a45a8d6..2e5ed6b 100644 --- a/docs/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md +++ b/docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md @@ -1,6 +1,6 @@ # Future Capabilities & Target Emitters Master Plan -**Document:** `docs/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md` +**Document:** `docs/dev/superpowers/plans/2026-09-14-future-capabilities-and-target-emitters.md` **Date:** 2026-09-14 **Status:** Queued / Future Roadmap **Scope:** Design and implementation specifications for SPARQL 1.1, Protobuf v3 / gRPC, SQL DDL relational schema generation, and WebAssembly (WASM) browser interactive studio. diff --git a/docs/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md b/docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md similarity index 87% rename from docs/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md rename to docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md index 11f2193..2687781 100644 --- a/docs/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md +++ b/docs/dev/superpowers/plans/2026-09-14-modular-namespacing-and-imports.md @@ -1,7 +1,7 @@ # Milestone 6 Plan: Modular Namespacing & Multi-File Imports > **Context:** Expands OntoLogic's DSL, parser, linter, and IR to support modular multi-file ontologies (`(import "path/to/file.logic")` and `(namespace "prefix")`), enabling the decomposition of large enterprise ontologies (BFO, CCO, MITRE, NIST AI RMF) into reusable components. -> **Tracking Document:** [`docs/superpowers/REPLAY_PLAYBOOK.md`](docs/superpowers/REPLAY_PLAYBOOK.md) +> **Tracking Document:** [`docs/dev/superpowers/REPLAY_PLAYBOOK.md`](../REPLAY_PLAYBOOK.md) --- @@ -38,7 +38,7 @@ ## 🧱 Architectural Specification -### 1. AST Extension in [`src/OntoLogic.hs`](src/OntoLogic.hs) +### 1. AST Extension in [`src/OntoLogic.hs`](../../../../src/OntoLogic.hs) ```haskell -- Qualified or unqualified identifier @@ -89,11 +89,11 @@ loadRegistryWithImports :: [FilePath] -> FilePath -> IO (Either String Registry) ## 📋 Execution Checklist - [ ] Create branch `feature/modular-imports`. -- [ ] Add `ImportDecl`, `NamespaceDecl`, `imports`, and `namespaces` to `Registry` in [`src/OntoLogic.hs`](src/OntoLogic.hs). -- [ ] Implement `(import "...")` and `(namespace "...")` parsers in [`src/Parser.hs`](src/Parser.hs). -- [ ] Implement multi-file import resolver with cycle detection in [`src/Loader.hs`](src/Loader.hs) / [`src/Parser.hs`](src/Parser.hs). -- [ ] Update [`src/Linter.hs`](src/Linter.hs) for multi-namespace symbol table validation. -- [ ] Update `ModelIR` in [`src/IR.hs`](src/IR.hs) and emitters for namespace support. +- [ ] Add `ImportDecl`, `NamespaceDecl`, `imports`, and `namespaces` to `Registry` in [`src/OntoLogic.hs`](../../../../src/OntoLogic.hs). +- [ ] Implement `(import "...")` and `(namespace "...")` parsers in [`src/Parser.hs`](../../../../src/Parser.hs). +- [ ] Implement multi-file import resolver with cycle detection in [`src/Loader.hs`](../../../../src/Loader.hs) / [`src/Parser.hs`](../../../../src/Parser.hs). +- [ ] Update [`src/Linter.hs`](../../../../src/Linter.hs) for multi-namespace symbol table validation. +- [ ] Update `ModelIR` in [`src/IR.hs`](../../../../src/IR.hs) and emitters for namespace support. - [ ] Add `test/ImportSpec.hs` with full test coverage. - [ ] Update existing test specs for new `Registry` record fields. - [ ] Verify with `stack test --ghc-options="-Wall -Werror"` and `./gradlew test`. diff --git a/docs/superpowers/plans/2026-09-19-review-remediation.md b/docs/dev/superpowers/plans/2026-09-19-review-remediation.md similarity index 100% rename from docs/superpowers/plans/2026-09-19-review-remediation.md rename to docs/dev/superpowers/plans/2026-09-19-review-remediation.md diff --git a/docs/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md b/docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md similarity index 90% rename from docs/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md rename to docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md index e383321..0e8bf33 100644 --- a/docs/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md +++ b/docs/dev/superpowers/plans/2026-10-01-canonical-cnf-and-native-prover.md @@ -1,7 +1,7 @@ # Milestone v1.7.0 Plan: Canonical Clausal Normal Form (CNF) IR & Native First-Order Prover Engine > **Context:** Evolution from relying exclusively on external automated theorem provers (Z3, CVC5, Vampire) over process stdio to providing a native, zero-dependency First-Order Logic (FOL) reasoning engine. Incorporates a formal Canonical Clausal Normal Form (CNF) intermediate representation and a built-in resolution/tableau prover directly in Haskell. -> **Tracking Document:** [`.planning/ROADMAP.md`](.planning/ROADMAP.md) +> **Tracking Document:** [`.planning/ROADMAP.md`](../../../../.planning/ROADMAP.md) --- @@ -17,7 +17,7 @@ - **Saturation Engine (`src/Prover/Resolution.hs`)**: Ordered Resolution with Factoring, Superposition for equality, and the Given-Clause loop (Otter/DISCOUNT model) for refutation proofs. - **Countermodel Search (`src/Prover/Tableau.hs`)**: Analytic Free-Variable Semantic Tableaux for finite model finding and generating human-readable counterexamples when formulas are satisfiable. 5. **Architectural Integration**: - Integrate the native engine into [`src/Solver.hs`](src/Solver.hs) as `--prover native` (default fallback when no external binaries exist), the REPL (`:cnf`, `:clausify`), and the LSP server (`ontologic-lsp`). + Integrate the native engine into [`src/Solver.hs`](../../../../src/Solver.hs) as `--prover native` (default fallback when no external binaries exist), the REPL (`:cnf`, `:clausify`), and the LSP server (`ontologic-lsp`). --- @@ -93,7 +93,7 @@ newtype CNFTheory = CNFTheory { getClauses :: Set.Set Clause } ### 2. Normalization Pipeline (`src/IR/Clausify.hs`) -The normalization pass takes raw [`FOL`](src/OntoLogic.hs#L49-L64) formulas and transforms them into [`CNFTheory`](#1-data-model-srcircnfhs): +The normalization pass takes raw [`FOL`](../../../../src/OntoLogic.hs#L49-L64) formulas and transforms them into [`CNFTheory`](#1-data-model-srcircnfhs): ``` Raw FOL Formula @@ -172,32 +172,32 @@ The normalization pass takes raw [`FOL`](src/OntoLogic.hs#L49-L64) formulas and ## 📋 Implementation Roadmap & Work Breakdown ### Phase 1: Canonical CNF Intermediate Representation -- [ ] **Task 1.1**: Create [`src/IR/CNF.hs`](src/IR/CNF.hs) defining `VarId`, `SkolemId`, `Term`, `Literal`, `Clause`, and `CNFTheory`. -- [ ] **Task 1.2**: Implement [`src/IR/Clausify.hs`](src/IR/Clausify.hs) with NNF transformation, variable standardization, and skolemization. +- [ ] **Task 1.1**: Create [`src/IR/CNF.hs`](../../../../src/IR/CNF.hs) defining `VarId`, `SkolemId`, `Term`, `Literal`, `Clause`, and `CNFTheory`. +- [ ] **Task 1.2**: Implement [`src/IR/Clausify.hs`](../../../../src/IR/Clausify.hs) with NNF transformation, variable standardization, and skolemization. - [ ] **Task 1.3**: Implement clausal distribution ($\lor$ over $\land$) with tautology pruning. - [ ] **Task 1.4**: Add unit tests in `test/CNFSpec.hs` verifying roundtripping, De Morgan correctness, and Skolem arity consistency. ### Phase 2: First-Order Unification & Term Indexing -- [ ] **Task 2.1**: Implement Robinson's MGU algorithm in [`src/Prover/Unification.hs`](src/Prover/Unification.hs) with occurs-check. +- [ ] **Task 2.1**: Implement Robinson's MGU algorithm in [`src/Prover/Unification.hs`](../../../../src/Prover/Unification.hs) with occurs-check. - [ ] **Task 2.2**: Implement substitution application and composition ($\sigma_1 \circ \sigma_2$). - [ ] **Task 2.3**: Implement clause subsumption checking ($C \subseteq_\sigma D$). - [ ] **Task 2.4**: Unit tests in `test/UnificationSpec.hs` covering cyclic terms, variable renaming, and failure cases. ### Phase 3: Native Resolution Prover Engine -- [ ] **Task 3.1**: Implement the Given-Clause saturation loop in [`src/Prover/Resolution.hs`](src/Prover/Resolution.hs). +- [ ] **Task 3.1**: Implement the Given-Clause saturation loop in [`src/Prover/Resolution.hs`](../../../../src/Prover/Resolution.hs). - [ ] **Task 3.2**: Implement binary resolution and positive factoring rules. - [ ] **Task 3.3**: Implement step/clause iteration limits and execution timeouts (`timeout :: Int -> IO a -> IO (Maybe a)`). - [ ] **Task 3.4**: Implement refutation proof trace generation (reconstructing the derivation tree from empty clause back to input axioms). ### Phase 4: Semantic Tableaux & Countermodel Generation -- [ ] **Task 4.1**: Implement tableau tree data structures in [`src/Prover/Tableau.hs`](src/Prover/Tableau.hs). +- [ ] **Task 4.1**: Implement tableau tree data structures in [`src/Prover/Tableau.hs`](../../../../src/Prover/Tableau.hs). - [ ] **Task 4.2**: Implement branch unification and branch closure checking. - [ ] **Task 4.3**: Implement open branch valuation extraction for counterexample reporting. ### Phase 5: Compiler & CLI Integration -- [ ] **Task 5.1**: Register `NativeProver` in [`src/Solver.hs`](src/Solver.hs) (`ProverType Native`). +- [ ] **Task 5.1**: Register `NativeProver` in [`src/Solver.hs`](../../../../src/Solver.hs) (`ProverType Native`). - [ ] **Task 5.2**: Update `AutoProver` fallback chain: `Z3 -> CVC5 -> Vampire -> NativeProver` (never error out due to missing binaries). -- [ ] **Task 5.3**: Add REPL commands in [`src/REPL.hs`](src/REPL.hs): `:cnf` (print CNF clauses), `:prover native`. +- [ ] **Task 5.3**: Add REPL commands in [`src/REPL.hs`](../../../../src/REPL.hs): `:cnf` (print CNF clauses), `:prover native`. - [ ] **Task 5.4**: Add CLI flag `--prover native` to `Main.hs`. ### Phase 6: Verification & Benchmarking diff --git a/docs/superpowers/plans/2026-10-01-clif-interop-fol-port.md b/docs/dev/superpowers/plans/2026-10-01-clif-interop-fol-port.md similarity index 100% rename from docs/superpowers/plans/2026-10-01-clif-interop-fol-port.md rename to docs/dev/superpowers/plans/2026-10-01-clif-interop-fol-port.md diff --git a/docs/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md b/docs/dev/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md similarity index 100% rename from docs/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md rename to docs/dev/superpowers/plans/2026-10-03-string-constants-in-fol-backends.md diff --git a/docs/superpowers/plans/2026-10-14-def-relation-smt-facts.md b/docs/dev/superpowers/plans/2026-10-14-def-relation-smt-facts.md similarity index 100% rename from docs/superpowers/plans/2026-10-14-def-relation-smt-facts.md rename to docs/dev/superpowers/plans/2026-10-14-def-relation-smt-facts.md diff --git a/docs/domains/README.md b/docs/domains/README.md new file mode 100644 index 0000000..1d8e576 --- /dev/null +++ b/docs/domains/README.md @@ -0,0 +1,143 @@ +# Domain Examples Gallery + +Complete, runnable models grouped by sector. Each links to its `.logic` source +and the D2 diagram rendered from it. Start with the foundations if you want to +see the upper-ontology pattern; start with your own sector if you want a template. + +- [Industrial and OT](#industrial-and-ot) | [IoT](#iot) | [Security](#security) | + [Software and engineering](#software-and-engineering) | + [Science, research and health](#science-research-and-health) | + [Customer and business](#customer-and-business) | + [Food, logistics and agriculture](#food-logistics-and-agriculture) | + [Foundations](#foundations) +- [Run an example](#run-an-example) +- [How the domain_* examples are verified](#how-the-domain_-examples-are-verified) + +Examples are sources to adapt, not fixed products. For reusable building blocks +(BFO, CCO, ATT&CK, NIST and others) see the [standard library](../standard-library.md). + +## Industrial and OT + +Plants, control systems and factories. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_ics`](../../examples/domain_ics.logic) | Industrial control systems: PLCs, SCADA/HMI, Purdue-model levels, safety instrumented systems, setpoints, alarms and interlocks. | [diagram](../../examples/domain_ics.d2.svg) | +| [`domain_iiot`](../../examples/domain_iiot.logic) | Industrial IoT: edge gateways, MQTT / OPC UA telemetry and asset condition monitoring. | [diagram](../../examples/domain_iiot.d2.svg) | +| [`domain_mining`](../../examples/domain_mining.logic) | Mining operations: equipment, processes and safety, on a condensed BFO layer. | [diagram](../../examples/domain_mining.d2.svg) | +| [`domain_semiconductor_fab`](../../examples/domain_semiconductor_fab.logic) | Semiconductor wafer fab: lots, wafers, process steps, tools, recipes and cleanroom classes. | [diagram](../../examples/domain_semiconductor_fab.d2.svg) | +| [`domain_aerospace`](../../examples/domain_aerospace.logic) | Aerospace: aircraft, components, certification, maintenance checks, flight operations and crews. | [diagram](../../examples/domain_aerospace.d2.svg) | +| [`smart_factory`](../../examples/smart_factory.logic) | Smart factory taxonomy with bounded sensor properties and axioms. | [diagram](../../examples/smart_factory.d2.svg) | +| [`dough_factory`](../../examples/dough_factory.logic) | Food-plant production line: processing and monitoring equipment. | [diagram](../../examples/dough_factory.d2.svg) | +| [`car_manufacturer`](../../examples/car_manufacturer.logic) | Vehicle manufacturing: taxonomy, properties and axioms. | [diagram](../../examples/car_manufacturer.d2.svg) | +| [`smart_grid_relational`](../../examples/smart_grid_relational.logic) | Smart-grid topology using relations between grid elements. | none yet | + +## IoT + +Connected devices and messaging. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_iot_smart_home`](../../examples/domain_iot_smart_home.logic) | Consumer smart home: devices, hubs, rooms, automations and firmware updates. | [diagram](../../examples/domain_iot_smart_home.d2.svg) | +| [`mqtt_operational`](../../examples/mqtt_operational.logic) | MQTT-centered operational domain: design, sell and operate layout. | [diagram](../../examples/mqtt_operational.d2.svg) | +| [`mqtt_ecosystem_unified`](../../examples/mqtt_ecosystem_unified.logic) | Unified MQTT ecosystem on a full BFO upper level. | [diagram](../../examples/mqtt_ecosystem_unified.d2.svg) | + +## Security + +Threats, trust and operations. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_cybersecurity_soc`](../../examples/domain_cybersecurity_soc.logic) | Security operations: assets, vulnerabilities, detections, alerts, incidents and analysts. | [diagram](../../examples/domain_cybersecurity_soc.d2.svg) | +| [`domain_security_trust`](../../examples/domain_security_trust.logic) | Digital trust and security: security artifacts, roles and trust relations. | [diagram](../../examples/domain_security_trust.d2.svg) | +| [`security_policy`](../../examples/security_policy.logic) | Network security policy: untrusted nodes may not reach the admin panel. | [diagram](../../examples/security_policy.d2.svg) | + +## Software and engineering + +Building and running software and systems. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_software_delivery`](../../examples/domain_software_delivery.logic) | Software delivery: repositories, commits, pull requests, reviews, builds, tests, releases and production incidents. | [diagram](../../examples/domain_software_delivery.d2.svg) | +| [`domain_systems_engineering`](../../examples/domain_systems_engineering.logic) | Systems engineering: requirements, system elements, interfaces, verification, change requests and traceability. | [diagram](../../examples/domain_systems_engineering.d2.svg) | +| [`domain_cloud_datacenter`](../../examples/domain_cloud_datacenter.logic) | Cloud and datacenter: physical and virtual infrastructure and software services. | [diagram](../../examples/domain_cloud_datacenter.d2.svg) | + +## Science, research and health + +Laboratories, research and clinical care. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_science_lab`](../../examples/domain_science_lab.logic) | Laboratory science: samples, specimens, instruments, calibration, protocols, experiments and custody. | [diagram](../../examples/domain_science_lab.d2.svg) | +| [`domain_research_projects`](../../examples/domain_research_projects.logic) | Research projects: funding, investigators, institutions, studies, datasets and publications. | [diagram](../../examples/domain_research_projects.d2.svg) | +| [`domain_clinical_medicine`](../../examples/domain_clinical_medicine.logic) | Clinical medicine: patients, encounters, clinicians, diagnoses, orders and medications. | [diagram](../../examples/domain_clinical_medicine.d2.svg) | + +## Customer and business + +Service and success operations. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_customer_service`](../../examples/domain_customer_service.logic) | Customer service: tickets, agents, queues and service levels. | [diagram](../../examples/domain_customer_service.d2.svg) | +| [`domain_customer_success`](../../examples/domain_customer_success.logic) | Customer success: accounts, health scores, renewals and playbooks. | [diagram](../../examples/domain_customer_success.d2.svg) | + +## Food, logistics and agriculture + +Supply chains from farm to table. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`domain_food_service`](../../examples/domain_food_service.logic) | Food service: kitchens, menus, orders, allergens and safety temperatures. | [diagram](../../examples/domain_food_service.d2.svg) | +| [`domain_logistics`](../../examples/domain_logistics.logic) | Logistics: shipments, carriers, warehouses and routes. | [diagram](../../examples/domain_logistics.d2.svg) | +| [`domain_agriculture`](../../examples/domain_agriculture.logic) | Agriculture: fields, crops, equipment and seasonal operations. | [diagram](../../examples/domain_agriculture.d2.svg) | + +## Foundations + +Upper-ontology examples that other models build on. + +| Example | What it models | Diagram | +| :--- | :--- | :--- | +| [`bfo_energy`](../../examples/bfo_energy.logic) | BFO applied to energy generation and distribution. | [diagram](../../examples/bfo_energy.d2.svg) | +| [`bfo_manufacturing`](../../examples/bfo_manufacturing.logic) | BFO applied to manufacturing. | [diagram](../../examples/bfo_manufacturing.d2.svg) | +| [`bfo_morphisms_plant`](../../examples/bfo_morphisms_plant.logic) | BFO with specifically dependent continuants in a plant setting. | [diagram](../../examples/bfo_morphisms_plant.d2.svg) | +| [`bfo_unified`](../../examples/bfo_unified.logic) | Unified BFO model combining the above. | [diagram](../../examples/bfo_unified.d2.svg) | + +## Run an example + +From the repository root (replace `ontologic` with `stack exec ontologic-exe --` +if you have not installed the binary): + +```bash +# Validate +ontologic -i examples/domain_ics.logic -t lint + +# Prove consistency and coherence +ontologic -i examples/domain_ics.logic --solve + +# Generate code or schemas +ontologic -i examples/domain_ics.logic -t python -o out/ics +ontologic -i examples/domain_ics.logic -t sql -o out/ics + +# Re-render the diagram +ontologic -i examples/domain_ics.logic -t d2 -o out/ics --render +``` + +To regenerate all example diagrams and Cypher files, use +[`examples/generate_visuals.sh`](../../examples/generate_visuals.sh) (needs `d2` +and `mmdc` on your `PATH`). + +## How the domain_* examples are verified + +Every `domain_*` example has two companions under +[`test/fixtures/domains/`](../../test/fixtures/domains/): + +- `.expect`: the concept, relation and property names that must exist in + the parsed registry. +- `_conflict.logic`: a deliberately contradictory variant of the model, which the + solver must report as unsatisfiable. + +[`test/DomainExamplesSpec.hs`](../../test/DomainExamplesSpec.hs) checks each +example against its `.expect` file and each `_conflict.logic` with Z3 or CVC5 +(the conflict checks need integer-bound reasoning the native prover lacks). A domain example cannot silently break without that spec +failing. The older BFO, factory and MQTT examples are exercised by +[`test/ExamplesSpec.hs`](../../test/ExamplesSpec.hs). diff --git a/docs/purpose.md b/docs/purpose.md new file mode 100644 index 0000000..187ddd7 --- /dev/null +++ b/docs/purpose.md @@ -0,0 +1,144 @@ +# Purpose: Why OntoLogic Exists + +> Complexity is conserved. Either you eliminate semantic ambiguity at the +> foundation, or you pay a compounding "sloppiness tax" of drifting rules, +> inconsistent schemas and hallucinated facts in application code. + +OntoLogic is a Haskell First-Order Logic (FOL) ontology DSL and toolchain. You +describe a domain once in a `.logic` file. OntoLogic checks it, proves things +about it, and compiles it to the schemas, models and diagrams your systems need. + +- [The problem](#the-problem) +- [The idea: Logic-as-Code](#the-idea-logic-as-code) +- [Why not the alternatives](#why-not-the-alternatives) +- [Three design choices: BFO, FOL, Haskell](#three-design-choices-bfo-fol-haskell) +- [Where it pays off](#where-it-pays-off) +- [Further reading](#further-reading) + +## The problem + +Modern systems split one domain across many technologies. A single rule such as +"a pump's temperature must stay between 0 and 90 degrees" is re-implemented as a +Java validator on a gateway, a Python model on a device, a SQL check constraint in +the warehouse, a Cypher assertion in a digital twin, an OpenAPI schema on the +REST edge, and a sentence in an LLM prompt. + +When the rule changes, someone must find and edit every copy. They never all +match for long. The result is **distributed logic drift**: + +```mermaid +flowchart LR + R["Rule changes:
max temp 100 to 90"] --> G["Gateway (Java)
updated: 90"] + R --> D["Device (Python)
missed: 100"] + R --> W["Warehouse (SQL)
stale: 85"] + G --- X{{"Silent disagreement:
one tier accepts what
another rejects"}} + D --- X + W --- X +``` + +Four related failures make it worse: + +1. **Flat property graphs and ad-hoc schemas** defer the cost of meaning. One + team writes `status: "active"`, another `is_active: true`, a third `state: 1`. + A relationship like `CONNECTED_TO` ends up meaning a cable, a TCP socket and a + reporting line at once. +2. **LLMs and RAG retrieve plausible text; they do not deduce.** An agent can + claim an unpowered sensor is reporting, or that software has mass. Retrieval + cannot enforce invariants. +3. **The academic Semantic Web stack** (RDF, OWL, desktop editors) is rigorous + but sits outside CI/CD, uses an open-world assumption that is awkward for + "this field is required" validation, and generates no application code. +4. **Data contracts without logic contracts.** Protobuf, JSON Schema and OpenAPI + describe shapes. They cannot say "if `risk_score > 7` a mitigation must exist" + or prove that an inheritance taxonomy has no cycles or contradictions. + +## The idea: Logic-as-Code + +Define concepts, typed properties, relations and axioms once. Treat the file as +source code: review it, version it, lint it, prove things about it, and generate +everything else from it. + +```mermaid +flowchart TD + L[".logic source
concepts, properties, relations, axioms"] --> V["Verify
linter, SAT, SMT / native prover"] + V --> C["Compile to ModelIR"] + C --> A["Code and data models
Java, Python, Rust, Go, TypeScript, C++"] + C --> B["Schemas and contracts
SQL, GraphQL, OpenAPI, JSON Schema, Protobuf"] + C --> K["Knowledge and proof formats
OWL, SHACL, Neo4j, SMT-LIB2, TPTP"] + C --> D["Diagrams
Mermaid, D2"] +``` + +What you get: + +- **One source of truth.** A rule change is one edit, then a regenerate. +- **Proofs, not hopes.** Consistency, taxonomic subsumption (`A` is a `B`), and + empty-concept detection run through Z3, CVC5, Vampire, or the built-in native + prover. +- **Zero runtime reasoner.** Production systems receive plain generated + validators and schemas. The heavy reasoning happens at build time. +- **Normal developer workflow.** A CLI, an interactive REPL, a language server, + and a VS Code extension. + +## Why not the alternatives + +| Dimension | Ad-hoc code and DTOs | JSON Schema / OpenAPI | RDF / OWL tooling | Property graph | OntoLogic | +| :--- | :--- | :--- | :--- | :--- | :--- | +| Single source of truth | Fragmented | Data shapes only | Ontology only | Database only | Yes | +| Logic and axiom constraints | Hand-coded per app | None | Description logic | None | First-order logic | +| Compile-time proofs | None | None | Slow DL reasoners | None | SMT and native prover | +| Multi-target generation | None | Basic stubs | None | None | 18 emitters | +| Upper-ontology grounding | None | None | Possible | None | BFO and CCO in the standard library | +| Developer ergonomics | Per IDE | Schema linter | Desktop GUI | Browser console | CLI, REPL, LSP | +| Runtime cost | Varies | Low | Heavy reasoner | Query overhead | None (generated code) | + +## Three design choices: BFO, FOL, Haskell + +**Basic Formal Ontology (BFO, ISO/IEC 21838-2) as the upper layer.** Models of +"concepts" are ideas in minds; models of *universals* describe what exists. BFO +separates things that exist (material entities), things that happen (processes), +and records about them (information content entities). That keeps a socket, a +cable and a social tie from collapsing into one `Connection`, lets mining, cloud +and manufacturing models merge without collisions, and gives you a principled +check against nonsense such as "the software weighs 5 kg" (software is a +generically dependent continuant; only material entities have mass). + +**First-order logic as the language of definition.** Triples cannot express +"all pumps have a safety valve" or "if a mining process runs, some excavator +exists". FOL can, and an axiom is a constraint a prover can use to deduce what a +sensor did not report. + +```lisp +;; High-risk vulnerabilities require an active mitigation +(forall (v) + (implies (and (Vulnerability v) (gt risk_score 7)) + (exists (m) (and (Mitigation m) (mitigates m v))))) +``` + +**Haskell as the implementation language.** Algebraic data types mirror the logic +(`FOL` is a sum type matching the grammar), pure functions make verification +deterministic for the same input, and Megaparsec gives a precise, testable +parser for untrusted `.logic` files. + +The trade is explicit: setup cost is higher than a loose graph, maintenance cost +is much lower, and ambiguity is removed once, at the foundation. Alerts become +explainable ("violated axiom 4: active oven must have temperature above 100") +instead of a bare score. + +## Where it pays off + +- **Industrial and IoT fleets.** One ontology becomes gateway validators, edge + models and digital-twin schemas, so every tier enforces the same bounds. +- **Security, threat intelligence and compliance.** The standard library covers + STIX, ATT&CK, D3FEND, NIST and AI-governance frameworks; compliance rules are + axioms you can check. See the [standard library](standard-library.md). +- **Grounding AI agents.** An agent's proposed actions can be checked against + domain invariants before they run, so a violation is rejected + deterministically. +- **Software and systems engineering.** Architecture, delivery and requirements + models stay consistent with the code generated from them. See the + [domain gallery](domains/README.md). + +## Further reading + +- [Architecture](architecture.md): how the toolchain is built. +- [Using OntoLogic](using.md): task-oriented usage. diff --git a/docs/purpose_and_motivation.md b/docs/purpose_and_motivation.md deleted file mode 100644 index 329342b..0000000 --- a/docs/purpose_and_motivation.md +++ /dev/null @@ -1,53 +0,0 @@ -# OntoLogic: Purpose & Motivation - -OntoLogic was created to address a critical challenge in modern Internet of Things (IoT) and Industrial IoT (IIOT) environments: **enforcing consistent business and safety rules across heterogeneous platforms at scale.** - ---- - -## 🛑 The Problem: Distributed Logic Drift - -In large-scale IoT fleets (such as smart factories, pipelines, or container terminal operations), multiple platforms execute different parts of the same operational process: -1. **Edge Gateways**: Run Java/JVM environments (e.g., Acme broker plugins) to parse and route high-throughput telemetry packets. -2. **Edge Devices**: Run Python scripts on single-board computers (e.g., Raspberry Pi, BeagleBone) to read sensor data and perform local logic checks. -3. **Cloud Analytics / Digital Twins**: Run graph databases like Neo4j to build semantic models of the system and audit historical states. - -If a safety rule changes (for example, the maximum threshold for a temperature sensor is reduced from `100°C` to `90°C`), developers must manually update: -* Java POJO validation rules on the Gateway. -* Python Pydantic parsing models on the Devices. -* Cypher queries auditing database records in the Cloud. - -This manual process is highly error-prone, leading to **logic drift** where different tiers of the application enforce inconsistent rules, potentially causing silent data corruption, validation bypasses, or safety hazards. - ---- - -## ⚡ The Solution: Logic-as-Code - -OntoLogic introduces a **Logic-as-Code** pipeline for IoT architectures. Instead of defining taxonomies and safety rules in multiple codebases, developers define them once in a declarative S-expression syntax. - -``` - ┌──────────────────────────────┐ - │ Unified .logic Rule File │ - │ (Single Source of Truth) │ - └──────────────────────────────┘ - │ - ▼ - ┌──────────────────┐ - │ Haskell Linter │ ──> (Static Cycle/Contradiction Check) - └──────────────────┘ - │ - ▼ - ┌──────────────────┐ - │ Compiler Emitters│ - └──────────────────┘ - ┌─────────────────────┼─────────────────────┐ - ▼ ▼ ▼ - ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ - │ Java POJOs │ │ Python │ │ Neo4j Graph │ - │ (Gateway) │ │ (Edge/Apps) │ │ (Cloud) │ - └─────────────┘ └─────────────┘ └─────────────┘ -``` - -By compiling the logical model from a single source of truth, OntoLogic ensures: -* **Mathematical Consistency**: All rules are statically checked for cycles and contradictions before compilation. -* **Zero Drift**: Any change in a rule propagates instantly to Java validation classes, Pydantic models, and Cypher database schema constraints. -* **Optimized Performance**: Generated artifacts are lightweight, platform-native classes or queries with zero heavy compiler runtime overhead. diff --git a/docs/standard-library.md b/docs/standard-library.md new file mode 100644 index 0000000..5d85fbd --- /dev/null +++ b/docs/standard-library.md @@ -0,0 +1,119 @@ +# Standard Library + +`ontologic-lib/` ships 19 ready-made `.logic` modules, layered on a common +upper ontology. Import what you need by bare file name; the transitive imports +come with it. + +- [How the layers fit](#how-the-layers-fit) +- [Importing](#importing) +- [Upper ontologies](#upper-ontologies) +- [Cybersecurity and threat intelligence](#cybersecurity-and-threat-intelligence) +- [Compliance and AI governance](#compliance-and-ai-governance) +- [Software, systems and factories](#software-systems-and-factories) +- [Instance data](#instance-data) +- [Domain examples](#domain-examples) + +Sizes are counted from the files (`def-concept` / `def-relation` forms), so +re-count after editing a module. Tests live in [`test/`](../test/). + +## How the layers fit + +```mermaid +flowchart BT + BFO["bfo_2020
upper ontology"] --> CCO["cco_core"] + CCO --> UCO["uco_observables"] + UCO --> STIX["stix_cve"] --> ATT["mitre_attack"] --> D3F["mitre_d3fend"] + ATT --> ATL["mitre_atlas"] --> RMF["nist_ai_rmf"] --> ISO["iso_42001_eu_ai_act"] + UCO --> OCSF["ocsf_schema"] --> SIG["sigma_rules"] + ATT --> SIG + CCO --> CSF["nist_csf"] --> SP["nist_sp800_53"] + STIX --> SP + CCO --> AAI["autonomous_ai"] + CCO --> SW["software_systems"] + CCO --> FD["factory_domain"] + BFO --> ECO["ecosystem"] + AAI --> UNI["ecosystem_unified"] + SW --> UNI + SIG --> UNI + D3F --> UNI + FD --> UNI +``` + +Arrows point from an imported module to the module that imports it. + +## Importing + +```lisp +(namespace "cco" "http://www.ontologyrepository.com/CommonCoreOntologies/") + +(import "cco_core.logic") ; also pulls in bfo_2020.logic +(import "mitre_attack.logic") ; also pulls in stix_cve, uco_observables, cco_core, bfo_2020 + +(def-concept LateralMovementAlert) +``` + +Then check or compile as usual: + +```bash +ontologic -i my_model.logic -t lint +ontologic -i my_model.logic --solve +ontologic -i my_model.logic -t sql -o out/ +``` + +Imports are searched in the importing file's directory, `$ONTOLOGIC_PATH`, the +directory beside the binary, the package data directory, `./ontologic-lib`, and +the current directory last. Add folders with `--lib-path DIR`. A module imported +by two paths is loaded once. See [architecture](architecture.md#frontend-and-loader). + +## Upper ontologies + +| File | Covers | Concepts / relations | Imports | Test | +| :--- | :--- | :--- | :--- | :--- | +| `bfo_2020.logic` | Basic Formal Ontology (ISO/IEC 21838-2): continuants, occurrents, material entities, sites, qualities, roles, dispositions, functions, information content entities, processes and temporal regions, with the core relations | 21 / 9 | none | `StandardLibrarySpec.hs`; also imported by `ImportSpec.hs`, `CompileSpec.hs`, `MainSpec.hs`, `LSPSpec.hs`, `SolverSpec.hs` | +| `cco_core.logic` | Common Core Ontologies mid-level: agents and organizations, artifacts and engineered systems, information content entities, acts and planned processes, facilities, and security and reliability qualities | 34 / 8 | `bfo_2020` | `StandardLibrarySpec.hs` | +| `uco_observables.logic` | Unified Cyber Ontology / CASE digital observables: network addresses, ports, sockets and flows, HTTP connections, processes, user accounts, files and certificates | 17 / 6 | `cco_core` | `StandardLibrarySpec.hs` | + +## Cybersecurity and threat intelligence + +| File | Covers | Concepts / relations | Imports | Test | +| :--- | :--- | :--- | :--- | :--- | +| `stix_cve.logic` | STIX 2.1, CAPEC, CWE and CVE: STIX domain objects (attack patterns, campaigns, indicators, intrusion sets, malware, threat actors, tools), vulnerabilities and weaknesses, with CVSS score bounds and EPSS probability | 17 / 8 | `uco_observables` | `ThreatModelingSpec.hs` | +| `mitre_attack.logic` | ATT&CK Enterprise: the tactic set (initial access through impact), techniques, sub-techniques, mitigations, data sources, groups and software | 21 / 8 | `stix_cve` | `ThreatModelingSpec.hs` | +| `mitre_d3fend.logic` | D3FEND defensive tactics (model, harden, detect, isolate, deceive, evict) and techniques such as network segmentation and process isolation, mapped to ATT&CK | 16 / 7 | `mitre_attack` | `ThreatModelingSpec.hs` | +| `mitre_atlas.logic` | ATLAS adversarial threat matrix for machine-learning systems: prompt injection, evasion, data poisoning, model inversion and extraction, with guardrail mitigations | 19 / 4 | `mitre_attack` | `AIGovernanceSpec.hs` | +| `ocsf_schema.logic` | Open Cybersecurity Schema Framework v1.1.0 event categories and events (file, process, authentication, network, DNS, HTTP activity, security findings) | 14 / 6 | `uco_observables` | `TelemetryMonitoringSpec.hs` | +| `sigma_rules.logic` | Sigma detection rules, detection conditions and severity levels, mapped onto OCSF and ATT&CK | 7 / 3 | `ocsf_schema`, `mitre_attack` | `TelemetryMonitoringSpec.hs` | + +## Compliance and AI governance + +| File | Covers | Concepts / relations | Imports | Test | +| :--- | :--- | :--- | :--- | :--- | +| `nist_csf.logic` | NIST Cybersecurity Framework 2.0: the six functions (Govern through Recover) and example categories | 14 / 2 | `cco_core` | `ComplianceGRCSpec.hs` | +| `nist_sp800_53.logic` | NIST SP 800-53 Rev 5 control families, representative controls, low/moderate/high baselines, system security plans and assessment findings for compliance-as-code | 22 / 6 | `nist_csf`, `stix_cve` | `ComplianceGRCSpec.hs` | +| `nist_ai_rmf.logic` | NIST AI Risk Management Framework: the Govern, Map, Measure and Manage functions, trustworthy-AI characteristics, AI systems, evaluation metrics and risk profiles | 17 / 4 | `mitre_atlas` | `AIGovernanceSpec.hs` | +| `iso_42001_eu_ai_act.logic` | ISO/IEC 42001 AI management system and EU AI Act risk tiers (prohibited, high, transparency, minimal), lifecycle stages, human oversight and audit records | 13 / 4 | `nist_ai_rmf` | `AIGovernanceSpec.hs` | + +## Software, systems and factories + +| File | Covers | Concepts / relations | Imports | Test | +| :--- | :--- | :--- | :--- | :--- | +| `software_systems.logic` | Software engineering and systems programming: repositories, branches, commits, pull requests, source files and ASTs, packages, hosts and containers, and build, test, CI and deployment processes | 31 / 10 | `cco_core` | `SoftwareSystemsSpec.hs` | +| `factory_domain.logic` | Software-factory domain: factory roles, instructions and standards, sandboxes, Toulmin-style arguments and verification gates. Vendored copy; the upstream project owns the source | 25 / 5 | `cco_core` | `StandardLibrarySpec.hs` | +| `autonomous_ai.logic` | Autonomous AI and multi-agent swarms: agents, subagents and swarms, role types, foundation models, prompts and context, MCP tools, task execution and evaluation suites with quality gates | 34 / 10 | `cco_core` | `AutonomousAISpec.hs`, `IndustrialBenchmarkSpec.hs` | +| `ecosystem.logic` | Class layer for a code ecosystem: repositories and code symbols bridged to BFO | 5 / 1 | `bfo_2020` | `EcosystemSpec.hs` (also `GraphQLSpec.hs`) | +| `ecosystem_unified.logic` | Mega-ontology that unifies AI agents, software systems, detection, countermeasures and the factory domain, with cross-domain axioms | 5 / 8 | `autonomous_ai`, `software_systems`, `sigma_rules`, `mitre_d3fend`, `factory_domain` | `EcosystemUnifiedSpec.hs`, `IndustrialBenchmarkSpec.hs` | + +Concept counts for `ecosystem_unified.logic` are its own additions; the imports +bring the rest. + +## Instance data + +`ontologic-lib/ecosystem.logic` is tested against a small synthetic Turtle sample, +[`test/fixtures/ecosystem_symbols.ttl`](../test/fixtures/ecosystem_symbols.ttl). +Individuals can also be declared directly with `def-individual` (see the +[language reference](user-guide/language-reference.md)). + +## Domain examples + +For complete models built on these layers, grouped by sector, see the +[domain examples gallery](domains/README.md). diff --git a/docs/user-guide/README.md b/docs/user-guide/README.md index dbff492..2634e94 100644 --- a/docs/user-guide/README.md +++ b/docs/user-guide/README.md @@ -1,477 +1,47 @@ # OntoLogic User Guide -[← Back to Project README](../../README.md) +This guide shows how to write, check, and compile OntoLogic ontologies. OntoLogic is a Haskell toolchain around a small first-order-logic (FOL) language: you describe concepts, properties, relations, and axioms in `.logic` files; the linter and SMT/ATP solvers check them for contradictions; and eighteen emitters turn the same model into code, API schemas, database schemas, knowledge-graph formats, prover input, and diagrams. A REPL, a language server (LSP), and a VS Code extension sit on top. -OntoLogic is a formal First-Order Logic (FOL) domain-specific language compiler, semantic linter, multi-target emitter, and automated theorem-proving bridge implemented in Haskell. It compiles high-integrity ontological specifications into production software artifacts, API schemas, relational and graph database schemas, automated theorem prover problems, and visual architectural diagrams. +Every command in these pages was run against the current build and the output pasted (trimmed). Commands are written as `stack exec ontologic-exe -- ...` or just `ontologic-exe ...` if the binary is on your `PATH`. ---- +## Reading order -## Table of Contents +New to OntoLogic: read 1 to 3 in order, then pick topics as needed. -- [Getting Started](#getting-started) - - [Prerequisites](#prerequisites) - - [Installation & Build](#installation--build) - - [Two-Minute First Run](#two-minute-first-run) -- [Core Concepts & DSL Syntax](#core-concepts--dsl-syntax) - - [Concepts & Taxonomic Inheritance](#concepts--taxonomic-inheritance) - - [Properties, Types & Cardinalities](#properties-types--cardinalities) - - [Relations](#relations) - - [First-Order Logic Axioms & Constraints](#first-order-logic-axioms--constraints) - - [Modular Namespaces & Imports](#modular-namespaces--imports) -- [Examples & Common Workflows](#examples--common-workflows) - - [1. Semantic Linting](#1-semantic-linting) - - [2. Automated SMT Reasoning & Coherence Verification](#2-automated-smt-reasoning--coherence-verification) - - [3. Multi-Target Code Generation](#3-multi-target-code-generation) - - [4. Interactive REPL Exploration](#4-interactive-repl-exploration) - - [5. Language Server Protocol (LSP) & Editor Setup](#5-language-server-protocol-lsp--editor-setup) -- [CLI Reference](#cli-reference) - - [Command-Line Options & Flags](#command-line-options--flags) - - [Compilation Targets](#compilation-targets) - - [Theorem Prover Backends](#theorem-prover-backends) - - [Exit Codes](#exit-codes) - - [Environment Variables](#environment-variables) -- [Troubleshooting & FAQ](#troubleshooting--faq) - - [Common Error Messages & Remedies](#common-error-messages--remedies) - - [Prover Selection & Solver Fallback](#prover-selection--solver-fallback) - - [Unmapped Axiom Warnings](#unmapped-axiom-warnings) +| # | Page | Read it when you want to... | +|---|------|------------------------------| +| 1 | [Installation](installation.md) | Build the tools, add solvers and diagram renderers, install the editor extension | +| 2 | [Quickstart](quickstart.md) | Go from an empty file to a checked, compiled, visualized ontology in 10 minutes | +| 3 | [Language reference](language-reference.md) | Look up every form the parser accepts, plus imports and search paths | +| 4 | [Axioms and reasoning](axioms-and-reasoning.md) | Understand what the linter and solvers check, SAT vs UNSAT, timeouts, prover choice | +| 5 | [CLI reference](cli-reference.md) | Find a flag, a target name, or an exit code | +| 6 | [Targets and emitters](targets-and-emitters.md) | See what each target writes and which constraints it can express | +| 7 | [Visualization](visualization.md) | Produce Mermaid and D2 diagrams and render them | +| 8 | [REPL](repl.md) | Explore an ontology interactively | +| 9 | [Editor and LSP](editor-and-lsp.md) | Get diagnostics, hover, completion, and solver commands in an editor | +| 10 | [Standard library](standard-library.md) | Import BFO, MITRE, NIST and other bundled ontologies | +| 11 | [Domain examples](domain-examples.md) | Browse worked domain ontologies and their conflict fixtures | +| 12 | [Troubleshooting](troubleshooting.md) | Decode an error message or a surprising result | +| 13 | [FAQ](faq.md) | Quick answers to common questions | ---- +## The workflow in one picture -## Getting Started - -### Prerequisites - -- **Haskell Toolchain:** [Stack](https://docs.haskellstack.org/) (recommended) or GHC 9.4.8 + Cabal 3.8+. -- **External Automated Theorem Provers (Optional, recommended for automated reasoning):** - - **Z3** (`z3 >= 4.8.0`): `sudo apt-get install z3` or `brew install z3` - - **CVC5** (`cvc5 >= 1.0.0`): `sudo apt-get install cvc5` or `brew install cvc5` - - **Vampire** (`vampire >= 4.7`): Download from [Vampire Prover releases](https://vprover.github.io/) - - *Note:* If external solvers are not present in `PATH`, OntoLogic automatically falls back to its built-in native Semantic Tableaux and Resolution engines. -- **Visual Diagram Renderers (Optional):** - - **Mermaid CLI** (`mmdc`): `npm install -g @mermaid-js/mermaid-cli` - - **D2 CLI** (`d2`): `curl -fsSL https://d2lang.com/install.sh | sh -s --` - -### Installation & Build - -Clone the repository and compile with Stack: - -```bash -git clone https://github.com/bsommers/OntoLogic.git -cd OntoLogic - -# Build compiler, REPL, and LSP server -stack build - -# Run full test suite with coverage verification -./scripts/check_coverage.sh -``` - -To install the executables (`ontologic-exe` and `ontologic-lsp`) to `~/.local/bin`: - -```bash -stack install -``` - -### Two-Minute First Run - -Create a sample specification named `device.logic`: - -```lisp -;; device.logic - Sample Industrial Ontology -(namespace iot "http://example.org/iot#") - -(def-concept Device) -(def-property serial_number Device String :cardinality 1..1) -(def-property firmware_version Device String :default "1.0.0") - -(def-concept Sensor Device) -(def-property reading Sensor Float) -(def-property is_active Sensor Boolean :default True) - -;; Axiom: If a sensor is active, its reading must be positive -(forall (s) - (implies (Sensor s) - (implies (eq is_active True) (gt reading 0.0)))) -``` - -Validate and solve the ontology: - -```bash -# 1. Semantic Linting -stack exec ontologic-exe -- -i device.logic -t lint - -# 2. Automated SMT Satisfiability and Concept Coherence Check -stack exec ontologic-exe -- -i device.logic -t solve --prover auto - -# 3. Transpile to TypeScript / Zod schemas -stack exec ontologic-exe -- -i device.logic -t ts -o dist/ts/ - -# 4. Transpile to Python Pydantic v2 models -stack exec ontologic-exe -- -i device.logic -t python -o dist/py/ - -# 5. Transpile to PostgreSQL DDL with check constraints -stack exec ontologic-exe -- -i device.logic -t sql -o dist/schema.sql -``` - ---- - -## Core Concepts & DSL Syntax - -OntoLogic uses an S-expression syntax designed to balance human readability with strict mathematical semantics. - -### Concepts & Taxonomic Inheritance - -Concepts define ontological classes or entity types. Subtyping is declared by naming the parent concept: - -```lisp -(def-concept Vehicle) -(def-concept Aircraft Vehicle) -(def-concept Drone Aircraft) -``` - -- In BFO-grounded models, concepts derive transitively from foundational entities (e.g. `bfo:Continuant`, `bfo:Occurrent`). -- Cyclic inheritance (e.g. `A` subclass of `B`, `B` subclass of `A`) is strictly rejected by the semantic linter. - -### Properties, Types & Cardinalities - -Properties define strongly typed datatype attributes associated with a domain concept: - -```lisp -(def-property [:cardinality ] [:default ] [:optional ]) -``` - -#### Supported Types: -- `Integer`: Signed 64-bit integer (`int64`, `int64_t`, `i64`). -- `Float`: 32-bit IEEE-754 floating point number. -- `Double`: 64-bit IEEE-754 floating point number. -- `String`: UTF-8 textual string. -- `Boolean`: Truth value (`True` / `False`). -- ``: Custom object reference to another declared concept. - -#### Supported Cardinalities: -- `1..1` or `1`: Mandatory scalar (default for datatype properties). -- `0..1` or `optional`: Optional scalar (`Option`, `Optional`, `*T`, `null`). -- `0..*` or `*`: Arbitrary collection / array / list (`Vec`, `List`, `[]T`). -- `1..*`: Non-empty collection requiring at least one element. - -```lisp -(def-property port Server Integer :cardinality 1..1 :default "8080") -(def-property backup_ip Server String :optional True) -(def-property error_codes Server Integer :cardinality 0..*) -(def-property tags Server String :cardinality 1..*) -``` - -### Relations - -Relations define directed associations (object properties) between a domain concept and a range concept: - -```lisp -(def-relation connects_to Device Router :cardinality 0..*) -(def-relation manages Controller Robot) -``` - -In relational targets (`sql`), relations emit junction tables with foreign key cascades. In graph targets (`neo4j`), relations emit labeled edges (`-[:CONNECTS_TO]->`). - -### First-Order Logic Axioms & Constraints - -Axioms declare universal rules, bound constraints, or conditional invariants using standard FOL connectives: - -- **Quantifiers:** `(forall (x) ...)`, `(exists (x) ...)`, `(forall ((x Concept)) ...)`, `(exists ((x Concept)) ...)` -- **Connectives:** `(implies P Q)`, `(iff P Q)`, `(and P Q ...)`, `(or P Q ...)`, `(not P)` -- **Comparison Operators:** `(eq prop val)`, `(ne prop val)`, `(gt prop val)`, `(gte prop val)`, `(lt prop val)`, `(lte prop val)` -- **Constants:** `top` (truth), `bottom` (contradiction). - -#### Simple Bound Constraints: -```lisp -(forall (v) - (implies (Vehicle v) - (and (gte speed 0) (lte speed 120)))) -``` - -#### Multi-Premise Conditional Constraints: -```lisp -(forall (o) - (implies (and (Oven o) (eq is_active True)) - (gt temperature 100))) -``` - -### Modular Namespaces & Imports - -Ontologies can be split across modular files and reusable namespaces: - -```lisp -;; Declare namespace prefix and base IRI -(namespace sys "http://example.org/systems#") - -;; Import shared foundations -(import "ontologic-lib/bfo_2020.logic") -(import "common/types.logic") -``` - -The import engine performs cycle detection, deduplicates diamond imports, and resolves files relative to the current file, `--lib-path`, or `$ONTOLOGIC_PATH`. - ---- - -## Examples & Common Workflows - -### 1. Semantic Linting - -Run static checks to detect circular inheritance, undeclared types, or contradictory axioms prior to code generation: - -```bash -stack exec ontologic-exe -- -i examples/bfo_manufacturing.logic -t lint -``` - -Output: ```text -✅ Logic Validated successfully. + .logic files --parse+imports--> Registry --lint--> errors? stop + | + +--------------+---------------+ + v v + --solve (z3/cvc5/vampire/native) -t -o DIR + SAT / UNSAT / unknown code, schemas, diagrams ``` -If an error is present: -```text -examples/broken.logic:14:3: error: Circular inheritance detected: Vehicle -> Car -> Vehicle -``` - -### 2. Automated SMT Reasoning & Coherence Verification - -Verify satisfiability and concept coherence using external solvers or the native prover: - -```bash -# Check satisfiability using auto-discovered solver (Z3, CVC5, Vampire, or Native) -stack exec ontologic-exe -- -i ontologic-lib/stix_cve.logic -t solve --prover auto - -# Explicitly use Z3 with a 5-second timeout -stack exec ontologic-exe -- -i ontologic-lib/stix_cve.logic -t solve -p z3 -T 5 - -# Explain an unsatisfiable core if a logical contradiction exists -stack exec ontologic-exe -- -i broken.logic -t solve --explain-unsat - -# Inspect full model valuation for satisfiable specifications -stack exec ontologic-exe -- -i device.logic -t solve --inspect-model -``` - -### 3. Multi-Target Code Generation - -Generate code for polyglot systems from a single source of truth: - -```bash -# TypeScript / Zod validation schemas -stack exec ontologic-exe -- -i device.logic -t ts -o src/models/device.ts - -# Python Pydantic v2 models -stack exec ontologic-exe -- -i device.logic -t python -o src/models/device.py - -# Rust structs with validate() implementation -stack exec ontologic-exe -- -i device.logic -t rust -o src/models/device.rs - -# Go structs with Validate() methods -stack exec ontologic-exe -- -i device.logic -t go -o models/device.go - -# Java Jakarta Bean Validation models with package declaration -stack exec ontologic-exe -- -i device.logic -t java --java-package com.company.iot -o src/main/java/ - -# PostgreSQL / ANSI SQL schema with foreign keys and check constraints -stack exec ontologic-exe -- -i device.logic -t sql -o db/schema.sql - -# Neo4j Cypher schema & index creation script -stack exec ontologic-exe -- -i device.logic -t neo4j --neo4j-edition enterprise -o db/schema.cypher - -# W3C OWL/RDF XML and SHACL Turtle Shapes -stack exec ontologic-exe -- -i device.logic -t owl -o dist/device.owl -stack exec ontologic-exe -- -i device.logic -t shacl -o dist/device.shacl.ttl - -# Visual Diagrams (Mermaid and D2) -stack exec ontologic-exe -- -i device.logic -t mermaid -o diagrams/device.mmd -stack exec ontologic-exe -- -i device.logic -t d2 -o diagrams/device.d2 -``` - -### 4. Interactive REPL Exploration - -Launch the interactive REPL to prototype, inspect, and query ontologies interactively: - -```bash -stack exec ontologic-exe -- --repl -``` - -Session example: -```text -ontologic> (def-concept Asset) -Added to registry. - -ontologic> (def-concept Robot Asset) -Added to registry. - -ontologic> (def-property batteryLevel Robot Integer) -Added to registry. - -ontologic> (forall (r) (implies (Robot r) (and (gte batteryLevel 0) (lte batteryLevel 100)))) -Added to registry. - -ontologic> :show -Active Registry State: - Concepts: 2 -> ["Asset","Robot"] - Properties: 1 -> ["batteryLevel"] - Relations: 0 -> [] - Axioms: 1 - Prover: Auto (Z3/CVC5/Vampire/Native) - Loaded: - -ontologic> :prove Robot Asset -✅ Theorem Proved via Auto (Z3/CVC5/Vampire/Native): 'Robot' ⊑ 'Asset' (Every instance of Robot is necessarily a Asset). - -ontologic> :solve -✅ SMT Satisfiable (SAT) via Auto (Z3/CVC5/Vampire/Native) — Consistent Model Found: -sat -✅ All concepts are satisfiable (0 empty concepts). - -ontologic> :emit ts -import { z } from "zod"; - -export const AssetSchema = z.object({ -}); -export type Asset = z.infer; - -export const RobotSchema = AssetSchema.extend({ - batteryLevel: z.number().int().gte(0).lte(100), -}); -export type Robot = z.infer; - -ontologic> :quit -Goodbye! -``` - -### 5. Language Server Protocol (LSP) & Editor Setup - -OntoLogic includes an LSP server providing real-time IDE diagnostics, hover tooltips, and jump-to-definition. - -#### Start LSP Daemon: -```bash -stack exec ontologic-lsp -``` - -#### Install VS Code Extension: -The VS Code extension package is available under `dist/`: -```bash -code --install-extension dist/ontologic-1.0.0.vsix -``` - -Features provided in VS Code: -- Syntax highlighting for `.logic` files. -- Live squiggly diagnostics from the parser and semantic linter. -- Documentation hover tooltips for concepts, properties, relations, and quantifiers. -- Code action quickfixes to solve consistency (`ontologic.solve`) or explain UNSAT cores (`ontologic.explainUnsat`). - ---- - -## CLI Reference - -### Command-Line Options & Flags - -| Option / Flag | Type | Description | -|---|---|---| -| `-h`, `--help` | Flag | Show CLI help text and option overview. | -| `-i`, `--input ARG` | FilePath | Path to input `.logic` ontology file. | -| `-t`, `--target ARG` | String | Target action or emitter format (see list below). | -| `-o`, `--output ARG` | Path | Output directory or file destination for emitted code. | -| `-p`, `--prover ARG` | String | Theorem prover backend: `z3`, `cvc5`, `vampire`, `native`, `auto` (default: `auto`). | -| `-T`, `--solve-timeout SECONDS` | Integer | Wall-clock execution timeout passed to theorem prover (in seconds). | -| `--solve-memory MB` | Integer | Virtual memory limit in megabytes (passed to Z3 `-memory:`). | -| `--repl` | Flag | Launch the interactive ontology REPL session. | -| `--solve` | Flag | Run SMT consistency, satisfiability, and coherence checks (shorthand for `-t solve`). | -| `--explain-unsat` | Flag | Extract minimal unsatisfiable core explaining logical contradictions. | -| `--inspect-model` | Flag | Print satisfying model valuation assignments for satisfiable ontologies. | -| `--cnf` | Flag | Emit ontology in Clausal Normal Form (CNF) to stdout. | -| `--lsp` | Flag | Start Language Server Protocol stdio daemon. | -| `--java-package ARG` | String | Target package for Java models (default: `ontologic.generated`). | -| `--base-iri IRI` | URI | Custom base IRI override for RDF/OWL/SHACL emissions. | -| `--neo4j-edition EDITION` | String | Neo4j constraint edition: `community` or `enterprise` (default: `enterprise`). | -| `--render` | Flag | Render Mermaid/D2 diagrams to SVG/PNG using installed CLI tools (`mmdc` / `d2`). | -| `--warn-unmapped` | Flag | Display warnings for axioms that cannot be mapped to field-level constraints. | -| `--lib-path DIR` | Directory | Additional search directory for imported modules (repeatable). | - -### Compilation Targets - -Specify using `-t `: - -| Target | Description | Output Structure | -|---|---|---| -| `lint` | Static semantic linter & cycle detector | Stdio diagnostic report | -| `solve` | SMT consistency & concept coherence check | Stdio SAT/UNSAT report | -| `ts` | TypeScript interfaces & Zod validation schemas | `.ts` file | -| `python` | Python Pydantic v2 `BaseModel` classes | `.py` file | -| `rust` | Rust structs with `validate()` methods | `.rs` file | -| `go` | Go structs with `Validate()` methods | `.go` file | -| `java` | Java POJOs with Jakarta validation annotations | `.java` files in directory | -| `sql` | PostgreSQL / ANSI SQL DDL with check constraints | `.sql` file | -| `openapi` | OpenAPI 3.1 YAML component schemas | `.yaml` file | -| `graphql` | GraphQL Schema Definition Language (SDL) | `.graphql` file | -| `neo4j` | Neo4j Cypher schema & constraint scripts | `.cypher` file | -| `owl` | W3C OWL 2 / RDF XML ontology | `.owl` / `.rdf` file | -| `shacl` | W3C SHACL shapes in Turtle syntax | `.ttl` file | -| `jsonschema` | JSON Schema (Draft 2020-12) definitions | `.json` file | -| `protobuf` | Protocol Buffers v3 message definitions | `.proto` file | -| `cpp` | Modern C++20 header structs with `validate()` | `.hpp` file | -| `smt` | Raw SMT-LIB2 theory for external provers | `.smt2` file | -| `tptp` | TPTP FOF format for automated theorem provers | `.p` file | -| `mermaid` | Mermaid class diagram | `.mmd` file | -| `d2` | D2 declarative architecture diagram | `.d2` file | - -### Theorem Prover Backends - -Configure using `-p ` or `--prover `: - -- `auto` (Default): Discovers installed provers in `PATH` in order: **Z3** $\to$ **CVC5** $\to$ **Vampire**. If none are installed, gracefully falls back to the native **Semantic Tableaux** and **Ordered Resolution** reasoning engines. -- `z3`: Invokes the Z3 SMT solver via stdin with `-in` and optional `-T:` / `-memory:`. -- `cvc5`: Invokes CVC5 with `--lang=smt2 --incremental --finite-model-find`. -- `vampire`: Invokes Vampire in CASC / SMTCOMP mode. -- `native`: Uses OntoLogic's pure in-memory First-Order Semantic Tableaux and Resolution saturation engines without spawning any external processes. - -### Exit Codes - -| Exit Code | Meaning | -|---|---| -| `0` | Success / SMT Satisfiable (SAT) / Linting Passed | -| `1` | SMT Unsatisfiable (UNSAT) / Logical Contradiction / Lint Error / CLI Error | -| `2` | SMT Result Inconclusive / Solver Timeout / Resource Limit Exceeded | - -### Environment Variables - -- `ONTOLOGIC_PATH`: Colon-separated (`:`) list of directory paths searched for `(import "...")` files. - ---- - -## Troubleshooting & FAQ - -### Common Error Messages & Remedies - -#### 1. `Circular inheritance detected: A -> B -> A` -- **Cause:** Concept `A` inherits from `B`, while `B` directly or transitively inherits from `A`. -- **Remedy:** Break the cycle by refactoring mutual dependencies into a common parent concept or modeling interactions as `def-relation`. - -#### 2. `Undeclared concept / property / relation` -- **Cause:** A property or relation references a concept name that has not been defined in the current file or imported modules. -- **Remedy:** Ensure the referenced concept is defined using `(def-concept )` or imported via `(import "path.logic")`. Check for typos or namespace prefix mismatches. - -#### 3. `❌ SMT Unsatisfiable (UNSAT) — Logical Contradiction Detected!` -- **Cause:** Asserted axioms form a logical contradiction (e.g. an entity must be simultaneously greater than 100 and less than 50, or concept disjointness is violated). -- **Remedy:** Run with `--explain-unsat` to identify the minimal unsatisfiable core of conflicting axioms: - ```bash - stack exec ontologic-exe -- -i model.logic -t solve --explain-unsat - ``` - -#### 4. `Error: --output is required for target: ` -- **Cause:** Code generation targets (`ts`, `python`, `rust`, `go`, `java`, `sql`, etc.) write output to files and require `-o` / `--output`. -- **Remedy:** Provide the `-o` argument: - ```bash - stack exec ontologic-exe -- -i model.logic -t ts -o dist/models.ts - ``` - -### Prover Selection & Solver Fallback +The linter always runs first. If it finds an error, nothing else runs (no solving, no emission) and the exit code is 1. -**Q: Do I need Z3 or CVC5 installed to run OntoLogic?** -**A:** No. While Z3 and CVC5 offer high performance on massive industrial theories, OntoLogic bundles a fully native First-Order Semantic Tableaux engine and Robinson-resolution prover. Setting `-p native` or using `-p auto` when no solver is in `PATH` executes all proofs hermetically in memory. +## Related documents -### Unmapped Axiom Warnings +- Project overview: [../../README.md](../../README.md) +- Architecture: [../architecture.md](../architecture.md) +- Why constraints are mapped the way they are: [../dev/design/constraints_and_patterned.md](../dev/design/constraints_and_patterned.md), [../dev/design/constraint_considerations.md](../dev/design/constraint_considerations.md) +- Release notes: [../../CHANGELOG.md](../../CHANGELOG.md) -**Q: Why do I see `warning: [WUnmappedAxiom] ... could not be mapped to field constraints`?** -**A:** Target programming languages (TypeScript, Python, Go, Rust) represent record types and field validators. Existential assertions (e.g. $\forall x.\, \exists y.\, R(x, y)$) or cross-concept relational assertions cannot be expressed as static record field bounds. OntoLogic emits a warning while preserving these axioms in full for formal targets (SMT, TPTP, OWL, SHACL). To suppress these warnings during build scripts, omit the `--warn-unmapped` flag. +Next: [Installation](installation.md) diff --git a/docs/user-guide/axioms-and-reasoning.md b/docs/user-guide/axioms-and-reasoning.md new file mode 100644 index 0000000..cae1567 --- /dev/null +++ b/docs/user-guide/axioms-and-reasoning.md @@ -0,0 +1,202 @@ +# Axioms and reasoning + +OntoLogic checks an ontology in two layers. The linter is fast, runs on every invocation, and catches structural mistakes and obvious contradictions. The solvers (Z3, CVC5, Vampire, or the built-in native prover) are invoked with `--solve` and answer deeper questions: can all axioms hold at once (consistency), and can every concept have an instance (coherence)? This page explains what is checked, how to read SAT, UNSAT, and unknown results, and how to control time, memory, and prover choice. + +## What axioms can say + +Axioms are full first-order logic, not Horn clauses (see [Language reference](language-reference.md) for syntax). Typical uses: + +| Intent | Axiom | +|--------|-------| +| Disjointness | `(forall (x) (implies (Truck x) (not (Car x))))` | +| Property bound | `(forall (v) (implies (Vehicle v) (and (gte speed 0) (lte speed 130))))` | +| Required relation | `(forall ((t Truck)) (exists ((s Site)) (serves t s)))` | +| Subsumption | `(forall (x) (implies (Hybrid x) (Truck x)))` (also implied by `(def-concept Hybrid Truck)`) | +| Rule | `(forall (o) (implies (and (Oven o) (eq is_active True)) (gt temperature 100)))` | + +Cardinality (`:cardinality`), `:optional`, and `:default` on properties and relations shape generated code and schemas but are not part of the solver's logical theory. If you need a cardinality to take part in reasoning, state it as an axiom. + +Disjointness is not a separate keyword; write it as an implication to a negation, as above. The linter recognizes that pattern. + +## Layer 1: the linter + +`-t lint` (or any run, since the linter always goes first) checks: + +- Undeclared parents, property domains, and relation endpoints; duplicate concepts, properties, relations, and namespace prefixes. +- Circular inheritance. +- Direct contradictions inside one axiom (`P and not P`, asserted `bottom`). +- Impossible numeric ranges on one property (`gt 5` with `lt 3`), within one axiom and across axioms for a concept and its ancestors. +- A propositional/Horn pass over the hierarchy and disjointness axioms that finds concepts forced to be empty, for example a subclass of two disjoint concepts. + +```bash +ontologic-exe -i test/fixtures/domains/domain_mining_conflict.logic -t lint +``` + +```text +examples/domain_mining.logic:49:15: error: Property contradiction on methane_level: gt 5 and lt 3 +examples/domain_mining.logic:27:14: error: Cross-axiom contradiction on GasSensor.methane_level: gt 5 and lt 3 +examples/domain_mining.logic:27:14: error: Cross-axiom contradiction on GasSensor.methane_level: lt 3 and gt 5 +``` + +(Paths are printed in full in real output; they are shortened here.) Any lint error stops the run with exit code 1. Because the linter runs first, `--solve` on an ontology with lint errors prints those errors and does not reach the solver. + +Add `--warn-unmapped` to also report axioms that the field-constraint emitters cannot express (see below). + +## Layer 2: the solvers + +`--solve` (or `-t solve`) translates the ontology to a first-order theory over one sort, `Entity`, and runs two checks. + +How the translation works (`src/FOLTheory.hs`): + +| Source | Solver encoding | +|--------|-----------------| +| concept `C` | predicate `is_C(x)` | +| `(def-concept C P)` | `is_C(x) => is_P(x)` | +| relation `r` | predicate `rel_r(x, y)`, with domain and range implications | +| data property `p : T` | function `prop_p(x) -> T` (`Int`, `Real`, `Bool`, `String`) | +| entity-valued property | treated as a relation | +| comparison `(gt p v)` in a quantifier | `prop_p() > v` | +| `def-individual i C` | constant `ind_i`, asserted to be a `C` | +| any other predicate | uninterpreted predicate `up_P` | + +1. **Consistency.** Can all translated axioms be true together? Result: SAT (a model exists), UNSAT (contradiction), or unknown (timeout, resource limit, or the solver gave up). +2. **Coherence.** For each concept, is there a model in which it has at least one instance? Concepts that cannot are reported as empty or unsatisfiable. A contradictory ontology makes every concept empty, which is why the UNSAT example below lists them all. + +### Axioms that are not sent + +Some axioms cannot be translated. They are listed before the verdict, and the verdict says how many were checked: + +```text +⚠️ 1 axiom(s) were not sent to the solver: + - ForAll "c" (Implies (And (Predicate "Controller" [Var "c"]) (Eq (Var "safety_status") (Constant "False"))) (Eq (Var "active") (Constant "False"))) (unbound variable active) +✅ SMT Satisfiable (SAT) — Ontology is logically consistent for the 1 axioms checked. +``` + +Common reasons: an unbound variable, a comparison outside any quantifier, an ordering comparison on a non-numeric property, a property used with conflicting types, a predicate used with different arities. A SAT verdict only covers the axioms actually sent. Fix the axiom or use `--free-constants`. + +### `--free-constants` + +By default a variable that is free (not bound by a quantifier, not a declared individual, concept, relation, or property) is an error for that axiom (it is skipped). With `--free-constants`, such names become `Entity` constants: + +```bash +ontologic-exe -i free.logic --solve +ontologic-exe -i free.logic --solve --free-constants +``` + +```text +⚠️ 1 axiom(s) were not sent to the solver: + - ForAll "x" (Implies (Predicate "A" [Var "x"]) (Predicate "Open" [Var "y"])) (unbound variable in predicate Open) +✅ SMT Satisfiable (SAT) — Ontology is logically consistent for the 0 axioms checked. +... +ℹ️ Free constants mode enabled (--free-constants): undeclared free variables are treated as Entity constants. +✅ SMT Satisfiable (SAT) — Ontology is logically consistent. +``` + +## Reading results + +| Output | Meaning | Exit | +|--------|---------|------| +| `✅ SMT Satisfiable (SAT)` and `✅ All concepts are satisfiable` | Consistent and coherent | 0 | +| `❌ SMT Unsatisfiable (UNSAT)` | The axioms contradict each other | 1 | +| `❌ Unsatisfiable / empty concept(s): A B` | Those concepts cannot have instances | 1 | +| `⚠️ SMT Solver Result (unknown): ...` | Timeout, limit, or solver gave up; not a proof either way | 2 | +| `❌ SMT Solver Error: ...` | The solver ran and failed | 1 | +| `⚠️ Concept coherence check could not run` | Coherence step failed | 2 | + +When several checks run, the worst code wins: 1 beats 2 beats 0. + +### `--explain-unsat` + +When the verdict is UNSAT, `--explain-unsat` re-runs the problem with every axiom named and prints the unsatisfiable core, the subset of axioms that already contradict each other: + +```bash +ontologic-exe -i unsat.logic -t solve --explain-unsat +``` + +```text +❌ SMT Unsatisfiable (UNSAT) — Logical contradiction detected! +🔍 Unsatisfiable Core Conflicting Axioms: + • Axiom #1: forall a (Account(a) implies gte(balance, 100)) + • Axiom #2: exists a (Account(a) and lt(balance, 50)) +❌ Unsatisfiable / empty concept(s): Account Frozen +``` + +The numbers are the axioms' positions in the file. In the REPL use `:explain`. + +### `--inspect-model` + +For a satisfiable ontology, `--inspect-model` prints the solver's model: a finite universe of `Entity` values and the interpretation of every `is_C`, `rel_r`, and `prop_p` symbol. It is useful to see a concrete witness, and to notice when a constraint you expected is not binding. + +```bash +ontologic-exe -i fleet.logic --solve --inspect-model +``` + +```text +✅ SMT Satisfiable (SAT) — Ontology is logically consistent. + +📋 SMT Model Valuation: +( +;; universe for Entity: +;; Entity!val!1 Entity!val!2 Entity!val!0 +... +(define-fun prop_speed ((x!0 Entity)) Int +1) +``` + +A model is one possible world, usually a tiny one. Concepts that are empty in this particular model are not necessarily unsatisfiable; the coherence check is what decides that. + +## Prover choice + +`-p/--prover` takes `z3`, `cvc5`, `vampire`, `native`, or `auto` (default); anything else is an error (`Unknown prover 'bogus'. Valid options: z3, cvc5, vampire, native, auto`, exit 1). + +| Prover | Notes | +|--------|-------| +| `z3` | External. Handles integer and real bounds well; supports `-T` and `--solve-memory`. Good default | +| `cvc5` | External. Run with finite-model finding and unsat-core support; supports `-T` | +| `vampire` | External. First-order specialist; given SMT-LIB or TPTP input; supports `-T` | +| `native` | Built into the binary (tableau and resolution). No install needed; honours `-T`; reports unknown on step or clause limits | +| `auto` | Tries `z3`, `cvc5`, `vampire` in order, skipping any that is not installed; if none is installed, falls back to `native`. A solver that is installed but fails is reported, not skipped | + +Practical guidance: use `z3` or `cvc5` for ontologies with numeric property bounds. On the balance example above, `z3` and `cvc5` report UNSAT while `native` and `vampire` report SAT, because they do not reason about the numeric comparisons the way an SMT solver does. The domain fixtures in `test/fixtures/domains/` are checked with Z3 (then CVC5) for the same reason. For purely taxonomic and relational reasoning, all backends agree. If two provers disagree, trust UNSAT from an SMT solver and treat the other's SAT as incomplete. + +## Time and memory limits + +```bash +ontologic-exe -i big.logic --solve -p z3 -T 60 --solve-memory 2048 +``` + +| Flag | Applies to | Behaviour | +|------|-----------|-----------| +| `-T/--solve-timeout SECONDS` | z3, cvc5, vampire, native | Positive integer. Each backend gets its own limit flag; external solvers are also killed after the limit plus a 2 second grace period. A timeout is reported as unknown (exit 2), never as an error | +| `--solve-memory MB` | z3 only | Positive integer. With `-p cvc5|vampire|native` it prints `⚠️ --solve-memory is not supported by CVC5 and is ignored.`; with `auto` it warns it applies only if Z3 is the selected prover | + +Zero and negative values are rejected: `option -T: expected a positive integer, got '0'`. For Z3 and CVC5 the coherence check runs all concepts in one solver process, so `-T` is a single budget for that whole batch; Vampire and native get the budget once per concept. + +## Subsumption proofs + +"Is every Truck necessarily a Vehicle?" is answered in the [REPL](repl.md) with `:prove Truck Vehicle`; a counterexample model is printed when the answer is no. There is no CLI flag for it. + +## From axioms to generated code + +Emitters work on the same parsed model but not through the solver. Axioms shaped like `forall x. Concept(x) implies comparisons` become field constraints; others are reported as unmapped (a `⚠️ Warning` on the CLI plus a comment in the output file, where the format allows). Targets without a built-in unmapped warning can be asked with `--warn-unmapped`. A clean `--solve` does not mean every axiom is enforced at runtime in generated code; see [Targets and emitters](targets-and-emitters.md). + +## CNF output + +`--cnf` prints the clausal normal form the native prover works with and exits, which helps to debug how an axiom is understood: + +```bash +ontologic-exe -i fleet.logic --cnf +``` + +```text +~Car(X1) | ~Truck(X1) +~Car(X1) | Vehicle(X1) +~Truck(X1) | Vehicle(X1) +~Truck(X1) | gte(X2, 0) +~Vehicle(X1) | gte(X2, 0) +~Vehicle(X1) | lte(X2, 130) +~drives(X1, X2) | Driver(X1) +~drives(X1, X2) | Vehicle(X2) +``` + +Next: [CLI reference](cli-reference.md) diff --git a/docs/user-guide/cli-reference.md b/docs/user-guide/cli-reference.md new file mode 100644 index 0000000..18462e1 --- /dev/null +++ b/docs/user-guide/cli-reference.md @@ -0,0 +1,125 @@ +# CLI reference + +The compiler executable is `ontologic-exe` (named `ontologic` in release tarballs). One invocation loads one input file, lints it, and then does exactly one thing: print the CNF, run the solver, or emit a target. This page lists every flag, every target (with aliases), the order in which modes are chosen, environment variables, and exit codes. + +```text +ontologic-exe [-i|--input FILE] [-t|--target TARGET] [-o|--output PATH] + [--java-package PKG] [--base-iri IRI] [-p|--prover NAME] + [--neo4j-edition EDITION] [--render] [--repl] [--cnf] [--lsp] + [--solve] [--warn-unmapped] [--explain-unsat] [--inspect-model] + [--free-constants] [-T|--solve-timeout SECONDS] + [--solve-memory MB] [--lib-path DIR] +``` + +## Flags + +| Flag | Argument | Description | +|------|----------|-------------| +| `-h`, `--help` | | Print usage and exit | +| `-i`, `--input` | FILE | Path to the `.logic` file. Required except with `--repl`/`--lsp` | +| `-t`, `--target` | TARGET | A target below, or `lint`, `solve`, `repl`, `lsp`. Default is `lint` | +| `-o`, `--output` | PATH | Output directory (created if missing). Required for every emitter target; ignored by `lint` and `solve` | +| `--java-package` | PKG | Package for the `java` target. Default `ontologic.generated` | +| `--base-iri` | IRI | Base IRI for `owl` and `shacl`. Default: the ontology's first namespace IRI (trailing `#` or `/` stripped), else `http://example.org/ontologic` | +| `-p`, `--prover` | z3, cvc5, vampire, native, auto | Solver backend for `--solve`. Default `auto` | +| `--neo4j-edition` | community, enterprise | Edition for `neo4j` constraints. Default `enterprise`; with `community`, node-property-existence constraints are written commented out | +| `--render` | | After `mermaid` or `d2` generation, call `mmdc` or `d2` to write an `.svg` | +| `--repl` | | Start the interactive REPL (same as `-t repl`) | +| `--cnf` | | Print the clausal normal form of the (linted) ontology to stdout and exit | +| `--lsp` | | Start the Language Server on stdin/stdout (same as `-t lsp`) | +| `--solve` | | Run the consistency and coherence checks (same as `-t solve`) | +| `--warn-unmapped` | | Report axioms that cannot be mapped to field constraints, even for targets that do not warn by default. With `-t lint` this is the only way to see them | +| `--explain-unsat` | | With `--solve`: on UNSAT print the unsatisfiable core | +| `--inspect-model` | | With `--solve`: on SAT print the full model valuation | +| `--free-constants` | | Treat undeclared free variables in axioms as `Entity` constants (applied before linting and solving) | +| `-T`, `--solve-timeout` | SECONDS | Positive integer. Enforced for z3, cvc5, vampire, and native | +| `--solve-memory` | MB | Positive integer. Z3 only; ignored with a warning for other provers | +| `--lib-path` | DIR | Extra import search directory; repeatable. Also `$ONTOLOGIC_PATH` | + +## Which mode runs + +Checked in this order after the file loads and lints cleanly: + +1. `--lsp` or `-t lsp`: start the language server (no input needed). +2. `--repl` or `-t repl`: start the REPL (no input needed). +3. Otherwise `-i` is required (`Error: --input is required (or use --repl / --lsp)`, exit 1). +4. Load the file and its imports. Failure: parse or import error printed, exit 1. +5. Lint. Any error: errors printed, exit 1. Nothing further runs. +6. `--cnf`: print CNF, exit 0. +7. `--solve` or `-t solve`: run the solver. +8. Otherwise the target: `lint` (the default) prints `✅ Logic Validated successfully.`; an emitter writes files into `-o`. + +So `--cnf` wins over `--solve`, which wins over `-t `. + +## Targets + +Names accepted by `-t`; aliases are equivalent. "Unmapped" says whether unmapped-axiom warnings are on by default (`--warn-unmapped` turns them on for the rest). + +| Target | Aliases | Files written | Unmapped by default | +|--------|---------|---------------|---------------------| +| `java` | | one `.java` per concept, plus `package-info.java` if there are unmapped axioms | yes | +| `python` | | `models.py` | yes | +| `rust` | | `models.rs` | yes | +| `go` | `golang` | `models.go` | yes | +| `ts` | `typescript`, `zod` | `models.ts` | yes | +| `openapi` | | `openapi.yaml` | yes | +| `graphql` | `gql` | `schema.graphql` | yes | +| `smt` | `smtlib` | `spec.smt2` | no | +| `neo4j` | | `graph.cypher`, `constraints.cypher` | no | +| `owl` | | `ontology.owl` | no | +| `jsonschema` | `json` | `schema.json` | yes (CLI only; JSON has no comments) | +| `shacl` | | `shapes.ttl` | no | +| `mermaid` | | `class_diagram.mmd` (+ `.svg` with `--render`) | no | +| `d2` | | `diagram.d2` (+ `.svg` with `--render`) | no | +| `protobuf` | `proto`, `proto3` | `schema.proto` | no | +| `cpp` | `c++` | `models.hpp` | yes | +| `sql` | `postgres`, `postgresql`, `ddl` | `schema.sql` | yes | +| `tptp` | `p`, `fof` | `theory.p` | yes | + +Special targets: `lint`, `solve`, `repl`, `lsp`. An unknown name prints `Unknown target: foo` and exits 1; an emitter without `-o` prints `Error: --output is required for target: ts` and exits 1. Details for each emitter: [Targets and emitters](targets-and-emitters.md). + +Each successful emission prints `Generated
`, for example `Generated TypeScript/Zod models in out/ts`. + +## Environment variables + +| Variable | Effect | +|----------|--------| +| `ONTOLOGIC_PATH` | `:`-separated list of directories searched for imports, after `--lib-path` directories and before the built-in locations | + +External solvers (`z3`, `cvc5`, `vampire`) and renderers (`d2`, `mmdc`) are located through `PATH`. + +## Exit codes + +| Code | When | +|------|------| +| 0 | Lint passed; files emitted; `--cnf` printed; `--solve` found the ontology consistent and every concept satisfiable; REPL/LSP exited normally | +| 1 | Missing `--input`; file not found; parse error; import error (not found, circular); any lint error; unknown target; missing `-o`; unknown `--prover`; `--solve` reported UNSAT, empty concepts, or a solver error | +| 2 | `--solve` was inconclusive: the solver answered `unknown` (including a timeout), or the coherence check could not run | + +Command-line parse errors (for example a non-positive `-T`) print the message plus usage and exit 1. For `--solve` with several results, the worst wins (1 over 2 over 0), which makes it safe in CI: + +```bash +ontologic-exe -i model.logic -t solve -p z3 -T 60 || { echo "ontology check failed"; exit 1; } +``` + +## Example invocations + +```bash +ontologic-exe -i fleet.logic -t lint # lint only +ontologic-exe -i fleet.logic -t lint --warn-unmapped # also list unmapped axioms +ontologic-exe -i fleet.logic --solve -p cvc5 -T 30 # solve with a timeout +ontologic-exe -i fleet.logic -t java -o out/java --java-package com.acme.fleet +ontologic-exe -i fleet.logic -t owl -o out/owl --base-iri http://example.org/other# +ontologic-exe -i fleet.logic -t neo4j -o out/neo --neo4j-edition community +ontologic-exe -i app.logic -t ts -o out/ts --lib-path ./shared +``` + +`--warn-unmapped` with lint: + +```text +⚠️ Warning: 1 complex / conditional axiom(s) could not be mapped to target models field constraints: +fleet.logic:17:2: warning: [WUnmappedAxiom] forall v (Truck(v) implies not Car(v)) +✅ Logic Validated successfully. +``` + +Next: [Targets and emitters](targets-and-emitters.md) diff --git a/docs/user-guide/domain-examples.md b/docs/user-guide/domain-examples.md new file mode 100644 index 0000000..e48240b --- /dev/null +++ b/docs/user-guide/domain-examples.md @@ -0,0 +1,65 @@ +# Domain examples + +The repository includes worked ontologies for realistic domains (mining, cloud data centers, security and trust, and more), each paired with a deliberately broken variant so you can see what a contradiction looks like. The gallery, with a description of each domain, is written separately: [../domains/README.md](../domains/README.md). This page explains how the files are organized and how to run them. + +## Layout + +| Path | Contents | +|------|----------| +| `examples/domain_*.logic` | The domain ontologies, for example `examples/domain_mining.logic`, `examples/domain_cloud_datacenter.logic`, `examples/domain_security_trust.logic` | +| `test/fixtures/domains/.expect` | The expected verdict for the ontology of that name | +| `test/fixtures/domains/_conflict.logic` | A variant that imports the domain file and adds an axiom that contradicts it | + +Each domain example has an `.expect` file and a `_conflict` fixture under `test/fixtures/domains/`. They are checked by `test/DomainExamplesSpec.hs`: + +- A guard fails if an `examples/domain_*.logic` file has no `.expect` fixture. +- The `.expect` file is a list of lines such as `concept Excavator`, `relation drives`, or `property methane_level` (`#` starts a comment); each named symbol must be declared in the loaded ontology. +- The ontology must be satisfiable (SAT). +- The `_conflict` variant must be unsatisfiable (UNSAT). This check uses Z3, falling back to CVC5, because the conflicts involve numeric bounds; it is marked pending when neither is installed. All solves use a 30 second limit. + +The test asks the solver directly. On the command line the linter catches these conflicts first, so the CLI reports lint errors rather than an UNSAT verdict (shown below). + +## Try one + +```bash +ontologic-exe -i examples/domain_mining.logic -t lint +ontologic-exe -i examples/domain_mining.logic -t solve -p z3 +``` + +```text +✅ Logic Validated successfully. +✅ SMT Satisfiable (SAT) — Ontology is logically consistent. +✅ All concepts are satisfiable (0 empty concepts). +``` + +Now the conflict variant, which is the import plus one extra axiom: + +```lisp +(import "examples/domain_mining.logic") +(forall (s) + (implies (GasSensor s) + (and (gt methane_level 5) (lt methane_level 3)))) +``` + +```bash +ontologic-exe -i test/fixtures/domains/domain_mining_conflict.logic -t lint +``` + +```text +examples/domain_mining.logic:49:15: error: Property contradiction on methane_level: gt 5 and lt 3 +examples/domain_mining.logic:27:14: error: Cross-axiom contradiction on GasSensor.methane_level: gt 5 and lt 3 +examples/domain_mining.logic:27:14: error: Cross-axiom contradiction on GasSensor.methane_level: lt 3 and gt 5 +``` + +(Real output prints full paths.) The `(import "examples/...")` path resolves relative to the current directory, so run these from the repository root. + +Compile a domain to code or diagrams the same way as any ontology: + +```bash +ontologic-exe -i examples/domain_cloud_datacenter.logic -t d2 -o diagrams --render +ontologic-exe -i examples/domain_security_trust.logic -t ts -o out/ts +``` + +The `examples/` directory also holds generated artifacts (`.mmd`, `.d2`, `.d2.svg`, `.cypher`) next to each `.logic` file. + +Next: [Troubleshooting](troubleshooting.md) diff --git a/docs/user-guide/editor-and-lsp.md b/docs/user-guide/editor-and-lsp.md new file mode 100644 index 0000000..ce8bfee --- /dev/null +++ b/docs/user-guide/editor-and-lsp.md @@ -0,0 +1,95 @@ +# Editor and LSP + +OntoLogic ships a Language Server (`ontologic-lsp`, or `ontologic-exe --lsp`) that speaks LSP over stdin/stdout, and a VS Code extension (`editors/vscode`) that wraps it. You get live diagnostics from the same linter the CLI uses, hover, completion, go-to-definition, rename, formatting, semantic highlighting, and commands that run the solver on the open file. Any LSP-capable editor can use the server directly. + +## What the server provides + +Capabilities reported by `initialize`: + +| Feature | Detail | +|---------|--------| +| Diagnostics | Published on open and on every change. Parse errors, plus all linter findings with line and column (`source: ontologic-linter`). Imports are resolved first, so a concept defined in an imported file is not reported as undeclared; problems that belong to the imported files are not shown on yours | +| Completion | Triggered on `(`, space, and `"`. Offers keywords, primitive types, and the concepts, properties, and relations of the document and its imports | +| Hover | Concepts (parent, properties), properties (domain, type, cardinality, default), relations, and keywords (syntax summary). Comment lines directly above a `def-concept` or `def-property` appear as documentation | +| Go to definition | Jumps to the `def-concept`, `def-property`, or `def-relation` line for the symbol under the cursor, in the open document (not into imported files) | +| Rename | `prepareRename` and `rename` of concepts, properties, and relations across the document; rejects keywords and invalid names | +| Formatting | Re-indents the whole document (honours the editor's tab size) | +| Semantic tokens | Keyword, type, class, property, function, variable, string, number, comment, operator | +| Code actions | Quick-fix entries "Verify SMT Consistency", "Explain SMT Unsatisfiable Core", "Inspect SMT Satisfying Model" | +| Execute command | `ontologic.solve`, `ontologic.explainUnsat`, `ontologic.inspectModel`. They run asynchronously with progress notifications and can be cancelled; they always use the `auto` prover | + +Imports use the same search path as the CLI, including `$ONTOLOGIC_PATH` (set it in the environment the editor is launched from). The server has no `--lib-path` option. + +A diagnostic exchange, abbreviated: + +```json +{"method":"textDocument/publishDiagnostics","params":{"uri":"file:///tmp/bad.logic","diagnostics":[{"range":{"start":{"line":3,"character":13},"end":{"line":3,"character":100}},"severity":1,"source":"ontologic-linter","message":"Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car."}]}} +``` + +## VS Code extension + +### Install + +```bash +./editors/vscode/scripts/build_extension.sh # npm install, compile, package a .vsix +code --install-extension editors/vscode/ontologic-*.vsix +``` + +The extension activates for `.logic` files (language id `ontologic`). It finds the language server in this order: an absolute `ontologic.lsp.path`; `bin/ontologic-lsp` or `dist/ontologic-lsp` in the workspace; a Stack build under the workspace; `~/.local/bin/ontologic-lsp`; then plain `ontologic-lsp` on `PATH`. The easiest setup is `stack install`, which puts `ontologic-lsp` in `~/.local/bin`. + +### Features + +- TextMate syntax highlighting and bracket/comment configuration. +- Snippets for `def-concept`, `def-concept-subclass`, `def-relation`, `axiom`, `axiom-forall`, and `import`. **Caution:** the concept, axiom, and subclass snippets were written for an older syntax (`(subclass-of ...)`, `(axiom ...)`, `=>`, inline property lists, `between`) and expand to forms the current parser rejects. Only `def-relation` and `import` expand to valid code; write concepts and axioms as shown in the [Language reference](language-reference.md). +- Everything in the table above via the language server. + +### Commands + +Open the Command Palette and type "OntoLogic". + +| Command | What it does | +|---------|--------------| +| OntoLogic: Restart Language Server | Stop and start `ontologic-lsp` (use after rebuilding the binary) | +| OntoLogic: Check SMT Consistency & Satisfiability | Saves the file and runs the CLI: `-i FILE -t solve --prover `; shows SAT/UNSAT in a message and the full output in the "OntoLogic" output channel | +| OntoLogic: Check Concept Satisfiability | Saves the file and runs the REPL's `:load` and `:unsat` | +| OntoLogic: Verify SMT Consistency (AutoProver) | LSP `ontologic.solve` | +| OntoLogic: Explain SMT Unsatisfiable Core | LSP `ontologic.explainUnsat` | +| OntoLogic: Inspect SMT Satisfying Model | LSP `ontologic.inspectModel` | + +### Settings + +| Setting | Default | Meaning | +|---------|---------|---------| +| `ontologic.lsp.path` | `ontologic-lsp` | Language server executable | +| `ontologic.cli.path` | empty | CLI executable (`ontologic` or `ontologic-exe`). Empty means: next to the language server, then a Stack build in the workspace, then `PATH` | +| `ontologic.solver.prover` | `auto` | `auto`, `z3`, `cvc5`, or `vampire`; used by "Check SMT Consistency & Satisfiability" only. The LSP-backed commands always use `auto` | +| `ontologic.trace.server` | `off` | `off`, `messages`, or `verbose` JSON-RPC tracing | + +In an untrusted workspace the three path/prover settings are restricted, so a repository cannot make the extension run an arbitrary binary. + +To debug the connection, set `ontologic.trace.server` to `verbose` and open View > Output > OntoLogic. + +## Other editors + +Any client that can launch a stdio server works. The server needs no arguments. For Neovim with `nvim-lspconfig`: + +```lua +local lspconfig = require('lspconfig') +local configs = require('lspconfig.configs') + +if not configs.ontologic_lsp then + configs.ontologic_lsp = { + default_config = { + cmd = { 'ontologic-lsp' }, + filetypes = { 'logic', 'lisp' }, + root_dir = lspconfig.util.root_pattern('.git', 'package.yaml'), + settings = {}, + }, + } +end +lspconfig.ontologic_lsp.setup{} +``` + +Map `*.logic` to a filetype your config lists (here `logic`). For other editors use `ontologic-lsp` (or `ontologic-exe --lsp`) as the server command over stdio, with the document language `ontologic` or `.logic` as the file pattern. + +Next: [Standard library](standard-library.md) diff --git a/docs/user-guide/faq.md b/docs/user-guide/faq.md new file mode 100644 index 0000000..900ffc1 --- /dev/null +++ b/docs/user-guide/faq.md @@ -0,0 +1,80 @@ +# FAQ + +Short answers to common questions, with links to the pages that go deeper. + +**What is OntoLogic for?** +Writing a domain model once as first-order logic, proving it is consistent, and generating the code, schemas, and diagrams from it so they cannot drift apart. See the [Quickstart](quickstart.md). + +**Is the language Prolog or Datalog?** +No. Axioms are full first-order logic (disjunction, negation, existentials), not restricted to Horn clauses. See [Axioms and reasoning](axioms-and-reasoning.md) and [../dev/design/constraint_considerations.md](../dev/design/constraint_considerations.md). + +**Do I need Z3, CVC5, or Vampire?** +No. Without any of them `--prover auto` uses a built-in native prover. But the native prover does not reason about numeric bounds like `(gt level 10)`, so install Z3 or CVC5 if your properties have numeric constraints. See [Installation](installation.md). + +**Which prover should I use?** +Z3 for most ontologies; CVC5 as a second opinion; Vampire for heavy first-order reasoning without arithmetic; native when nothing is installed. If provers disagree, trust UNSAT from an SMT solver. + +**What is the difference between lint and solve?** +Lint is a fast structural and pattern check that always runs. Solve invokes a theorem prover to find contradictions that need real reasoning, and also checks that every concept can have an instance. A lint error stops everything, so `--solve` only runs on lint-clean input. See [Axioms and reasoning](axioms-and-reasoning.md#layer-1-the-linter). + +**What do "SAT" and "UNSAT" mean here?** +SAT: the axioms can all be true in some world, so the ontology is consistent. UNSAT: they cannot, so there is a contradiction (use `--explain-unsat` to see which axioms). `unknown`, exit code 2, is neither: the solver ran out of time or gave up. + +**Why does `--solve` say a concept is "empty"?** +The axioms force that concept to have no instances (for example, it inherits two incompatible bounds, or a contradiction exists). It is a modelling error even if the whole ontology is otherwise consistent. + +**Does the solver enforce cardinality such as `1..*`?** +No. Cardinality, `:optional`, and `:default` shape generated code (optional vs list fields, `NOT NULL`, SHACL counts). If you need them in reasoning, state them as axioms. + +**How do I say two concepts are disjoint?** +`(forall (x) (implies (Truck x) (not (Car x))))`. The linter and solvers both understand it. There is no dedicated keyword. + +**Why "could not be mapped to field constraints"?** +Emitters can turn `forall x. Concept(x) implies ` into field constraints. Disjointness, existentials, and relational rules have no field-level form, so they are reported (and written as a comment) instead. They are still verified by `--solve`. See [Targets and emitters](targets-and-emitters.md#unmapped-axioms). + +**Can I generate several targets at once?** +One target per invocation. Script it: `for t in ts python sql; do ontologic-exe -i m.logic -t $t -o out/$t; done`. File names inside each directory are fixed. + +**Where does the output go, and can I choose file names?** +Into the `-o` directory (created if needed) under fixed names such as `models.ts` and `schema.sql`; rename afterwards. See the file table in the [CLI reference](cli-reference.md#targets). + +**How do I set the Java package or OWL base IRI?** +`--java-package com.acme.fleet` and `--base-iri http://example.org/ns#`; in the REPL, `:set java-package ...` and `:set base-iri ...`. Without `--base-iri`, the first `namespace` declaration is used. + +**Can I split an ontology across files?** +Yes: `(import "file.logic")`. Imports are found next to the importing file, then via `--lib-path`, `$ONTOLOGIC_PATH`, and the bundled library. See [Language reference](language-reference.md#imports-and-search-path). + +**Why can't I use a quoted namespace prefix?** +The prefix is an identifier: `(namespace bfo "http://...")`. Some older docs show `(namespace "bfo" ...)`, which does not parse. + +**Can I declare individuals (instances)?** +Yes: `(def-individual depot1 Site)`. They can be used as terms in axioms. Larger instance data is better kept in a data format such as Turtle (see `test/fixtures/ecosystem_symbols.ttl` for a small sample). + +**How do I use the standard ontologies like BFO or MITRE ATT&CK?** +`(import "bfo_2020.logic")` and refer to concepts with their prefix (`bfo:Process`). See [Standard library](standard-library.md). + +**How do I get diagrams?** +`-t mermaid` or `-t d2`, add `--render` for SVGs (needs `mmdc` or `d2`). See [Visualization](visualization.md). + +**Can I put OntoLogic in CI?** +Yes. `ontologic-exe -i model.logic -t lint` exits non-zero on any lint error, and `--solve` exits 1 on UNSAT or empty concepts and 2 on unknown. Add `-T` to bound the runtime. See [CLI reference](cli-reference.md#exit-codes). + +**A solve takes forever. What can I do?** +Set `-T 60` so it ends with exit 2 instead of hanging, try another prover, check `--cnf` for blow-up, or split the ontology. Z3 also accepts `--solve-memory MB`. + +**Why does the REPL not show my multi-line form?** +Each REPL line is parsed independently. Enter the form on one line, or `:load` a file. + +**How do I check a subclass relationship?** +In the REPL, `:prove Truck Vehicle`. See [REPL](repl.md). + +**How do I find where a lint error comes from in an imported file?** +Diagnostics carry the file and line of the declaration (`examples/domain_mining.logic:49:15: error: ...`), even when the root file is a different one. + +**Which version am I running?** +The package version is in `package.yaml` and [../../CHANGELOG.md](../../CHANGELOG.md). The CLI has no `--version` flag. + +**Where do I report problems or contribute?** +See the contributor workflow in the repository's `AGENTS.md`; the pre-push gate is `stack test --ghc-options="-Wall -Werror"`. + +Next: [README (guide index)](README.md) diff --git a/docs/user-guide/installation.md b/docs/user-guide/installation.md new file mode 100644 index 0000000..dc49c59 --- /dev/null +++ b/docs/user-guide/installation.md @@ -0,0 +1,83 @@ +# Installation + +OntoLogic is built with Stack (GHC 9.4.8, resolver `lts-21.25`) and produces two executables: `ontologic-exe` (compiler, solver driver, REPL) and `ontologic-lsp` (language server). SMT/ATP solvers (Z3, CVC5, Vampire) and diagram renderers (`d2`, `mmdc`) are optional external programs: without a solver OntoLogic falls back to a built-in native prover, and without a renderer it still writes the diagram source. + +## Build from source + +```bash +git clone OntoLogic +cd OntoLogic +stack build +stack exec ontologic-exe -- --help +``` + +Install both executables into `~/.local/bin`: + +```bash +stack install +ontologic-exe --help +``` + +Before contributing, the project's gate is `stack test --ghc-options="-Wall -Werror"`; `scripts/check_coverage.sh` runs the suite with coverage. + +Release tarballs (built by `scripts/package_release.sh`) lay out `bin/ontologic`, `bin/ontologic-lsp`, `ontologic-lib/`, `examples/`, and the `.vsix`. The CLI in a tarball is named `ontologic`; everywhere in this guide `ontologic-exe` and `ontologic` are the same program. In that layout the standard library is found automatically (see [Standard library](standard-library.md)). + +## Optional solvers + +OntoLogic talks to solvers by running them as child processes found on `PATH`. + +| Solver | Used for | Install | +|--------|----------|---------| +| Z3 | Default first choice; best for integer/real bounds on properties | `sudo apt-get install z3` / `brew install z3` | +| CVC5 | Second choice; finite-model finding | `sudo apt-get install cvc5` / `brew install cvc5` | +| Vampire | Third choice; strong on pure first-order reasoning | releases at the Vampire project site | + +With `--prover auto` (the default) OntoLogic tries `z3`, then `cvc5`, then `vampire`, moving on only when a binary is not installed. If none is installed it uses the native prover. Check what you have: + +```bash +z3 --version && cvc5 --version && vampire --version +``` + +Note that the native prover does not reason about numeric comparisons such as `(gt balance 100)`, so numeric contradictions are only found by Z3 or CVC5. See [Axioms and reasoning](axioms-and-reasoning.md). + +## Optional diagram renderers + +| Tool | Renders | Install | +|------|---------|---------| +| `d2` | `-t d2 --render` | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` | +| `mmdc` (Mermaid CLI) | `-t mermaid --render` | `npm install -g @mermaid-js/mermaid-cli` | + +If a renderer is missing, generation still succeeds and a warning is printed. Details in [Visualization](visualization.md). + +## Docker + +There is no OntoLogic image. The repository's `docker-compose.yml` starts a Neo4j 5.12 container and a Python validator container (`Dockerfile.python`, which mounts `./generated/python`) for trying the `neo4j` and `python` targets: + +```bash +docker-compose up +``` + +Neo4j listens on ports 7474 (web UI) and 7687 (Bolt); set `NEO4J_AUTH` to change the default credentials. + +## VS Code extension + +The extension (`editors/vscode`) adds highlighting, snippets, diagnostics, hover, completion, go-to-definition, rename, formatting, and solver commands. Build and install it: + +```bash +./editors/vscode/scripts/build_extension.sh # needs Node.js and npm +code --install-extension editors/vscode/ontologic-*.vsix +``` + +The extension needs the `ontologic-lsp` binary: put it on `PATH` (for example via `stack install`) or set `ontologic.lsp.path`. See [Editor and LSP](editor-and-lsp.md). + +## Verify the install + +```bash +ontologic-exe -i examples/smart_factory.logic -t lint +``` + +```text +✅ Logic Validated successfully. +``` + +Next: [Quickstart](quickstart.md) diff --git a/docs/user-guide/language-reference.md b/docs/user-guide/language-reference.md new file mode 100644 index 0000000..491df34 --- /dev/null +++ b/docs/user-guide/language-reference.md @@ -0,0 +1,215 @@ +# Language reference + +A `.logic` file is a sequence of parenthesized top-level forms in an S-expression syntax. This page lists every form the parser accepts, what it means, and a small example, then explains imports and how the search path is built. The authoritative source is `src/Parser.hs`. + +## Lexical rules + +| Item | Rule | +|------|------| +| Line comments | `;` or `//` to end of line | +| Block comments | `/* ... */` or `#| ... |#` | +| Identifiers | start with a letter or `_`, then letters, digits, and any of `_ : - . / + * '`. So `bfo:Entity`, `max-load`, and `ns.Thing` are single identifiers | +| Operator symbols | runs of `+ * / < > = ! & \| ' ~` (for example `!=` and `=`) | +| Strings | double quoted, with the usual escapes | +| Numbers | integers and decimals, optionally signed (`-3`, `0.5`) | +| Booleans | `True`, `False`, `true`, `false` | + +Whitespace and comments may appear between any tokens. Source positions in diagnostics are 1-based `line:col`. + +Comments directly above a `def-concept` or `def-property` (consecutive `;` lines with no blank line between) become the hover documentation in the editor (see [Editor and LSP](editor-and-lsp.md)). + +## Declarations + +### `def-concept` + +```lisp +(def-concept Name) +(def-concept Name Parent) +``` + +Declares a concept (class). With a parent it is a subclass; the parent must be declared somewhere (the linter reports `Undeclared parent concept`). Inheritance cycles are lint errors. Declaring the same concept twice with an identical definition is harmless (identical duplicates are merged, which is what makes diamond imports work), but two definitions that differ, for example with different parents, are reported as `Duplicate concept definition`. The same rule applies to properties and relations. + +```lisp +(def-concept Vehicle) +(def-concept Truck Vehicle) +``` + +### `def-property` + +```lisp +(def-property name Domain Type [:cardinality C] [:optional True|False] [:default V]) +``` + +A typed attribute of the domain concept. Types: `Integer`, `Float`, `Double`, `Boolean`, `String`; any other name is a custom type, treated as a reference to another concept (an entity-valued property, which the solver models as a relation). + +Options can be given in any order: + +| Option | Meaning | +|--------|---------| +| `:cardinality C` | One of `1..1` (or `1`), `0..1` (or `optional`), `0..*` (or `*`, `0..n`), `1..*` (or `1..n`). Anything else is a parse error | +| `:optional True` | Same as `:cardinality 0..1`. `:optional False` is `1..1`. Only `True`/`true`/`False`/`false` are accepted | +| `:default V` | A default value, as a string literal, identifier, or number | + +If you give no cardinality, the emitters pick a default (a plain required field for scalars). Cardinality and defaults shape generated code; they are not sent to the solver (see [Axioms and reasoning](axioms-and-reasoning.md)). + +```lisp +(def-property vin Vehicle String :cardinality 1..1) +(def-property nickname Driver String :optional True) +(def-property tags Driver String :cardinality 1..*) +(def-property version Vehicle String :default "1.0.0") +``` + +### `def-relation` + +```lisp +(def-relation name Domain Range [MoreConcepts...] [:cardinality C]) +``` + +A relation between concepts. The first two concepts are domain and range; any further concepts extend the signature to an n-ary relation. Cardinality uses the same values as properties. + +```lisp +(def-relation drives Driver Vehicle :cardinality 0..*) +``` + +Domain and range must be declared concepts. + +### `def-individual` + +```lisp +(def-individual name) +(def-individual name Concept) +``` + +Declares a named individual (a constant), optionally typed by a concept. Individuals can be used as terms in axioms. + +```lisp +(def-individual depot1 Site) +``` + +### `namespace` + +```lisp +(namespace prefix "http://example.org/ns#") +(namespace prefix) +``` + +Declares a prefix and optionally its IRI. The prefix is a bare identifier, not a quoted string (`(namespace "bfo" "...")` is a parse error). The first declared namespace becomes the default base IRI for the `owl` and `shacl` targets (override with `--base-iri`). Duplicate prefixes are lint errors. Prefixes are conventionally used in concept names (`bfo:Entity`) but a name containing `:` is just an identifier; nothing expands it. + +### `import` + +```lisp +(import "relative/or/library/file.logic") +``` + +Loads another `.logic` file and merges its declarations and axioms. See [Imports and search path](#imports-and-search-path). + +## Axioms + +An axiom is a first-order formula. There are three equivalent ways to state one: + +```lisp +(forall (v) (implies (Truck v) (not (Car v)))) ; bare axiom +(def-axiom (forall (v) (implies (Truck v) (not (Car v))))) ; def-axiom +(def-axiom "trucks-not-cars" (forall (v) (implies (Truck v) (not (Car v))))) ; with a label +``` + +The optional label is documentation only. + +### Formulas + +| Form | Meaning | +|------|---------| +| `(Concept x)` | `x` is an instance of the concept | +| `(relation x y)` | `x` and `y` are related | +| `(pred t1 t2 ...)` | any other predicate application; undeclared predicate names become uninterpreted predicates in the solver | +| `(and P Q ...)` | conjunction (zero arguments is `top`) | +| `(or P Q ...)` | disjunction (zero arguments is `bottom`) | +| `(not P)` | negation | +| `(implies P Q)` or `(if P Q)` | implication | +| `(iff P Q)` | biconditional | +| `(forall (x y ...) P)` | universal quantification over one or more variables | +| `(exists (x y ...) P)` | existential quantification | +| `(forall ((x Concept) ...) P)` | typed binder; mixing plain and typed variables is allowed | +| `(eq a b)` or `(= a b)` | equality | +| `(!= a b)` | disequality | +| `(gt p v)` `(gte p v)` `(lt p v)` `(lte p v)` `(ne p v)` `(eq p v)` | comparison of a property with a value | +| `top`, `true`, `bottom`, `false` | truth and falsity (any capitalization of the first letter) | + +Subformulas of connectives must be parenthesized or one of the constants above. + +### Terms + +A term is a variable (identifier), a constant (string, number, boolean), or a function application `(f t1 t2 ...)`. + +### Property comparisons + +Comparisons name the property directly, without a variable: `(gte speed 0)`. Inside a quantifier the property is read on the innermost bound variable: + +```lisp +(forall (v) (implies (Vehicle v) (and (gte speed 0) (lte speed 130)))) +``` + +Axioms of the shape `forall x. Concept(x) implies ` are the ones emitters can turn into field constraints (`@Min`, `Field(ge=...)`, `CHECK (...)`). Everything else (disjointness, existentials, relational rules) is still checked by the solvers, but emitters report it as an unmapped axiom (see [Targets and emitters](targets-and-emitters.md)). + +### Common patterns + +```lisp +;; Disjointness +(forall (x) (implies (Truck x) (not (Car x)))) + +;; Every Truck has some Site it serves +(forall ((t Truck)) (exists ((s Site)) (serves t s))) + +;; Symmetric relation +(forall (x y) (implies (link x y) (link y x))) + +;; Multi-premise rule +(forall (o) (implies (and (Oven o) (eq is_active True)) (gt temperature 100))) +``` + +## Imports and search path + +`(import "name.logic")` is resolved by looking for `name.logic` in these directories, first match wins: + +1. The directory of the importing file. +2. Each `--lib-path DIR` given on the command line, in order (the flag is repeatable). +3. Each directory in `$ONTOLOGIC_PATH` (a `:`-separated list on Linux and macOS). +4. `ontologic-lib/` next to the executable's parent (`bin/../ontologic-lib`, the release-tarball layout), then next to the executable. +5. `ontologic-lib/` in the installed package data directory (`stack install`). +6. `./ontologic-lib` in the current directory (running from a source checkout). +7. The current directory, last, so a stray file there cannot shadow a library module. + +Only directories that exist are searched. An absolute import path is used as is. Imports are transitive, imported files may import others, and a file imported by several paths is loaded once. A circular import is reported: + +```text +Circular import dependency detected: /path/a.logic -> /path/b.logic -> /path/a.logic +``` + +A missing file is reported as `Import not found: shared.logic` (exit 1). Adding the directory fixes it: + +```bash +ontologic-exe -i imp3.logic -t lint --lib-path libx +ONTOLOGIC_PATH=libx ontologic-exe -i imp3.logic -t lint +``` + +```text +✅ Logic Validated successfully. +✅ Logic Validated successfully. +``` + +The standard library names are listed in [Standard library](standard-library.md). Note that library concepts carry namespace prefixes, so you write `(def-concept Pump bfo:MaterialEntity)` after `(import "bfo_2020.logic")`. + +The REPL's `:load` uses the default search path but has no `--lib-path`; set `ONTOLOGIC_PATH` instead. + +## Lint-visible rules at a glance + +| Check | Example message | +|-------|-----------------| +| Undeclared parent / domain / range | `Undeclared parent concept: B referenced by A` | +| Duplicates | `Duplicate concept definition: Bus` | +| Circular inheritance | `Circular inheritance: ...` | +| Contradictory bounds | `Property contradiction on methane_level: gt 5 and lt 3` | +| Inherited-bound clash | `Cross-axiom contradiction on GasSensor.methane_level: ...` | +| Disjointness violation | `Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car.` | + +Next: [Axioms and reasoning](axioms-and-reasoning.md) diff --git a/docs/user-guide/quickstart.md b/docs/user-guide/quickstart.md new file mode 100644 index 0000000..1bf3576 --- /dev/null +++ b/docs/user-guide/quickstart.md @@ -0,0 +1,166 @@ +# Quickstart + +In about ten minutes you will write a small fleet ontology, lint it, ask a solver whether it is consistent, break it on purpose to see a contradiction reported, emit TypeScript, SQL, and OpenAPI from it, and draw a diagram. You need a built `ontologic-exe` (see [Installation](installation.md)); Z3 or CVC5 is recommended but not required. + +## 1. Write the ontology + +Create `fleet.logic`. Comments start with `;` (or `//`). + +```lisp +;; fleet.logic - a small vehicle-fleet ontology +(namespace fleet "http://example.org/fleet#") + +(def-concept Vehicle) +(def-concept Truck Vehicle) +(def-concept Car Vehicle) +(def-concept Driver) + +(def-property vin Vehicle String :cardinality 1..1) +(def-property speed Vehicle Integer) +(def-property max_load Truck Integer :optional True) +(def-property nickname Driver String :optional True) + +(def-relation drives Driver Vehicle :cardinality 0..*) + +;; Trucks and cars are disjoint +(forall (v) (implies (Truck v) (not (Car v)))) + +;; Speed is bounded for every vehicle +(forall (v) (implies (Vehicle v) (and (gte speed 0) (lte speed 130)))) + +;; Trucks have a non-negative load limit +(forall (t) (implies (Truck t) (gte max_load 0))) +``` + +`(def-concept Truck Vehicle)` makes Truck a subclass of Vehicle. Properties are typed attributes of one concept; relations link two concepts. The `forall` forms are axioms. Full syntax: [Language reference](language-reference.md). + +## 2. Lint + +```bash +stack exec ontologic-exe -- -i fleet.logic -t lint +``` + +```text +✅ Logic Validated successfully. +``` + +The linter checks symbols, duplicates, inheritance cycles, and obvious contradictions. Try breaking it: make `Hybrid` a subclass of `Truck` that is also a `Car`. + +```lisp +(def-concept Hybrid Truck) +(forall (h) (implies (Hybrid h) (Car h))) +``` + +```text +bad.logic:4:14: error: Semantic contradiction: Concept Hybrid implies both Truck and Car, but Truck is disjoint with Car. +``` + +The message has `file:line:col: error:` format, the exit code is 1, and (because the linter runs first) nothing else is attempted. In the real output the file path is printed in full. + +## 3. Solve + +```bash +stack exec ontologic-exe -- -i fleet.logic -t solve +``` + +```text +✅ SMT Satisfiable (SAT) — Ontology is logically consistent. +✅ All concepts are satisfiable (0 empty concepts). +``` + +Two checks ran: the axioms can be satisfied together (consistency), and every concept can have an instance (coherence). Exit code 0 means both passed. To see a failure, state a contradiction the linter cannot spot syntactically: + +```lisp +(def-concept Account) +(def-concept Frozen Account) +(def-property balance Account Integer) +(def-axiom "min-balance" (forall (a) (implies (Account a) (gte balance 100)))) +(def-axiom "some-low" (exists (a) (and (Account a) (lt balance 50)))) +``` + +```bash +stack exec ontologic-exe -- -i unsat.logic -t solve --explain-unsat +``` + +```text +❌ SMT Unsatisfiable (UNSAT) — Logical contradiction detected! +🔍 Unsatisfiable Core Conflicting Axioms: + • Axiom #1: forall a (Account(a) implies gte(balance, 100)) + • Axiom #2: exists a (Account(a) and lt(balance, 50)) +❌ Unsatisfiable / empty concept(s): Account Frozen +``` + +The exit code is 1. More in [Axioms and reasoning](axioms-and-reasoning.md). + +## 4. Emit code and schemas + +Every target except `lint`/`solve`/`repl`/`lsp` needs `-o` (an output directory, created if missing). + +```bash +stack exec ontologic-exe -- -i fleet.logic -t ts -o out/ts +stack exec ontologic-exe -- -i fleet.logic -t sql -o out/sql +stack exec ontologic-exe -- -i fleet.logic -t openapi -o out/openapi +``` + +```text +⚠️ Warning: 1 complex / conditional axiom(s) could not be mapped to TypeScript field constraints: +fleet.logic:17:2: warning: [WUnmappedAxiom] forall v (Truck(v) implies not Car(v)) +Generated TypeScript/Zod models in out/ts +``` + +The warning is expected: the disjointness axiom is logic, not a field bound, so no field constraint can express it. It is recorded as a comment at the end of the generated file. Field bounds were mapped: + +```ts +// out/ts/models.ts +export const VehicleSchema = z.object({ + vin: z.string(), + speed: z.number().int().gte(0).lte(130), +}); +export const TruckSchema = VehicleSchema.extend({ + max_load: z.number().int().optional(), +}); +``` + +```sql +-- out/sql/schema.sql +CREATE TABLE IF NOT EXISTS "Vehicle" ( + "id" TEXT PRIMARY KEY, + "vin" TEXT NOT NULL, + "speed" INTEGER NOT NULL, + CONSTRAINT "chk_Vehicle_speed" CHECK ("speed" >= 0 AND "speed" <= 130) +); +``` + +All targets are listed in [Targets and emitters](targets-and-emitters.md). + +## 5. Visualize + +```bash +stack exec ontologic-exe -- -i fleet.logic -t mermaid -o out/diagrams +stack exec ontologic-exe -- -i fleet.logic -t d2 -o out/diagrams --render +``` + +```text +Generated D2 diagram in out/diagrams +Rendering to out/diagrams/diagram.d2.svg using d2... +✅ Rendered SVG successfully. +``` + +`class_diagram.mmd` holds a Mermaid class diagram (paste it into any Mermaid viewer); `diagram.d2` and `diagram.d2.svg` are the D2 version. See [Visualization](visualization.md). + +## 6. Explore interactively + +```bash +stack exec ontologic-exe -- --repl +``` + +```text +ontologic> :load fleet.logic +✅ Loaded fleet.logic (4 concepts, 0 lint errors). +ontologic> :prove Truck Vehicle +✅ Theorem Proved via Z3: 'Truck' ⊑ 'Vehicle' (Every instance of Truck is necessarily a Vehicle). +``` + +See [REPL](repl.md). + +Next: [Language reference](language-reference.md) | [CLI reference](cli-reference.md) diff --git a/docs/user-guide/repl.md b/docs/user-guide/repl.md new file mode 100644 index 0000000..699421c --- /dev/null +++ b/docs/user-guide/repl.md @@ -0,0 +1,107 @@ +# REPL + +The REPL is an interactive session in which you load or type ontology forms, lint them, run the solvers, prove subsumptions, and print any emitter's output without writing files. It is the quickest way to ask "does this follow?" or "what would this look like in TypeScript?". Start it with `ontologic-exe --repl` (or `-t repl`); no input file is needed. + +```text +╔════════════════════════════════════════════════════════════╗ +║ OntoLogic Interactive REPL v1.0 ║ +║ Type ':help' for commands or enter DSL expressions ║ +╚════════════════════════════════════════════════════════════╝ +ontologic> +``` + +Input is read one line at a time, so each form or command must fit on one line. End the session with `:quit`, `:q`, `exit`, or end-of-input (Ctrl-D). + +## Commands + +| Command | What it does | +|---------|--------------| +| `:help`, `:?` | List commands | +| `:load ` | Replace the session with a file and its imports (uses the default library search path and `$ONTOLOGIC_PATH`) | +| `:show` | Counts and names of concepts, properties, relations, axioms; active prover; loaded file | +| `:lint` | Run the linter on the session | +| `:prover [name]` | Show or set the prover: `z3`, `cvc5`, `vampire`, `native`, `auto` | +| `:solve`, `:check` | Consistency check (prints the model when SAT) plus the coherence check | +| `:explain` (also `:unsat-core`, `:explain-unsat`) | Unsatisfiable core, when there is a contradiction | +| `:model` (also `:inspect-model`) | Print a satisfying model | +| `:prove ` | Prove or refute that every `A` is necessarily a `B` (A ⊑ B); a counterexample model is printed when refuted | +| `:unsat` | List concepts that cannot have instances | +| `:cnf` | Show the session in clausal normal form | +| `:ir` | Dump the compiled intermediate model (for debugging) | +| `:emit ` | Print the target's output (all files concatenated) to the screen. Any name or alias from the [CLI reference](cli-reference.md#targets) | +| `:set java-package ` | Package used by `:emit java` | +| `:set base-iri ` | Base IRI used by `:emit owl` and `:emit shacl` | +| `:clear` | Empty the session (the prover choice is kept) | +| `:quit`, `:q`, `exit` | Leave | + +Anything that is not a command is parsed as DSL. A line may contain one or several top-level forms; they are merged into the session. The linter runs after each addition and, if it finds a problem, prints `⚠️ Lint warning: ...` for the first one; the forms stay in the session regardless. + +## Example session + +```text +ontologic> (def-concept Device) +Added to registry. +ontologic> (def-concept SmartSensor Device) +Added to registry. +ontologic> (def-property batteryLevel SmartSensor Integer) +Added to registry. +ontologic> (forall (s) (implies (SmartSensor s) (and (gte batteryLevel 0) (lte batteryLevel 100)))) +Added to registry. +ontologic> :lint +✅ Semantic Linting Passed (0 errors). +ontologic> :prove SmartSensor Device +✅ Theorem Proved via Auto (Z3/CVC5/Vampire/Native): 'SmartSensor' ⊑ 'Device' (Every instance of SmartSensor is necessarily a Device). +ontologic> :emit ts +import { z } from "zod"; + +export const DeviceSchema = z.object({ +}); +... +export const SmartSensorSchema = DeviceSchema.extend({ + batteryLevel: z.number().int().gte(0).lte(100), +}); +``` + +Adding a contradictory bound is caught immediately: + +```text +ontologic> (forall (s) (implies (SmartSensor s) (gt batteryLevel 100))) +Added to registry. +⚠️ Lint warning: Cross-axiom contradiction on SmartSensor.batteryLevel: lte 100 and gt 100 +ontologic> :solve +❌ SMT Unsatisfiable (UNSAT) via Auto (Z3/CVC5/Vampire/Native) — Logical Contradiction Detected! +❌ Unsatisfiable / empty concept(s): SmartSensor +``` + +Refuting a subsumption (with Z3 selected): + +```text +ontologic> :load fleet.logic +✅ Loaded fleet.logic (4 concepts, 0 lint errors). +ontologic> :prover z3 +✅ SMT Prover switched to: Z3 +ontologic> :prove Vehicle Truck +❌ Theorem Disproved via Z3: 'Vehicle' is NOT subsumed by 'Truck'. Counterexample model: +``` + +## Differences from the CLI + +- `:load` does not take `--lib-path`; use `ONTOLOGIC_PATH`. +- `:load` loads even when there are lint errors (it reports `Loaded ... with N lint warnings`); the CLI refuses to continue past lint errors. +- There are no `-T`/`--solve-timeout` or `--solve-memory` controls; for bounded runs use the CLI. +- `:solve` always prints the model on SAT; the CLI needs `--inspect-model`. +- `:prove` exists only here. +- `:explain` reports "No contradictory axioms or unsat cores detected" when the solver returns an empty core, which can happen even when `:solve` has just reported UNSAT. If so, rely on the `:solve` verdict and read the lint message. +- Malformed input prints a parse error with a caret and leaves the session unchanged: + +```text +ontologic> (oops +❌ Parse Error: +:1:6: + | +1 | (oops + | ^ +unexpected end of input +``` + +Next: [Editor and LSP](editor-and-lsp.md) diff --git a/docs/user-guide/standard-library.md b/docs/user-guide/standard-library.md new file mode 100644 index 0000000..6ab43f8 --- /dev/null +++ b/docs/user-guide/standard-library.md @@ -0,0 +1,49 @@ +# Standard library + +OntoLogic bundles reusable ontologies in the `ontologic-lib/` directory: an upper ontology (BFO), common-core and cybersecurity vocabularies, AI-governance frameworks, and more. You use them with `(import "name.logic")`. The full catalogue, with descriptions and layering, is on its own page: [../standard-library.md](../standard-library.md). This page only covers how imports of library files work. + +## Importing a library file + +```lisp +(import "bfo_2020.logic") + +(def-concept Pump bfo:MaterialEntity) +(def-property flow_rate Pump Integer) +``` + +```bash +ontologic-exe -i pump.logic -t lint +ontologic-exe -i pump.logic -t solve -T 20 +``` + +```text +✅ Logic Validated successfully. +✅ SMT Satisfiable (SAT) — Ontology is logically consistent. +✅ All concepts are satisfiable (0 empty concepts). +``` + +Points to know: + +- **Use the bare file name.** `(import "bfo_2020.logic")` is found through the search path, whether you run from the repository, from an installed copy, or from a release tarball. A path such as `ontologic-lib/bfo_2020.logic` only works when run from a directory that has it. +- **Names carry prefixes.** Library concepts are declared with namespace prefixes (`bfo:MaterialEntity`, not `MaterialEntity`). Refer to them exactly as declared; the linter reports `Undeclared parent concept` otherwise. +- **Imports are transitive.** Importing `mitre_attack.logic` also loads the files it imports (for example `stix_cve.logic`). Circular imports are an error. +- **Library files must be lint-clean.** The linter checks the merged ontology, so a problem anywhere in the import graph stops your run. + +## Where library files are found + +In order: your file's own directory, each `--lib-path DIR`, each directory in `$ONTOLOGIC_PATH`, then the built-in locations (next to the executable, the installed data directory, `./ontologic-lib`, and finally the current directory). The details and an example are in the [Language reference](language-reference.md#imports-and-search-path). + +To use your own shared library of ontologies, put it in a directory and add it to the path: + +```bash +export ONTOLOGIC_PATH=$HOME/ontologies +ontologic-exe -i app.logic -t lint +# or per run: +ontologic-exe -i app.logic -t lint --lib-path $HOME/ontologies +``` + +## Files in `ontologic-lib/` + +`bfo_2020`, `cco_core`, `uco_observables`, `stix_cve`, `mitre_attack`, `mitre_d3fend`, `mitre_atlas`, `nist_ai_rmf`, `nist_csf`, `nist_sp800_53`, `iso_42001_eu_ai_act`, `ocsf_schema`, `sigma_rules`, `autonomous_ai`, `software_systems`, `factory_domain`, `ecosystem`, and `ecosystem_unified` (each with the `.logic` extension). See [../standard-library.md](../standard-library.md) for what each covers. + +Next: [Domain examples](domain-examples.md) diff --git a/docs/user-guide/targets-and-emitters.md b/docs/user-guide/targets-and-emitters.md new file mode 100644 index 0000000..8e5ddb9 --- /dev/null +++ b/docs/user-guide/targets-and-emitters.md @@ -0,0 +1,186 @@ +# Targets and emitters + +Each `-t ` compiles the checked ontology into one or more files in the `-o` directory. All emitters read the same intermediate model, so the same concept becomes a Java class, a Pydantic model, a SQL table, an OWL class, and so on. This page says what each target writes, how it maps concepts, properties, relations, and bounds, and shows a real snippet. All snippets come from `fleet.logic` in the [Quickstart](quickstart.md). + +## How the model maps + +| Ontology element | Typical output | +|------------------|----------------| +| `def-concept C [P]` | a class, message, table, shape, or node type; `P` becomes inheritance, `allOf`, `extends`, an FK, or a subclass edge | +| `def-property p C T` | a typed field; `:cardinality 0..1` or `:optional True` makes it optional; `0..*` or `1..*` makes it a list | +| `def-relation r A B` | a list-valued field, a junction table, a graph edge, or an object property, depending on the target | +| Axiom `forall x. C(x) implies (gte p 0 ...)` | a field constraint (`>=`, `>`, `<=`, `<`, and for some targets equality) on `p` for `C` and its subclasses | +| Any other axiom | unmapped: reported as a warning, and written as a comment in the output where the format has comments | + +Type mapping: `Integer` becomes the target's 64-bit integer (`int`, `i64`, `int64_t`, `Int` or `integer`); `Float`/`Double` become floating point; `Boolean`, `String` map to the native types; a custom type is a reference to a concept. + +Constraints are only *enforced* by targets that have a validation notion (Java Jakarta Validation, Pydantic, Zod, Rust/Go/C++ `validate()`, SQL `CHECK`, JSON Schema, OpenAPI, SHACL). The `smt`, `tptp`, `owl`, and diagram targets describe the model rather than enforce it. Background: [../dev/design/constraints_and_patterned.md](../dev/design/constraints_and_patterned.md). + +## Application code + +### `java` + +One `.java` per concept, in the package given by `--java-package` (default `ontologic.generated`). Fields are private with getters and setters; bounds become Jakarta Validation annotations (`@NotNull`, `@Min`, `@Max`); subclasses use `extends`. If any axiom is unmapped, a `package-info.java` carries the warning (so it is not repeated in each class). + +```java +public class Vehicle { + private Integer speed; + + @NotNull + @Min(0) + @Max(130) + public Integer getSpeed() { return this.speed; } +``` + +Files: `Vehicle.java`, `Truck.java`, `Car.java`, `Driver.java`, `package-info.java`. + +### `python` + +`models.py`: Pydantic v2 `BaseModel` classes with `Field(ge=..., le=...)`, `Optional[...]`, `List[...]`, and `model_rebuild()` calls at the end. + +```python +class Vehicle(BaseModel): + vin: str + speed: int = Field(ge=0, le=130) + +class Truck(Vehicle): + max_load: Optional[int] = Field(default=None, ge=0) +``` + +### `ts` (aliases `typescript`, `zod`) + +`models.ts`: Zod schemas plus inferred types; subclasses use `.extend(...)`. + +```ts +export const VehicleSchema = z.object({ + vin: z.string(), + speed: z.number().int().gte(0).lte(130), +}); +export type Vehicle = z.infer; +``` + +### `rust` + +`models.rs`: structs with `Option` / `Vec` fields and an `impl` with `validate() -> Result<(), Vec>`. Subclasses embed the parent as `base` and call its `validate`. + +### `go` (alias `golang`) + +`models.go`: structs with `json` tags (optional fields are pointers), the parent embedded for inheritance, and `Validate() []string` methods. + +### `cpp` (alias `c++`) + +`models.hpp`: a header-only C++20 file in `namespace ontologic` with `std::optional`, `std::vector`, `std::shared_ptr`, and virtual `validate()` methods that return error strings. + +## API and data contracts + +### `openapi` + +`openapi.yaml`: OpenAPI 3.1 `components/schemas`, one schema per concept (`required`, `minimum`, `maximum`, `allOf` with a `$ref` for subclasses). + +```yaml + Vehicle: + type: object + required: + - vin + - speed + properties: + vin: + type: string + speed: + type: integer + minimum: 0 + maximum: 130 +``` + +### `graphql` (alias `gql`) + +`schema.graphql`: object types (subclass types repeat the inherited fields), non-null `!` for required fields, and a `Query` type with one list field per concept. + +### `jsonschema` (alias `json`) + +`schema.json`: JSON Schema draft 2020-12 with one entry per concept in `$defs`, `allOf` + `$ref` for subclasses, `minimum`/`maximum`, and `required`. JSON has no comments, so unmapped axioms are reported on the console only. + +### `protobuf` (aliases `proto`, `proto3`) + +`schema.proto`: `proto3` messages in a package named after the first namespace prefix, lower-cased (`package fleet;`; `ontologic` if none is declared), with `optional` and `repeated` fields and native scalar types. Inheritance is shown as a comment, and bounds are not expressed. + +```proto +message Driver { + optional string nickname = 1; + repeated Vehicle drives = 2; +} +``` + +### `sql` (aliases `postgres`, `postgresql`, `ddl`) + +`schema.sql`: PostgreSQL DDL. One table per concept with a `TEXT` primary key `id`; subclass tables reference the parent with `ON DELETE CASCADE`; bounds become named `CHECK` constraints; relations become junction tables `rel_`. + +```sql +CREATE TABLE IF NOT EXISTS "Truck" ( + "id" TEXT PRIMARY KEY REFERENCES "Vehicle"("id") ON DELETE CASCADE, + "max_load" INTEGER, + CONSTRAINT "chk_Truck_max_load" CHECK ("max_load" >= 0) +); +``` + +## Knowledge graphs + +### `owl` + +`ontology.owl`: RDF/XML with `owl:Class`, `rdfs:subClassOf`, `owl:DatatypeProperty` (with domain and XSD range), and `owl:ObjectProperty`. The base IRI is the first namespace's IRI, or `--base-iri`. + +```xml + +``` + +### `shacl` + +`shapes.ttl`: Turtle with a `sh:NodeShape` per concept (`sh:targetClass`), `sh:datatype`, `sh:minCount`/`sh:maxCount` from cardinality, and `sh:minInclusive`/`sh:maxInclusive` from bounds. Same `--base-iri` rules as OWL. + +```turtle +ont:VehicleShape + a sh:NodeShape ; + sh:targetClass ont:Vehicle ; + sh:property [ sh:path ont:speed ; sh:datatype xsd:integer ; + sh:minInclusive 0 ; sh:maxInclusive 130 ] . +``` + +### `neo4j` + +Two files. `graph.cypher` creates `OntologyClass` nodes, `SUBCLASS_OF` and `RELATION` edges, and one audit query per bound that returns the ids of violating nodes. `constraints.cypher` holds property-existence constraints, which need Neo4j Enterprise; `--neo4j-edition community` writes them commented out. + +```cypher +// Axiom validation: Vehicle speed gte 0 +MATCH (n:`Vehicle`) WHERE NOT (n.`speed` >= 0) RETURN elementId(n) AS invalid_node_id; +``` + +## Prover input + +### `smt` + +`spec.smt2`: SMT-LIB2 with an `Entity` sort, one constant per concept, `subClassOf` facts, per-property functions with bound assertions, and a trailing `(check-sat)` and `(get-model)`. Feed it to any SMT solver (`z3 spec.smt2`). This is a declarative export; the in-process `--solve` uses a richer first-order encoding (see [Axioms and reasoning](axioms-and-reasoning.md)), so verdicts can differ. + +### `tptp` + +`theory.p`: TPTP first-order form (`fof(...)` axioms with `is_`, `rel_`, `prop_`, and `cmp_` symbols) for Vampire, E, and other ATPs. + +```text +fof(subclass_Truck_Vehicle, axiom, (! [X] : (is_Truck(X) => is_Vehicle(X)))). +``` + +## Diagrams + +`mermaid` writes `class_diagram.mmd`; `d2` writes `diagram.d2`. Both accept `--render`. See [Visualization](visualization.md). + +## Unmapped axioms + +An axiom that is not of the "concept implies property comparisons" shape (disjointness, existentials, relational rules) cannot become a field constraint. Targets with `Unmapped by default = yes` in the [CLI reference](cli-reference.md#targets) print + +```text +⚠️ Warning: 1 complex / conditional axiom(s) could not be mapped to Python field constraints: +fleet.logic:17:2: warning: [WUnmappedAxiom] forall v (Truck(v) implies not Car(v)) +``` + +and append the same list as a comment to the first (or, for Java, a `package-info.java`) output file. Use `--warn-unmapped` to get the warning for the remaining targets. Such axioms are still verified by `--solve`; they are just not enforced by the generated artifact, so enforce them in application code or with SHACL/OWL tooling. + +Next: [Visualization](visualization.md) diff --git a/docs/user-guide/troubleshooting.md b/docs/user-guide/troubleshooting.md new file mode 100644 index 0000000..6e0afc1 --- /dev/null +++ b/docs/user-guide/troubleshooting.md @@ -0,0 +1,94 @@ +# Troubleshooting + +This page maps messages and surprising results to causes and fixes. Messages are quoted exactly as OntoLogic prints them; paths are shortened. When in doubt, run `-t lint` first: it is fast, and every other mode starts with it. + +## Parse and load errors + +| Message | Cause | Fix | +|---------|-------|-----| +| `Parse error in FILE:` followed by a caret excerpt | Syntax error | Look at the line and column; the `expecting` list says what the parser wanted | +| `unexpected '"'` / `expecting '_' or letter` on a `namespace` line | Quoted prefix, as in `(namespace "bfo" "...")` | Use a bare prefix: `(namespace bfo "http://...")` | +| `unexpected ':'` / `expecting ')'` in a `def-property` | Unknown or invalid option, for example `:cardinality 2..3` | Cardinalities are `1..1`, `0..1`, `0..*`, `1..*` (and `1`, `optional`, `*`, `0..n`, `1..n`). | +| `unexpected end of input, expecting ')'` | Unbalanced parentheses | Check the last form; an editor with bracket matching helps | +| `unknown form 'def-foo'` | A `def-` word the parser does not know | The declarations are `def-concept`, `def-property`, `def-relation`, `def-individual`, `def-axiom` | +| `File not found: x.logic` | Wrong `-i` path | Check the working directory | +| `Import not found: x.logic` | Import not on the search path | Add `--lib-path DIR` or `$ONTOLOGIC_PATH`, or fix the name; see [Language reference](language-reference.md#imports-and-search-path) | +| `Circular import dependency detected: a -> b -> a` | Two files import each other | Move shared definitions to a third file both import | +| `Error: --input is required (or use --repl / --lsp)` | No `-i` | Pass `-i FILE` | +| `Error: --output is required for target: ts` | Emitter without `-o` | Pass `-o DIR` | +| `Unknown target: foo` | Misspelled target | See the list in `--help` or the [CLI reference](cli-reference.md#targets) | +| `option -T: expected a positive integer, got '0'` | Zero or negative limit | Use a value of 1 or more | + +## Lint errors + +All have the form `file:line:col: error: message` and make the run exit 1. + +| Message | Meaning and fix | +|---------|-----------------| +| `Undeclared parent concept: B referenced by A` | `A`'s parent is not declared. Declare it or fix the name. For library concepts include the prefix: `bfo:MaterialEntity` | +| `Undeclared domain concept: X in property p` | The property's domain concept is missing | +| `Undeclared domain/range concept: X in relation r` | A relation endpoint is missing | +| `Duplicate concept definition: A` | Two differing definitions of one concept (identical repeats are merged silently) | +| `Circular inheritance: ["A","B","A"]` | The parent chain loops | +| `Property contradiction on p: gt 5 and lt 3` | One axiom demands incompatible bounds | +| `Cross-axiom contradiction on C.p: ...` | Axioms (including inherited ones) on a concept's property conflict | +| `Semantic contradiction: Concept H implies both T and C, but T is disjoint with C.` | A subclass of two disjoint concepts. Remove one parent or the disjointness axiom | +| `Axiom contradiction: bottom (false) asserted.` | An axiom reduces to `bottom` | +| `Semantic contradiction: Global axioms derive unsatisfiable conflict: A, B.` | The axioms force these concepts to be empty | + +Contradictions can be reported twice (once per operand order); fix the first and the pair disappears. + +## Solver messages + +| Output | Meaning | +|--------|---------| +| `⚠️ N axiom(s) were not sent to the solver` | Those axioms could not be translated (reason in parentheses). The verdict covers the rest. See [Axioms and reasoning](axioms-and-reasoning.md#axioms-that-are-not-sent) | +| `ℹ️ ... --free-constants` | You enabled free-constants mode; undeclared names are treated as constants | +| `SMT Solver Result (unknown): ...` | Exit 2. Timeout or the solver gave up. Raise `-T`, try another `-p`, or simplify the ontology | +| `SMT Solver Error: Failed to execute Z3 solver: ... Ensure 'z3' is installed and available in PATH.` | You asked for a specific prover (`-p z3`) that is not installed. Install it, or use `-p auto`/`-p native` | +| `Unknown prover 'x'. Valid options: z3, cvc5, vampire, native, auto` | Bad `-p` value | +| `⚠️ --solve-memory is not supported by CVC5 and is ignored.` | Memory limits apply to Z3 only | +| `Concept coherence check could not run: ...` | Exit 2; the second solver step failed. Usually the same cause as an adjacent solver error | +| `Native resolution prover timed out / step limit / clause limit exceeded` | The built-in prover gave up (reported as unknown). Use `z3` or `cvc5` | + +### SAT from one prover, UNSAT from another + +The native prover and Vampire do not interpret numeric comparisons the way Z3 and CVC5 do. An ontology with contradictory numeric bounds that the linter did not catch (for example a universal lower bound and an existential witness below it) is UNSAT under `-p z3` or `-p cvc5` and can look SAT under `-p native` or `-p vampire`. Prefer Z3 or CVC5 whenever properties have numeric bounds. + +### Auto picked the native prover + +`--prover auto` falls back to the native prover only when none of `z3`, `cvc5`, `vampire` is on `PATH`. Check with `which z3 cvc5 vampire`. Solvers installed through sandboxed packages (snap, flatpak) may not be visible or may not read your files. + +### "Satisfiable" but a constraint is missing at runtime + +`--solve` reasons about the logic, not about generated code. Cardinality, `:optional`, and `:default` are not part of the solver's theory; axioms that are not field-shaped are reported as unmapped by emitters. See [Targets and emitters](targets-and-emitters.md#unmapped-axioms). + +## Emitter issues + +| Symptom | Cause and fix | +|---------|---------------| +| `⚠️ Warning: N complex / conditional axiom(s) could not be mapped...` | Expected for disjointness, existential, and relational axioms. Enforce them elsewhere or ignore | +| No warning for `owl`, `shacl`, `smt`, `neo4j`, ... | They do not warn by default; add `--warn-unmapped` | +| Output file overwritten | File names are fixed per target; use a separate `-o` directory per ontology | +| `mmdc ... not found or failed` / `d2 CLI not found or failed` | Install the renderer or drop `--render`; see [Visualization](visualization.md) | +| Generated Python or Java has the same bound repeated | Known limitation (as of 1.8.2): when a subclass restates a bound on a property it inherits, for example `Field(le=90, ge=0, le=130)`, the emitter lists both the subclass and inherited bounds. Python rejects a repeated keyword and Java rejects a repeated annotation. Put each bound on one concept only | +| `openapi.yaml` fails to parse when a subclass has its own properties | Known limitation (as of 1.8.2): the properties of such a subclass are emitted at the wrong indentation. Check generated YAML before use, or use `jsonschema` | + +## REPL and editor + +| Symptom | Fix | +|---------|-----| +| REPL `:explain` says "No contradictory axioms" right after `:solve` reported UNSAT | The solver returned an empty core; rely on `:solve` and the lint message | +| REPL form spans several lines and fails | Each REPL line is parsed on its own; put the whole form on one line | +| Editor shows no diagnostics | Check the "OntoLogic" output channel; run "OntoLogic: Restart Language Server"; make sure `ontologic-lsp` is found (set `ontologic.lsp.path`) | +| Editor reports undeclared library concepts | `ONTOLOGIC_PATH` must be set in the environment the editor was launched from | +| Snippet expands to code that does not parse | The concept and axiom snippets use an older syntax; see [Editor and LSP](editor-and-lsp.md) | + +## Getting more detail + +- `--cnf` shows how axioms were understood. +- `--inspect-model` shows a witness world; `--explain-unsat` shows the conflicting axioms. +- `-t smt -o DIR` or `-t tptp -o DIR` writes the problem so you can run `z3`, `cvc5`, or `vampire` yourself. +- See [FAQ](faq.md) for conceptual questions. + +Next: [FAQ](faq.md) diff --git a/docs/user-guide/visualization.md b/docs/user-guide/visualization.md new file mode 100644 index 0000000..d55844a --- /dev/null +++ b/docs/user-guide/visualization.md @@ -0,0 +1,100 @@ +# Visualization + +OntoLogic turns an ontology into diagrams in two text formats, Mermaid and D2, and can call the matching command-line renderer to produce an SVG. The diagrams show concepts, inheritance, typed properties, and relations. The text files work without any extra software; rendering to an image needs `d2` or `mmdc`. + +## Prerequisites (optional) + +| Tool | Needed for | Install | +|------|-----------|---------| +| D2 CLI | `-t d2 --render` | `curl -fsSL https://d2lang.com/install.sh \| sh -s --` | +| Mermaid CLI | `-t mermaid --render` | `npm install -g @mermaid-js/mermaid-cli` | + +Without them, OntoLogic still writes `class_diagram.mmd` and `diagram.d2`, which you can paste into an online Mermaid or D2 editor, or into a Markdown file (GitHub renders ```` ```mermaid ```` blocks). + +## Mermaid class diagram + +```bash +ontologic-exe -i fleet.logic -t mermaid -o diagrams +``` + +```text +Generated Mermaid diagram in diagrams +Skipping render (use --render to generate SVG). +``` + +`diagrams/class_diagram.mmd`: + +```text +classDiagram + class Vehicle["Vehicle"] + class Truck["Truck"] + class Car["Car"] + class Driver["Driver"] + Vehicle <|-- Truck + Vehicle <|-- Car + Vehicle : +String vin + Vehicle : +Integer speed + Truck : +Integer max_load + Driver : +String nickname + Driver --> Vehicle : drives +``` + +Inheritance is drawn `Parent <|-- Child`, properties are `+Type name` members, and a relation is an arrow labeled with the relation name. Unmapped axioms are appended as `%%` comments, which Mermaid ignores. + +Add `--render` to also write `class_diagram.mmd.svg` next to the source. This calls `mmdc -i .mmd -o .mmd.svg`. If `mmdc` is missing or fails you get a warning and the `.mmd` file is still there: + +```text +⚠️ Error: 'mmdc' (Mermaid CLI) not found or failed. Install with 'npm install -g @mermaid-js/mermaid-cli' +``` + +## D2 diagram + +```bash +ontologic-exe -i fleet.logic -t d2 -o diagrams --render +``` + +```text +success: successfully compiled diagrams/diagram.d2 to diagrams/diagram.d2.svg in 45.912272ms +Generated D2 diagram in diagrams +Rendering to diagrams/diagram.d2.svg using d2... +✅ Rendered SVG successfully. +``` + +`diagrams/diagram.d2` uses D2's `class` shape: + +```text +"Vehicle": { shape: class } +"Truck": { shape: class } +"Truck" -> "Vehicle" +"Vehicle"."speed": Integer +"Driver" -> "Vehicle": drives +``` + +D2 is a good choice for large ontologies because its layout engines handle nesting and dense graphs well. + +## Output summary + +| Target | Source file | Rendered file | Contents | +|--------|-------------|---------------|----------| +| `mermaid` | `class_diagram.mmd` | `class_diagram.mmd.svg` | UML-style class diagram: inheritance, typed fields, association arrows | +| `d2` | `diagram.d2` | `diagram.d2.svg` | Class-shaped nodes, inheritance and relation arrows, typed properties | +| `neo4j` | `graph.cypher` | n/a | Graph schema and audit queries for a graph database ([Targets](targets-and-emitters.md#neo4j)) | + +The output file names are fixed, so use one `-o` directory per diagram, or move the files after generation. `examples/generate_visuals.sh` does this for every example, and the checked-in `examples/*.mmd`, `*.d2`, and `*.d2.svg` files are its output. + +## Working with big ontologies + +- Import a library and diagram a subset: write a small `.logic` file that imports only what you need. +- Large standard-library ontologies (for example `ontologic-lib/mitre_attack.logic`) produce very large diagrams; prefer D2 and render to SVG, or split by domain. +- The REPL can print either format without writing a file: `:emit mermaid` or `:emit d2` (see [REPL](repl.md)). + +## Troubleshooting + +| Symptom | Cause and fix | +|---------|---------------| +| `Skipping render (use --render to generate SVG).` | You did not pass `--render`; this is informational | +| `'mmdc' ... not found or failed` | Mermaid CLI is not installed, not on `PATH`, or cannot run (for example a sandboxed package that cannot read the output directory). Run `mmdc -i class_diagram.mmd -o out.svg` by hand to see its error | +| `'d2' CLI not found or failed` | Install D2; check `d2 --version` | +| Overwritten diagrams | Fixed file names; use separate `-o` directories | + +Next: [REPL](repl.md) diff --git a/docs/using.md b/docs/using.md index 309a8d6..004e704 100644 --- a/docs/using.md +++ b/docs/using.md @@ -1,102 +1,203 @@ -# OntoLogic: User Guide +# Using OntoLogic -This guide describes how to write `.logic` syntax, compile logic files, build target libraries, and render visual diagrams. +A task-oriented guide: pick the job you want to do and follow the recipe. For +depth, each section links to the [user guide](user-guide/README.md). ---- +- [Build and install](#build-and-install) +- [Write a first ontology](#write-a-first-ontology) +- [Check an ontology](#check-an-ontology) +- [Prove things about it](#prove-things-about-it) +- [Generate code, schemas and diagrams](#generate-code-schemas-and-diagrams) +- [Reuse the standard library](#reuse-the-standard-library) +- [Work interactively](#work-interactively) +- [Use it in your editor](#use-it-in-your-editor) +- [Integrate with other tools](#integrate-with-other-tools) +- [Where to go next](#where-to-go-next) -## ✍️ Writing `.logic` Files +The examples use `ontologic`. From a source checkout, replace it with +`stack exec ontologic-exe --`. -A `.logic` file defines the taxonomy classes, properties, and constraints. +## Build and install -### 1. Concepts (Taxonomy) -Concepts define classes of objects in your environment. You can specify a parent class to represent inheritance. -```lisp -(def-concept Asset) -(def-concept Device Asset) -(def-concept Sensor Device) +```bash +git clone https://github.com/bsommers/OntoLogic.git +cd OntoLogic +stack build --ghc-options="-Wall -Werror" +stack test --ghc-options="-Wall -Werror" ``` -### 2. Properties -Properties map concepts to value types (Integer, Boolean, String). -```lisp -(def-property serial_number Asset String) -(def-property temperature Sensor Integer) -(def-property is_active Sensor Boolean) -``` +For a standalone binary, `./scripts/package_release.sh` builds an archive under +`dist/`; extract it and copy `bin/ontologic` onto your `PATH`. Details are in +[installation](user-guide/installation.md). + +## Write a first ontology -### 3. Axioms (Constraints) -Axioms enforce logical assertions and ranges on concepts: ```lisp -; Active sensors must have a temperature greater than 0 +;; sensors.logic +(def-concept Device) +(def-concept Sensor Device) + +(def-property serial Device String) +(def-property batteryLevel Sensor Integer) +(def-property isActive Sensor Boolean) + +(def-relation monitors Sensor Device) + +;; Battery level is a percentage (forall (s) - (implies (and (Sensor s) (is_active)) (gt temperature 0))) + (implies (Sensor s) + (and (gte batteryLevel 0) (lte batteryLevel 100)))) ``` ---- +- `def-concept Name [Parent]` declares a class and its parent. +- `def-property name Domain Type` takes `Integer`, `Float`, `Double`, `String`, + `Boolean`, or a concept name. +- `def-relation name Domain Range` declares a binary relation. +- `forall` / `exists` with `implies`, `iff`, `and`, `or`, `not` build axioms; + `gt`, `gte`, `lt`, `lte` bound numeric properties. -## 💻 CLI Compiler Usage +See the [language reference](user-guide/language-reference.md). + +## Check an ontology -Build the compiler first: ```bash -stack build +ontologic -i sensors.logic -t lint ``` -Run the compiler executable using: +Lint catches undeclared parents, domains and relation endpoints, taxonomy cycles, +duplicate definitions, contradictory axioms, and empty numeric intervals across +axioms. Findings print as `file:line:col: error: message` and the exit code is +non-zero. Add `--warn-unmapped` to see axioms a given target cannot express +instead of having them dropped quietly. + +## Prove things about it + ```bash -stack exec ontologic-exe -- -i -t -o +ontologic -i sensors.logic --solve # auto-select a prover +ontologic -i sensors.logic --solve -p z3 # z3, cvc5, vampire, native, auto +ontologic -i sensors.logic --solve -T 30 # 30 second limit, every backend +ontologic -i sensors.logic --solve --explain-unsat # show the conflicting axioms +ontologic -i sensors.logic --solve --inspect-model # print a satisfying model ``` -### CLI Options -- `-i, --input PATH`: Path to the input `.logic` file. -- `-t, --target TARGET`: Target output format. Supported targets: - - `java`: Generates separate Java class files with Jakarta validations. - - `python`: Generates a `models.py` Pydantic schema file. - - `neo4j`: Generates a Cypher script to build node hierarchies and audit queries. - - `owl`: Generates a Web Ontology Language (OWL) XML schema. - - `mermaid`: Generates a Mermaid class diagram markup file (`.mmd`). - - `d2`: Generates a D2 diagram markup file (`.d2`). - - `lint`: Runs linter validation checks only. -- `-o, --output PATH`: Target directory or file path for the output. -- `--render`: Converts Mermaid or D2 diagram files to SVG images (requires CLI tools installed). - ---- +`--solve` reports **consistency** (can the axioms hold at all) and **coherence** +(which concepts can have no instance). Exit code `0` means both pass, `1` means +unsatisfiable or an error, `2` means the solver answered unknown. Axioms the +solver encoding cannot express are listed first. With no external prover +installed, `auto` falls back to the built-in native prover. -## 🎨 Visualizing Diagrams +Other useful switches: `--free-constants` treats undeclared free variables as +constants, `--solve-memory MB` limits Z3 memory, and `--cnf` prints the clausal +normal form. Subsumption (`:prove A B`) and empty-concept search (`:unsat`) are +REPL commands. See [axioms and reasoning](user-guide/axioms-and-reasoning.md). -To render SVG/PNG diagrams automatically from the compiler, install the following CLI tools: +## Generate code, schemas and diagrams -### Mermaid CLI (`mmdc`) ```bash -npm install -g @mermaid-js/mermaid-cli +ontologic -i sensors.logic -t python -o out/py +ontologic -i sensors.logic -t sql -o out/sql +ontologic -i sensors.logic -t java -o out/java --java-package com.example.models +ontologic -i sensors.logic -t owl -o out/owl --base-iri https://example.test/onto +ontologic -i sensors.logic -t d2 -o out/diagram --render ``` -Generate and render class diagram: -```bash -stack exec ontologic-exe -- -i examples/smart_factory.logic -t mermaid -o . --render -# Generates class_diagram.mmd and class_diagram.mmd.svg + +| Goal | Targets | +| :--- | :--- | +| Typed models with validation | `java`, `python`, `rust`, `go`, `ts` (Zod), `cpp` | +| API and storage contracts | `openapi`, `graphql`, `jsonschema`, `protobuf`, `sql` | +| Knowledge graph and semantic web | `neo4j`, `owl`, `shacl` | +| Proof inputs | `smt`, `tptp` | +| Diagrams | `mermaid`, `d2` (add `--render` for SVG) | + +Run `ontologic --help` for the live list. Aliases such as `typescript`, `golang`, +`postgres`, `proto` and `gql` also work. Notes: + +- **Names.** `--java-package` defaults to `ontologic.generated`. The OWL and + SHACL base IRI defaults to the ontology's first declared namespace, then to + `http://example.org/ontologic`. +- **Neo4j** writes `graph.cypher` (loads on Community Edition) and + `constraints.cypher` (existence constraints, Enterprise only). Use + `--neo4j-edition community` to adapt the constraints. +- **Diagrams** need `mmdc` (Mermaid CLI) or `d2` on your `PATH` for `--render`; + without them you still get the `.mmd` / `.d2` source. + +Full table of outputs: [targets and emitters](user-guide/targets-and-emitters.md). +Visual output: [visualization](user-guide/visualization.md). + +## Reuse the standard library + +```lisp +(namespace "bfo" "http://purl.obolibrary.org/obo/bfo.owl#") +(import "bfo_2020.logic") +(import "cco_core.logic") ``` -### D2 Lang CLI (`d2`) +Library files resolve by bare name. The search order is the importing file's +directory, `$ONTOLOGIC_PATH` (`:`-separated), the directory beside the binary, the +package data directory, `./ontologic-lib`, then the current directory. Add your +own folders with `--lib-path DIR` (repeatable). See the +[standard library](standard-library.md) for what each module contains and the +[domain gallery](domains/README.md) for complete models built on it. + +## Work interactively + ```bash -curl -fsSL https://d2lang.com/install.sh | sh -s -- +ontologic --repl ``` -Generate and render structural nesting diagram: + +```text +ontologic> :load sensors.logic +ontologic> (def-concept Gateway Device) +ontologic> :lint +ontologic> :prove Sensor Device +ontologic> :unsat +ontologic> :emit ts +``` + +| Command | Action | +| :--- | :--- | +| `:load ` | Load a file and its imports | +| `:show` | List concepts, properties, relations, axiom count, active prover | +| `:lint` | Run the linter on the session | +| `:prover [name]` | Show or set `z3`, `cvc5`, `vampire`, `native`, `auto` | +| `:solve` / `:check` | Consistency check | +| `:explain`, `:model` | Unsat core, satisfying model | +| `:prove A B` | Prove `A` is subsumed by `B`, or show a counterexample | +| `:unsat` | Find empty concepts | +| `:cnf`, `:ir` | Show clausal normal form, or the compiled `ModelIR` | +| `:emit ` | Print any target's output | +| `:set base-iri X`, `:set java-package X` | Set emit options | +| `:clear`, `:help`, `:quit` | Session control | + +Anything starting with `(` is added to the session. See [REPL](user-guide/repl.md). + +## Use it in your editor + +`ontologic --lsp` (or the `ontologic-lsp` binary) is a Language Server over +stdio. It gives live diagnostics, completion, hover, go-to-definition, rename, +formatting, semantic highlighting, and solver commands as code actions. + ```bash -stack exec ontologic-exe -- -i examples/smart_factory.logic -t d2 -o . --render -# Generates diagram.d2 and diagram.d2.svg +./editors/vscode/scripts/build_extension.sh # builds the .vsix +code --install-extension .vsix ``` ---- +For Neovim, point `nvim-lspconfig` at `ontologic-lsp` for `logic` files. See +[editor and LSP](user-guide/editor-and-lsp.md). -## 📦 Integrating with Gradle & Docker +## Integrate with other tools -### Gradle Integration -The root project has Gradle tasks configured to run compile-time checks: -- **`./gradlew lintOntology`**: Runs the static cycle linter on your logic file. -- **`./gradlew generateJavaModels`**: Generates Java class structures directly into the `models-java` codebase. +- **Gradle.** `./gradlew lintOntology` runs the linter; `./gradlew + generateJavaModels` writes Java models into the `models-java` subproject. +- **Docker.** `docker-compose up -d` starts a local Neo4j (ports 7474 and 7687) + for loading generated Cypher. Credentials come from `NEO4J_AUTH`. +- **CI.** Run `ontologic -i model.logic -t lint` and `--solve` as gates; both exit + non-zero on failure. -### Docker Setup -To start the Neo4j database and Python verification server: -```bash -docker-compose up -``` -This runs Neo4j on ports `7474` (web UI) and `7687` (bolt connection) and mounts Python Pydantic models for edge service validation. +## Where to go next + +- Problems? [troubleshooting](user-guide/troubleshooting.md) and the + [FAQ](user-guide/faq.md). +- Command reference: [CLI reference](user-guide/cli-reference.md). +- How it is built: [architecture](architecture.md). +- Why it exists: [purpose](purpose.md). diff --git a/examples/domain_aerospace.cypher b/examples/domain_aerospace.cypher new file mode 100644 index 0000000..7441f97 --- /dev/null +++ b/examples/domain_aerospace.cypher @@ -0,0 +1,321 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Aircraft'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FixedWingAircraft'}) +MERGE (p:OntologyClass {name: 'Aircraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Airliner'}) +MERGE (p:OntologyClass {name: 'FixedWingAircraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CargoAircraft'}) +MERGE (p:OntologyClass {name: 'FixedWingAircraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BusinessJet'}) +MERGE (p:OntologyClass {name: 'FixedWingAircraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Rotorcraft'}) +MERGE (p:OntologyClass {name: 'Aircraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Helicopter'}) +MERGE (p:OntologyClass {name: 'Rotorcraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'UnmannedAircraft'}) +MERGE (p:OntologyClass {name: 'Aircraft'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AircraftComponent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Airframe'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Wing'}) +MERGE (p:OntologyClass {name: 'Airframe'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Fuselage'}) +MERGE (p:OntologyClass {name: 'Airframe'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Empennage'}) +MERGE (p:OntologyClass {name: 'Airframe'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Powerplant'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TurbofanEngine'}) +MERGE (p:OntologyClass {name: 'Powerplant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Propeller'}) +MERGE (p:OntologyClass {name: 'Powerplant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LandingGear'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FlightControlSurface'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Avionics'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FlightManagementComputer'}) +MERGE (p:OntologyClass {name: 'Avionics'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Transponder'}) +MERGE (p:OntologyClass {name: 'Avionics'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FuelSystem'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HydraulicSystem'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LifeLimitedPart'}) +MERGE (p:OntologyClass {name: 'AircraftComponent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SparePart'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Organization'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PilotInCommand'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FirstOfficer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CertifyingEngineer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AirworthinessInspector'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Operator'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaintenanceOrganization'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Regulator'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Airport'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Runway'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CertificationDocument'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TypeCertificate'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AirworthinessCertificate'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AirworthinessDirective'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PilotLicense'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MedicalCertificate'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaintenanceRelease'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MinimumEquipmentList'}) +MERGE (p:OntologyClass {name: 'CertificationDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FlightPlan'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TechnicalLogEntry'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Defect'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DeferredDefect'}) +MERGE (p:OntologyClass {name: 'Defect'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaintenanceCheck'}) +MERGE (p:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LineCheck'}) +MERGE (p:OntologyClass {name: 'MaintenanceCheck'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ACheck'}) +MERGE (p:OntologyClass {name: 'MaintenanceCheck'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CCheck'}) +MERGE (p:OntologyClass {name: 'MaintenanceCheck'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HeavyCheck'}) +MERGE (p:OntologyClass {name: 'MaintenanceCheck'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ComponentOverhaul'}) +MERGE (p:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NonDestructiveInspection'}) +MERGE (p:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DefectRectification'}) +MERGE (p:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ComplianceAction'}) +MERGE (p:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FlightOperation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Flight'}) +MERGE (p:OntologyClass {name: 'FlightOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CommercialFlight'}) +MERGE (p:OntologyClass {name: 'Flight'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FerryFlight'}) +MERGE (p:OntologyClass {name: 'Flight'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TestFlight'}) +MERGE (p:OntologyClass {name: 'Flight'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Takeoff'}) +MERGE (p:OntologyClass {name: 'FlightOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Landing'}) +MERGE (p:OntologyClass {name: 'FlightOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Cruise'}) +MERGE (p:OntologyClass {name: 'FlightOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PreflightInspection'}) +MERGE (p:OntologyClass {name: 'FlightOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Incident'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RunwayExcursion'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'AircraftComponent'}) +MERGE (t:OntologyClass {name: 'Aircraft'}) +MERGE (s)-[:RELATION {name: 'installed_on'}]->(t); +MERGE (s:OntologyClass {name: 'Aircraft'}) +MERGE (t:OntologyClass {name: 'AirworthinessCertificate'}) +MERGE (s)-[:RELATION {name: 'has_certificate'}]->(t); +MERGE (s:OntologyClass {name: 'Aircraft'}) +MERGE (t:OntologyClass {name: 'TypeCertificate'}) +MERGE (s)-[:RELATION {name: 'type_certified_by'}]->(t); +MERGE (s:OntologyClass {name: 'Aircraft'}) +MERGE (t:OntologyClass {name: 'Operator'}) +MERGE (s)-[:RELATION {name: 'operated_by'}]->(t); +MERGE (s:OntologyClass {name: 'Aircraft'}) +MERGE (t:OntologyClass {name: 'Flight'}) +MERGE (s)-[:RELATION {name: 'performs_flight'}]->(t); +MERGE (s:OntologyClass {name: 'Person'}) +MERGE (t:OntologyClass {name: 'Flight'}) +MERGE (s)-[:RELATION {name: 'commands'}]->(t); +MERGE (s:OntologyClass {name: 'Person'}) +MERGE (t:OntologyClass {name: 'PilotLicense'}) +MERGE (s)-[:RELATION {name: 'holds_license'}]->(t); +MERGE (s:OntologyClass {name: 'Flight'}) +MERGE (t:OntologyClass {name: 'Airport'}) +MERGE (s)-[:RELATION {name: 'departs_from'}]->(t); +MERGE (s:OntologyClass {name: 'Flight'}) +MERGE (t:OntologyClass {name: 'Airport'}) +MERGE (s)-[:RELATION {name: 'arrives_at'}]->(t); +MERGE (s:OntologyClass {name: 'Flight'}) +MERGE (t:OntologyClass {name: 'FlightPlan'}) +MERGE (s)-[:RELATION {name: 'follows_plan'}]->(t); +MERGE (s:OntologyClass {name: 'MaintenanceCheck'}) +MERGE (t:OntologyClass {name: 'Aircraft'}) +MERGE (s)-[:RELATION {name: 'inspects'}]->(t); +MERGE (s:OntologyClass {name: 'MaintenanceProcess'}) +MERGE (t:OntologyClass {name: 'MaintenanceOrganization'}) +MERGE (s)-[:RELATION {name: 'performed_by'}]->(t); +MERGE (s:OntologyClass {name: 'MaintenanceRelease'}) +MERGE (t:OntologyClass {name: 'CertifyingEngineer'}) +MERGE (s)-[:RELATION {name: 'certified_by'}]->(t); +MERGE (s:OntologyClass {name: 'MaintenanceRelease'}) +MERGE (t:OntologyClass {name: 'Aircraft'}) +MERGE (s)-[:RELATION {name: 'releases'}]->(t); +MERGE (s:OntologyClass {name: 'AirworthinessDirective'}) +MERGE (t:OntologyClass {name: 'Aircraft'}) +MERGE (s)-[:RELATION {name: 'applies_to'}]->(t); +MERGE (s:OntologyClass {name: 'Defect'}) +MERGE (t:OntologyClass {name: 'AircraftComponent'}) +MERGE (s)-[:RELATION {name: 'raised_against'}]->(t); +MERGE (s:OntologyClass {name: 'DefectRectification'}) +MERGE (t:OntologyClass {name: 'Defect'}) +MERGE (s)-[:RELATION {name: 'rectifies'}]->(t); +MERGE (s:OntologyClass {name: 'CertificationDocument'}) +MERGE (t:OntologyClass {name: 'Regulator'}) +MERGE (s)-[:RELATION {name: 'issued_by'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'Aircraft'}) +MERGE (s)-[:RELATION {name: 'involves'}]->(t); +// Axiom Validations +// Axiom validation: LifeLimitedPart flight_cycles gte 0 +MATCH (n:`LifeLimitedPart`) WHERE NOT (n.`flight_cycles` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: LifeLimitedPart flight_cycles lte 50000 +MATCH (n:`LifeLimitedPart`) WHERE NOT (n.`flight_cycles` <= 50000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Flight takeoff_mass_kg gt 0 +MATCH (n:`Flight`) WHERE NOT (n.`takeoff_mass_kg` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Flight takeoff_mass_kg lte 600000 +MATCH (n:`Flight`) WHERE NOT (n.`takeoff_mass_kg` <= 600000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Flight fuel_reserve_kg gt 0 +MATCH (n:`Flight`) WHERE NOT (n.`fuel_reserve_kg` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Flight cruise_altitude_ft gte 0 +MATCH (n:`Flight`) WHERE NOT (n.`cruise_altitude_ft` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Flight cruise_altitude_ft lte 51000 +MATCH (n:`Flight`) WHERE NOT (n.`cruise_altitude_ft` <= 51000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: CommercialFlight crew_size gte 2 +MATCH (n:`CommercialFlight`) WHERE NOT (n.`crew_size` >= 2) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall a (Aircraft(a) and is_airworthy = True implies exists c (has_certificate(a, c))) +// forall a (Aircraft(a) and is_released_to_service = True implies is_airworthy = True) +// forall a (Aircraft(a) and gt(hours_since_check, 600) implies is_airworthy = False) +// forall p (forall f (commands(p, f) implies exists l (holds_license(p, l)))) +// forall a (Aircraft(a) and is_airworthy = True implies open_defect_count = 0) +// forall m (MaintenanceRelease(m) implies exists e (certified_by(m, e))) +// forall x (not Aircraft(x) and AircraftComponent(x)) +// forall x (not Flight(x) and MaintenanceProcess(x)) diff --git a/examples/domain_aerospace.d2 b/examples/domain_aerospace.d2 new file mode 100644 index 0000000..b3a1b56 --- /dev/null +++ b/examples/domain_aerospace.d2 @@ -0,0 +1,204 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"InformationContentEntity": { shape: class } +"Aircraft": { shape: class } +"FixedWingAircraft": { shape: class } +"Airliner": { shape: class } +"CargoAircraft": { shape: class } +"BusinessJet": { shape: class } +"Rotorcraft": { shape: class } +"Helicopter": { shape: class } +"UnmannedAircraft": { shape: class } +"AircraftComponent": { shape: class } +"Airframe": { shape: class } +"Wing": { shape: class } +"Fuselage": { shape: class } +"Empennage": { shape: class } +"Powerplant": { shape: class } +"TurbofanEngine": { shape: class } +"Propeller": { shape: class } +"LandingGear": { shape: class } +"FlightControlSurface": { shape: class } +"Avionics": { shape: class } +"FlightManagementComputer": { shape: class } +"Transponder": { shape: class } +"FuelSystem": { shape: class } +"HydraulicSystem": { shape: class } +"LifeLimitedPart": { shape: class } +"SparePart": { shape: class } +"Person": { shape: class } +"Organization": { shape: class } +"PilotInCommand": { shape: class } +"FirstOfficer": { shape: class } +"CertifyingEngineer": { shape: class } +"AirworthinessInspector": { shape: class } +"Operator": { shape: class } +"MaintenanceOrganization": { shape: class } +"Regulator": { shape: class } +"Airport": { shape: class } +"Runway": { shape: class } +"CertificationDocument": { shape: class } +"TypeCertificate": { shape: class } +"AirworthinessCertificate": { shape: class } +"AirworthinessDirective": { shape: class } +"PilotLicense": { shape: class } +"MedicalCertificate": { shape: class } +"MaintenanceRelease": { shape: class } +"MinimumEquipmentList": { shape: class } +"FlightPlan": { shape: class } +"TechnicalLogEntry": { shape: class } +"Defect": { shape: class } +"DeferredDefect": { shape: class } +"MaintenanceProcess": { shape: class } +"MaintenanceCheck": { shape: class } +"LineCheck": { shape: class } +"ACheck": { shape: class } +"CCheck": { shape: class } +"HeavyCheck": { shape: class } +"ComponentOverhaul": { shape: class } +"NonDestructiveInspection": { shape: class } +"DefectRectification": { shape: class } +"ComplianceAction": { shape: class } +"FlightOperation": { shape: class } +"Flight": { shape: class } +"CommercialFlight": { shape: class } +"FerryFlight": { shape: class } +"TestFlight": { shape: class } +"Takeoff": { shape: class } +"Landing": { shape: class } +"Cruise": { shape: class } +"PreflightInspection": { shape: class } +"Incident": { shape: class } +"RunwayExcursion": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Aircraft" -> "Object" +"FixedWingAircraft" -> "Aircraft" +"Airliner" -> "FixedWingAircraft" +"CargoAircraft" -> "FixedWingAircraft" +"BusinessJet" -> "FixedWingAircraft" +"Rotorcraft" -> "Aircraft" +"Helicopter" -> "Rotorcraft" +"UnmannedAircraft" -> "Aircraft" +"AircraftComponent" -> "Object" +"Airframe" -> "AircraftComponent" +"Wing" -> "Airframe" +"Fuselage" -> "Airframe" +"Empennage" -> "Airframe" +"Powerplant" -> "AircraftComponent" +"TurbofanEngine" -> "Powerplant" +"Propeller" -> "Powerplant" +"LandingGear" -> "AircraftComponent" +"FlightControlSurface" -> "AircraftComponent" +"Avionics" -> "AircraftComponent" +"FlightManagementComputer" -> "Avionics" +"Transponder" -> "Avionics" +"FuelSystem" -> "AircraftComponent" +"HydraulicSystem" -> "AircraftComponent" +"LifeLimitedPart" -> "AircraftComponent" +"SparePart" -> "Object" +"Person" -> "Object" +"Organization" -> "Object" +"PilotInCommand" -> "Role" +"FirstOfficer" -> "Role" +"CertifyingEngineer" -> "Role" +"AirworthinessInspector" -> "Role" +"Operator" -> "Role" +"MaintenanceOrganization" -> "Organization" +"Regulator" -> "Organization" +"Airport" -> "Object" +"Runway" -> "Object" +"CertificationDocument" -> "InformationContentEntity" +"TypeCertificate" -> "CertificationDocument" +"AirworthinessCertificate" -> "CertificationDocument" +"AirworthinessDirective" -> "CertificationDocument" +"PilotLicense" -> "CertificationDocument" +"MedicalCertificate" -> "CertificationDocument" +"MaintenanceRelease" -> "CertificationDocument" +"MinimumEquipmentList" -> "CertificationDocument" +"FlightPlan" -> "InformationContentEntity" +"TechnicalLogEntry" -> "InformationContentEntity" +"Defect" -> "InformationContentEntity" +"DeferredDefect" -> "Defect" +"MaintenanceProcess" -> "Process" +"MaintenanceCheck" -> "MaintenanceProcess" +"LineCheck" -> "MaintenanceCheck" +"ACheck" -> "MaintenanceCheck" +"CCheck" -> "MaintenanceCheck" +"HeavyCheck" -> "MaintenanceCheck" +"ComponentOverhaul" -> "MaintenanceProcess" +"NonDestructiveInspection" -> "MaintenanceProcess" +"DefectRectification" -> "MaintenanceProcess" +"ComplianceAction" -> "MaintenanceProcess" +"FlightOperation" -> "Process" +"Flight" -> "FlightOperation" +"CommercialFlight" -> "Flight" +"FerryFlight" -> "Flight" +"TestFlight" -> "Flight" +"Takeoff" -> "FlightOperation" +"Landing" -> "FlightOperation" +"Cruise" -> "FlightOperation" +"PreflightInspection" -> "FlightOperation" +"Incident" -> "Occurrent" +"RunwayExcursion" -> "Incident" +"Aircraft"."registration": String +"Aircraft"."max_takeoff_mass_kg": Integer +"Flight"."takeoff_mass_kg": Integer +"Flight"."fuel_load_kg": Integer +"Flight"."fuel_reserve_kg": Integer +"Aircraft"."total_flight_hours": Integer +"LifeLimitedPart"."flight_cycles": Integer +"LifeLimitedPart"."cycle_limit": Integer +"Aircraft"."hours_since_check": Integer +"Aircraft"."check_interval_hours": Integer +"AirworthinessCertificate"."certificate_valid": Boolean +"Aircraft"."is_airworthy": Boolean +"Aircraft"."is_released_to_service": Boolean +"PilotLicense"."license_current": Boolean +"Flight"."crew_size": Integer +"Flight"."cruise_altitude_ft": Integer +"AirworthinessDirective"."directive_complied": Boolean +"Aircraft"."open_defect_count": Integer +"AircraftComponent" -> "Aircraft": installed_on +"Aircraft" -> "AirworthinessCertificate": has_certificate +"Aircraft" -> "TypeCertificate": type_certified_by +"Aircraft" -> "Operator": operated_by +"Aircraft" -> "Flight": performs_flight +"Person" -> "Flight": commands +"Person" -> "PilotLicense": holds_license +"Flight" -> "Airport": departs_from +"Flight" -> "Airport": arrives_at +"Flight" -> "FlightPlan": follows_plan +"MaintenanceCheck" -> "Aircraft": inspects +"MaintenanceProcess" -> "MaintenanceOrganization": performed_by +"MaintenanceRelease" -> "CertifyingEngineer": certified_by +"MaintenanceRelease" -> "Aircraft": releases +"AirworthinessDirective" -> "Aircraft": applies_to +"Defect" -> "AircraftComponent": raised_against +"DefectRectification" -> "Defect": rectifies +"CertificationDocument" -> "Regulator": issued_by +"Incident" -> "Aircraft": involves +# WARNING: The following axioms could not be mapped to field constraints: +# forall a (Aircraft(a) and is_airworthy = True implies exists c (has_certificate(a, c))) +# forall a (Aircraft(a) and is_released_to_service = True implies is_airworthy = True) +# forall a (Aircraft(a) and gt(hours_since_check, 600) implies is_airworthy = False) +# forall p (forall f (commands(p, f) implies exists l (holds_license(p, l)))) +# forall a (Aircraft(a) and is_airworthy = True implies open_defect_count = 0) +# forall m (MaintenanceRelease(m) implies exists e (certified_by(m, e))) +# forall x (not Aircraft(x) and AircraftComponent(x)) +# forall x (not Flight(x) and MaintenanceProcess(x)) diff --git a/examples/domain_aerospace.d2.svg b/examples/domain_aerospace.d2.svg new file mode 100644 index 0000000..b94262d --- /dev/null +++ b/examples/domain_aerospace.d2.svg @@ -0,0 +1,120 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectOccurrentProcessRoleFunctionInformationContentEntityAircraft+registrationString+max_takeoff_mass_kgInteger+total_flight_hoursInteger+hours_since_checkInteger+check_interval_hoursInteger+is_airworthyBoolean+is_released_to_serviceBoolean+open_defect_countIntegerFixedWingAircraftAirlinerCargoAircraftBusinessJetRotorcraftHelicopterUnmannedAircraftAircraftComponentAirframeWingFuselageEmpennagePowerplantTurbofanEnginePropellerLandingGearFlightControlSurfaceAvionicsFlightManagementComputerTransponderFuelSystemHydraulicSystemLifeLimitedPart+flight_cyclesInteger+cycle_limitIntegerSparePartPersonOrganizationPilotInCommandFirstOfficerCertifyingEngineerAirworthinessInspectorOperatorMaintenanceOrganizationRegulatorAirportRunwayCertificationDocumentTypeCertificateAirworthinessCertificate+certificate_validBooleanAirworthinessDirective+directive_compliedBooleanPilotLicense+license_currentBooleanMedicalCertificateMaintenanceReleaseMinimumEquipmentListFlightPlanTechnicalLogEntryDefectDeferredDefectMaintenanceProcessMaintenanceCheckLineCheckACheckCCheckHeavyCheckComponentOverhaulNonDestructiveInspectionDefectRectificationComplianceActionFlightOperationFlight+takeoff_mass_kgInteger+fuel_load_kgInteger+fuel_reserve_kgInteger+crew_sizeInteger+cruise_altitude_ftIntegerCommercialFlightFerryFlightTestFlightTakeoffLandingCruisePreflightInspectionIncidentRunwayExcursion installed_onhas_certificatetype_certified_byoperated_byperforms_flightcommandsholds_licensedeparts_fromarrives_atfollows_planinspectsperformed_bycertified_byreleasesapplies_toraised_againstrectifiesissued_byinvolves + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_aerospace.logic b/examples/domain_aerospace.logic new file mode 100644 index 0000000..6bd4833 --- /dev/null +++ b/examples/domain_aerospace.logic @@ -0,0 +1,200 @@ +; Domain: Aerospace (airworthiness, maintenance and flight operations). +; Models aircraft, components, certification, maintenance checks, flight +; operations and crews, with a condensed BFO upper level. +; Axioms enforce: flight only with a valid airworthiness certificate, life-limited +; parts within limits, maintenance release before flight, crew licensing, +; mass and fuel limits, and component/aircraft disjointness. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Aircraft --- +(def-concept Aircraft Object) +(def-concept FixedWingAircraft Aircraft) +(def-concept Airliner FixedWingAircraft) +(def-concept CargoAircraft FixedWingAircraft) +(def-concept BusinessJet FixedWingAircraft) +(def-concept Rotorcraft Aircraft) +(def-concept Helicopter Rotorcraft) +(def-concept UnmannedAircraft Aircraft) + +; --- Components --- +(def-concept AircraftComponent Object) +(def-concept Airframe AircraftComponent) +(def-concept Wing Airframe) +(def-concept Fuselage Airframe) +(def-concept Empennage Airframe) +(def-concept Powerplant AircraftComponent) +(def-concept TurbofanEngine Powerplant) +(def-concept Propeller Powerplant) +(def-concept LandingGear AircraftComponent) +(def-concept FlightControlSurface AircraftComponent) +(def-concept Avionics AircraftComponent) +(def-concept FlightManagementComputer Avionics) +(def-concept Transponder Avionics) +(def-concept FuelSystem AircraftComponent) +(def-concept HydraulicSystem AircraftComponent) +(def-concept LifeLimitedPart AircraftComponent) +(def-concept SparePart Object) + +; --- Roles and people --- +(def-concept Person Object) +(def-concept Organization Object) +(def-concept PilotInCommand Role) +(def-concept FirstOfficer Role) +(def-concept CertifyingEngineer Role) +(def-concept AirworthinessInspector Role) +(def-concept Operator Role) +(def-concept MaintenanceOrganization Organization) +(def-concept Regulator Organization) +(def-concept Airport Object) +(def-concept Runway Object) + +; --- Certification and documents --- +(def-concept CertificationDocument InformationContentEntity) +(def-concept TypeCertificate CertificationDocument) +(def-concept AirworthinessCertificate CertificationDocument) +(def-concept AirworthinessDirective CertificationDocument) +(def-concept PilotLicense CertificationDocument) +(def-concept MedicalCertificate CertificationDocument) +(def-concept MaintenanceRelease CertificationDocument) +(def-concept MinimumEquipmentList CertificationDocument) +(def-concept FlightPlan InformationContentEntity) +(def-concept TechnicalLogEntry InformationContentEntity) +(def-concept Defect InformationContentEntity) +(def-concept DeferredDefect Defect) + +; --- Maintenance processes --- +(def-concept MaintenanceProcess Process) +(def-concept MaintenanceCheck MaintenanceProcess) +(def-concept LineCheck MaintenanceCheck) +(def-concept ACheck MaintenanceCheck) +(def-concept CCheck MaintenanceCheck) +(def-concept HeavyCheck MaintenanceCheck) +(def-concept ComponentOverhaul MaintenanceProcess) +(def-concept NonDestructiveInspection MaintenanceProcess) +(def-concept DefectRectification MaintenanceProcess) +(def-concept ComplianceAction MaintenanceProcess) + +; --- Flight operations --- +(def-concept FlightOperation Process) +(def-concept Flight FlightOperation) +(def-concept CommercialFlight Flight) +(def-concept FerryFlight Flight) +(def-concept TestFlight Flight) +(def-concept Takeoff FlightOperation) +(def-concept Landing FlightOperation) +(def-concept Cruise FlightOperation) +(def-concept PreflightInspection FlightOperation) +(def-concept Incident Occurrent) +(def-concept RunwayExcursion Incident) + +; --- Properties --- +(def-property registration Aircraft String :cardinality 1..1) +(def-property max_takeoff_mass_kg Aircraft Integer) +(def-property takeoff_mass_kg Flight Integer) +(def-property fuel_load_kg Flight Integer) +(def-property fuel_reserve_kg Flight Integer) +(def-property total_flight_hours Aircraft Integer) +(def-property flight_cycles LifeLimitedPart Integer) +(def-property cycle_limit LifeLimitedPart Integer) +(def-property hours_since_check Aircraft Integer) +(def-property check_interval_hours Aircraft Integer) +(def-property certificate_valid AirworthinessCertificate Boolean) +(def-property is_airworthy Aircraft Boolean) +(def-property is_released_to_service Aircraft Boolean) +(def-property license_current PilotLicense Boolean) +(def-property crew_size Flight Integer) +(def-property cruise_altitude_ft Flight Integer) +(def-property directive_complied AirworthinessDirective Boolean) +(def-property open_defect_count Aircraft Integer) + +; --- Relations --- +(def-relation installed_on AircraftComponent Aircraft) +(def-relation has_certificate Aircraft AirworthinessCertificate) +(def-relation type_certified_by Aircraft TypeCertificate) +(def-relation operated_by Aircraft Operator) +(def-relation performs_flight Aircraft Flight) +(def-relation commands Person Flight) +(def-relation holds_license Person PilotLicense) +(def-relation departs_from Flight Airport) +(def-relation arrives_at Flight Airport) +(def-relation follows_plan Flight FlightPlan) +(def-relation inspects MaintenanceCheck Aircraft) +(def-relation performed_by MaintenanceProcess MaintenanceOrganization) +(def-relation certified_by MaintenanceRelease CertifyingEngineer) +(def-relation releases MaintenanceRelease Aircraft) +(def-relation applies_to AirworthinessDirective Aircraft) +(def-relation raised_against Defect AircraftComponent) +(def-relation rectifies DefectRectification Defect) +(def-relation issued_by CertificationDocument Regulator) +(def-relation involves Incident Aircraft) + +; --- Axioms --- +; 1. Safety: an aircraft flagged airworthy must hold an airworthiness certificate. +(forall (a) + (implies (and (Aircraft a) (eq is_airworthy True)) + (exists (c) (has_certificate a c)))) + +; 2. Safety: a released-to-service aircraft must be airworthy. +(forall (a) + (implies (and (Aircraft a) (eq is_released_to_service True)) + (eq is_airworthy True))) + +; 3. Life limits: life-limited parts never exceed their cycle limit. +(forall (p) + (implies (LifeLimitedPart p) + (and (gte flight_cycles 0) (lte flight_cycles 50000)))) + +; 4. Maintenance: an aircraft whose check interval is exceeded is not airworthy. +(forall (a) + (implies (and (Aircraft a) (gt hours_since_check 600)) + (eq is_airworthy False))) + +; 5. Mass limit: takeoff mass stays within a physical bound for the fleet. +(forall (f) + (implies (Flight f) + (and (gt takeoff_mass_kg 0) (lte takeoff_mass_kg 600000)))) + +; 6. Fuel: every flight carries a positive fuel reserve. +(forall (f) + (implies (Flight f) + (gt fuel_reserve_kg 0))) + +; 7. Crew: commercial flights require at least two crew. +(forall (f) + (implies (CommercialFlight f) + (gte crew_size 2))) + +; 8. Licensing: the commander of a flight must hold a pilot license. +(forall (p f) + (implies (commands p f) + (exists (l) (holds_license p l)))) + +; 9. Airworthiness directives: no open defects on an airworthy aircraft. +(forall (a) + (implies (and (Aircraft a) (eq is_airworthy True)) + (eq open_defect_count 0))) + +; 10. Release: a maintenance release must be certified by a certifying engineer. +(forall (m) + (implies (MaintenanceRelease m) + (exists (e) (certified_by m e)))) + +; 11. Altitude: cruise altitude stays within the certified ceiling. +(forall (f) + (implies (Flight f) + (and (gte cruise_altitude_ft 0) (lte cruise_altitude_ft 51000)))) + +; 12. Disjointness: aircraft and their components are different kinds of object. +(forall (x) (not (and (Aircraft x) (AircraftComponent x)))) +(forall (x) (not (and (Flight x) (MaintenanceProcess x)))) diff --git a/examples/domain_aerospace.mmd b/examples/domain_aerospace.mmd new file mode 100644 index 0000000..a9d3a9c --- /dev/null +++ b/examples/domain_aerospace.mmd @@ -0,0 +1,205 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class InformationContentEntity["InformationContentEntity"] + class Aircraft["Aircraft"] + class FixedWingAircraft["FixedWingAircraft"] + class Airliner["Airliner"] + class CargoAircraft["CargoAircraft"] + class BusinessJet["BusinessJet"] + class Rotorcraft["Rotorcraft"] + class Helicopter["Helicopter"] + class UnmannedAircraft["UnmannedAircraft"] + class AircraftComponent["AircraftComponent"] + class Airframe["Airframe"] + class Wing["Wing"] + class Fuselage["Fuselage"] + class Empennage["Empennage"] + class Powerplant["Powerplant"] + class TurbofanEngine["TurbofanEngine"] + class Propeller["Propeller"] + class LandingGear["LandingGear"] + class FlightControlSurface["FlightControlSurface"] + class Avionics["Avionics"] + class FlightManagementComputer["FlightManagementComputer"] + class Transponder["Transponder"] + class FuelSystem["FuelSystem"] + class HydraulicSystem["HydraulicSystem"] + class LifeLimitedPart["LifeLimitedPart"] + class SparePart["SparePart"] + class Person["Person"] + class Organization["Organization"] + class PilotInCommand["PilotInCommand"] + class FirstOfficer["FirstOfficer"] + class CertifyingEngineer["CertifyingEngineer"] + class AirworthinessInspector["AirworthinessInspector"] + class Operator["Operator"] + class MaintenanceOrganization["MaintenanceOrganization"] + class Regulator["Regulator"] + class Airport["Airport"] + class Runway["Runway"] + class CertificationDocument["CertificationDocument"] + class TypeCertificate["TypeCertificate"] + class AirworthinessCertificate["AirworthinessCertificate"] + class AirworthinessDirective["AirworthinessDirective"] + class PilotLicense["PilotLicense"] + class MedicalCertificate["MedicalCertificate"] + class MaintenanceRelease["MaintenanceRelease"] + class MinimumEquipmentList["MinimumEquipmentList"] + class FlightPlan["FlightPlan"] + class TechnicalLogEntry["TechnicalLogEntry"] + class Defect["Defect"] + class DeferredDefect["DeferredDefect"] + class MaintenanceProcess["MaintenanceProcess"] + class MaintenanceCheck["MaintenanceCheck"] + class LineCheck["LineCheck"] + class ACheck["ACheck"] + class CCheck["CCheck"] + class HeavyCheck["HeavyCheck"] + class ComponentOverhaul["ComponentOverhaul"] + class NonDestructiveInspection["NonDestructiveInspection"] + class DefectRectification["DefectRectification"] + class ComplianceAction["ComplianceAction"] + class FlightOperation["FlightOperation"] + class Flight["Flight"] + class CommercialFlight["CommercialFlight"] + class FerryFlight["FerryFlight"] + class TestFlight["TestFlight"] + class Takeoff["Takeoff"] + class Landing["Landing"] + class Cruise["Cruise"] + class PreflightInspection["PreflightInspection"] + class Incident["Incident"] + class RunwayExcursion["RunwayExcursion"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- InformationContentEntity + Object <|-- Aircraft + Aircraft <|-- FixedWingAircraft + FixedWingAircraft <|-- Airliner + FixedWingAircraft <|-- CargoAircraft + FixedWingAircraft <|-- BusinessJet + Aircraft <|-- Rotorcraft + Rotorcraft <|-- Helicopter + Aircraft <|-- UnmannedAircraft + Object <|-- AircraftComponent + AircraftComponent <|-- Airframe + Airframe <|-- Wing + Airframe <|-- Fuselage + Airframe <|-- Empennage + AircraftComponent <|-- Powerplant + Powerplant <|-- TurbofanEngine + Powerplant <|-- Propeller + AircraftComponent <|-- LandingGear + AircraftComponent <|-- FlightControlSurface + AircraftComponent <|-- Avionics + Avionics <|-- FlightManagementComputer + Avionics <|-- Transponder + AircraftComponent <|-- FuelSystem + AircraftComponent <|-- HydraulicSystem + AircraftComponent <|-- LifeLimitedPart + Object <|-- SparePart + Object <|-- Person + Object <|-- Organization + Role <|-- PilotInCommand + Role <|-- FirstOfficer + Role <|-- CertifyingEngineer + Role <|-- AirworthinessInspector + Role <|-- Operator + Organization <|-- MaintenanceOrganization + Organization <|-- Regulator + Object <|-- Airport + Object <|-- Runway + InformationContentEntity <|-- CertificationDocument + CertificationDocument <|-- TypeCertificate + CertificationDocument <|-- AirworthinessCertificate + CertificationDocument <|-- AirworthinessDirective + CertificationDocument <|-- PilotLicense + CertificationDocument <|-- MedicalCertificate + CertificationDocument <|-- MaintenanceRelease + CertificationDocument <|-- MinimumEquipmentList + InformationContentEntity <|-- FlightPlan + InformationContentEntity <|-- TechnicalLogEntry + InformationContentEntity <|-- Defect + Defect <|-- DeferredDefect + Process <|-- MaintenanceProcess + MaintenanceProcess <|-- MaintenanceCheck + MaintenanceCheck <|-- LineCheck + MaintenanceCheck <|-- ACheck + MaintenanceCheck <|-- CCheck + MaintenanceCheck <|-- HeavyCheck + MaintenanceProcess <|-- ComponentOverhaul + MaintenanceProcess <|-- NonDestructiveInspection + MaintenanceProcess <|-- DefectRectification + MaintenanceProcess <|-- ComplianceAction + Process <|-- FlightOperation + FlightOperation <|-- Flight + Flight <|-- CommercialFlight + Flight <|-- FerryFlight + Flight <|-- TestFlight + FlightOperation <|-- Takeoff + FlightOperation <|-- Landing + FlightOperation <|-- Cruise + FlightOperation <|-- PreflightInspection + Occurrent <|-- Incident + Incident <|-- RunwayExcursion + Aircraft : +String registration + Aircraft : +Integer max_takeoff_mass_kg + Flight : +Integer takeoff_mass_kg + Flight : +Integer fuel_load_kg + Flight : +Integer fuel_reserve_kg + Aircraft : +Integer total_flight_hours + LifeLimitedPart : +Integer flight_cycles + LifeLimitedPart : +Integer cycle_limit + Aircraft : +Integer hours_since_check + Aircraft : +Integer check_interval_hours + AirworthinessCertificate : +Boolean certificate_valid + Aircraft : +Boolean is_airworthy + Aircraft : +Boolean is_released_to_service + PilotLicense : +Boolean license_current + Flight : +Integer crew_size + Flight : +Integer cruise_altitude_ft + AirworthinessDirective : +Boolean directive_complied + Aircraft : +Integer open_defect_count + AircraftComponent --> Aircraft : installed_on + Aircraft --> AirworthinessCertificate : has_certificate + Aircraft --> TypeCertificate : type_certified_by + Aircraft --> Operator : operated_by + Aircraft --> Flight : performs_flight + Person --> Flight : commands + Person --> PilotLicense : holds_license + Flight --> Airport : departs_from + Flight --> Airport : arrives_at + Flight --> FlightPlan : follows_plan + MaintenanceCheck --> Aircraft : inspects + MaintenanceProcess --> MaintenanceOrganization : performed_by + MaintenanceRelease --> CertifyingEngineer : certified_by + MaintenanceRelease --> Aircraft : releases + AirworthinessDirective --> Aircraft : applies_to + Defect --> AircraftComponent : raised_against + DefectRectification --> Defect : rectifies + CertificationDocument --> Regulator : issued_by + Incident --> Aircraft : involves + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall a (Aircraft(a) and is_airworthy = True implies exists c (has_certificate(a, c))) +%% forall a (Aircraft(a) and is_released_to_service = True implies is_airworthy = True) +%% forall a (Aircraft(a) and gt(hours_since_check, 600) implies is_airworthy = False) +%% forall p (forall f (commands(p, f) implies exists l (holds_license(p, l)))) +%% forall a (Aircraft(a) and is_airworthy = True implies open_defect_count = 0) +%% forall m (MaintenanceRelease(m) implies exists e (certified_by(m, e))) +%% forall x (not Aircraft(x) and AircraftComponent(x)) +%% forall x (not Flight(x) and MaintenanceProcess(x)) diff --git a/examples/domain_agriculture.cypher b/examples/domain_agriculture.cypher new file mode 100644 index 0000000..1ea88bf --- /dev/null +++ b/examples/domain_agriculture.cypher @@ -0,0 +1,367 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Farm'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Field'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ArableField'}) +MERGE (p:OntologyClass {name: 'Field'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pasture'}) +MERGE (p:OntologyClass {name: 'Field'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Orchard'}) +MERGE (p:OntologyClass {name: 'Field'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Greenhouse'}) +MERGE (p:OntologyClass {name: 'Field'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Paddock'}) +MERGE (p:OntologyClass {name: 'Field'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Barn'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MilkingParlour'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GrainSilo'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WaterSource'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Borehole'}) +MERGE (p:OntologyClass {name: 'WaterSource'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Reservoir'}) +MERGE (p:OntologyClass {name: 'WaterSource'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Farmer'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FarmHand'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agronomist'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Veterinarian'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Inspector'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Plant'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Crop'}) +MERGE (p:OntologyClass {name: 'Plant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CerealCrop'}) +MERGE (p:OntologyClass {name: 'Crop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Wheat'}) +MERGE (p:OntologyClass {name: 'CerealCrop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Maize'}) +MERGE (p:OntologyClass {name: 'CerealCrop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Barley'}) +MERGE (p:OntologyClass {name: 'CerealCrop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LegumeCrop'}) +MERGE (p:OntologyClass {name: 'Crop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Soybean'}) +MERGE (p:OntologyClass {name: 'LegumeCrop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VegetableCrop'}) +MERGE (p:OntologyClass {name: 'Crop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tomato'}) +MERGE (p:OntologyClass {name: 'VegetableCrop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FruitCrop'}) +MERGE (p:OntologyClass {name: 'Crop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Apple'}) +MERGE (p:OntologyClass {name: 'FruitCrop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CoverCrop'}) +MERGE (p:OntologyClass {name: 'Crop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Weed'}) +MERGE (p:OntologyClass {name: 'Plant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pest'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CropDisease'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Animal'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Livestock'}) +MERGE (p:OntologyClass {name: 'Animal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Cattle'}) +MERGE (p:OntologyClass {name: 'Livestock'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DairyCow'}) +MERGE (p:OntologyClass {name: 'Cattle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BeefCattle'}) +MERGE (p:OntologyClass {name: 'Cattle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sheep'}) +MERGE (p:OntologyClass {name: 'Livestock'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pig'}) +MERGE (p:OntologyClass {name: 'Livestock'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Poultry'}) +MERGE (p:OntologyClass {name: 'Livestock'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Herd'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Flock'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Feed'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VeterinaryTreatment'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Vaccination'}) +MERGE (p:OntologyClass {name: 'VeterinaryTreatment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AntibioticTreatment'}) +MERGE (p:OntologyClass {name: 'VeterinaryTreatment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quarantine'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IrrigationSystem'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DripIrrigation'}) +MERGE (p:OntologyClass {name: 'IrrigationSystem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PivotIrrigation'}) +MERGE (p:OntologyClass {name: 'IrrigationSystem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sprinkler'}) +MERGE (p:OntologyClass {name: 'IrrigationSystem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pump'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Valve'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sensor'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SoilSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MoistureSensor'}) +MERGE (p:OntologyClass {name: 'SoilSensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PhSensor'}) +MERGE (p:OntologyClass {name: 'SoilSensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NitrogenSensor'}) +MERGE (p:OntologyClass {name: 'SoilSensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WeatherStation'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SensorReading'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Soil'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Fertilizer'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pesticide'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FarmOperation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Planting'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Irrigating'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Fertilizing'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Spraying'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Harvesting'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Milking'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Grazing'}) +MERGE (p:OntologyClass {name: 'FarmOperation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Harvest'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GrainHarvest'}) +MERGE (p:OntologyClass {name: 'Harvest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FruitHarvest'}) +MERGE (p:OntologyClass {name: 'Harvest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HarvestLot'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FieldRecord'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Farmer'}) +MERGE (t:OntologyClass {name: 'Farm'}) +MERGE (s)-[:RELATION {name: 'owns'}]->(t); +MERGE (s:OntologyClass {name: 'Field'}) +MERGE (t:OntologyClass {name: 'Farm'}) +MERGE (s)-[:RELATION {name: 'part_of'}]->(t); +MERGE (s:OntologyClass {name: 'Field'}) +MERGE (t:OntologyClass {name: 'Crop'}) +MERGE (s)-[:RELATION {name: 'planted_with'}]->(t); +MERGE (s:OntologyClass {name: 'IrrigationSystem'}) +MERGE (t:OntologyClass {name: 'Field'}) +MERGE (s)-[:RELATION {name: 'irrigates'}]->(t); +MERGE (s:OntologyClass {name: 'IrrigationSystem'}) +MERGE (t:OntologyClass {name: 'WaterSource'}) +MERGE (s)-[:RELATION {name: 'supplied_by'}]->(t); +MERGE (s:OntologyClass {name: 'IrrigationSystem'}) +MERGE (t:OntologyClass {name: 'Pump'}) +MERGE (s)-[:RELATION {name: 'powered_by'}]->(t); +MERGE (s:OntologyClass {name: 'Valve'}) +MERGE (t:OntologyClass {name: 'IrrigationSystem'}) +MERGE (s)-[:RELATION {name: 'controls'}]->(t); +MERGE (s:OntologyClass {name: 'SoilSensor'}) +MERGE (t:OntologyClass {name: 'Field'}) +MERGE (s)-[:RELATION {name: 'installed_in'}]->(t); +MERGE (s:OntologyClass {name: 'SensorReading'}) +MERGE (t:OntologyClass {name: 'SoilSensor'}) +MERGE (s)-[:RELATION {name: 'measures'}]->(t); +MERGE (s:OntologyClass {name: 'Herd'}) +MERGE (t:OntologyClass {name: 'Paddock'}) +MERGE (s)-[:RELATION {name: 'grazes'}]->(t); +MERGE (s:OntologyClass {name: 'Livestock'}) +MERGE (t:OntologyClass {name: 'Herd'}) +MERGE (s)-[:RELATION {name: 'member_of'}]->(t); +MERGE (s:OntologyClass {name: 'Livestock'}) +MERGE (t:OntologyClass {name: 'Feed'}) +MERGE (s)-[:RELATION {name: 'fed_with'}]->(t); +MERGE (s:OntologyClass {name: 'Livestock'}) +MERGE (t:OntologyClass {name: 'VeterinaryTreatment'}) +MERGE (s)-[:RELATION {name: 'treated_with'}]->(t); +MERGE (s:OntologyClass {name: 'VeterinaryTreatment'}) +MERGE (t:OntologyClass {name: 'Veterinarian'}) +MERGE (s)-[:RELATION {name: 'administered_by'}]->(t); +MERGE (s:OntologyClass {name: 'Harvest'}) +MERGE (t:OntologyClass {name: 'Field'}) +MERGE (s)-[:RELATION {name: 'harvested_from'}]->(t); +MERGE (s:OntologyClass {name: 'Harvest'}) +MERGE (t:OntologyClass {name: 'HarvestLot'}) +MERGE (s)-[:RELATION {name: 'yields'}]->(t); +MERGE (s:OntologyClass {name: 'Field'}) +MERGE (t:OntologyClass {name: 'Agronomist'}) +MERGE (s)-[:RELATION {name: 'advised_by'}]->(t); +MERGE (s:OntologyClass {name: 'Pest'}) +MERGE (t:OntologyClass {name: 'Crop'}) +MERGE (s)-[:RELATION {name: 'threatens'}]->(t); +MERGE (s:OntologyClass {name: 'CropDisease'}) +MERGE (t:OntologyClass {name: 'Crop'}) +MERGE (s)-[:RELATION {name: 'affects'}]->(t); +MERGE (s:OntologyClass {name: 'Fertilizer'}) +MERGE (t:OntologyClass {name: 'Field'}) +MERGE (s)-[:RELATION {name: 'applied_to'}]->(t); +MERGE (s:OntologyClass {name: 'Livestock'}) +MERGE (t:OntologyClass {name: 'Barn'}) +MERGE (s)-[:RELATION {name: 'housed_in'}]->(t); +// Axiom Validations +// Axiom validation: Paddock stocking_density lte 40 +MATCH (n:`Paddock`) WHERE NOT (n.`stocking_density` <= 40) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Reservoir tank_level_percent gte 0 +MATCH (n:`Reservoir`) WHERE NOT (n.`tank_level_percent` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Reservoir tank_level_percent lte 100 +MATCH (n:`Reservoir`) WHERE NOT (n.`tank_level_percent` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: AntibioticTreatment withdrawal_days gte 7 +MATCH (n:`AntibioticTreatment`) WHERE NOT (n.`withdrawal_days` >= 7) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: MoistureSensor soil_moisture_percent gte 0 +MATCH (n:`MoistureSensor`) WHERE NOT (n.`soil_moisture_percent` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: MoistureSensor soil_moisture_percent lte 100 +MATCH (n:`MoistureSensor`) WHERE NOT (n.`soil_moisture_percent` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: PhSensor soil_ph gte 3 +MATCH (n:`PhSensor`) WHERE NOT (n.`soil_ph` >= 3) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: PhSensor soil_ph lte 10 +MATCH (n:`PhSensor`) WHERE NOT (n.`soil_ph` <= 10) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: HarvestLot has_traceability_lot eq True +MATCH (n:`HarvestLot`) WHERE NOT (n.`has_traceability_lot` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall x (not Crop(x) and Livestock(x)) +// forall x (not Crop(x) and Weed(x)) +// forall x (not Fertilizer(x) and Pesticide(x)) +// forall x (not Farmer(x) and Inspector(x)) +// forall s (MoistureSensor(s) and lt(soil_moisture_percent, 20) implies exists i (IrrigationSystem(i))) +// forall a (Livestock(a) and in_quarantine = True implies sold_for_slaughter = False) +// forall s (Spraying(s) and pesticide_applied = True implies gte(days_before_harvest, 14)) diff --git a/examples/domain_agriculture.d2 b/examples/domain_agriculture.d2 new file mode 100644 index 0000000..beb387c --- /dev/null +++ b/examples/domain_agriculture.d2 @@ -0,0 +1,237 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Farm": { shape: class } +"Field": { shape: class } +"ArableField": { shape: class } +"Pasture": { shape: class } +"Orchard": { shape: class } +"Greenhouse": { shape: class } +"Paddock": { shape: class } +"Barn": { shape: class } +"MilkingParlour": { shape: class } +"GrainSilo": { shape: class } +"WaterSource": { shape: class } +"Borehole": { shape: class } +"Reservoir": { shape: class } +"Person": { shape: class } +"Farmer": { shape: class } +"FarmHand": { shape: class } +"Agronomist": { shape: class } +"Veterinarian": { shape: class } +"Inspector": { shape: class } +"Plant": { shape: class } +"Crop": { shape: class } +"CerealCrop": { shape: class } +"Wheat": { shape: class } +"Maize": { shape: class } +"Barley": { shape: class } +"LegumeCrop": { shape: class } +"Soybean": { shape: class } +"VegetableCrop": { shape: class } +"Tomato": { shape: class } +"FruitCrop": { shape: class } +"Apple": { shape: class } +"CoverCrop": { shape: class } +"Weed": { shape: class } +"Pest": { shape: class } +"CropDisease": { shape: class } +"Animal": { shape: class } +"Livestock": { shape: class } +"Cattle": { shape: class } +"DairyCow": { shape: class } +"BeefCattle": { shape: class } +"Sheep": { shape: class } +"Pig": { shape: class } +"Poultry": { shape: class } +"Herd": { shape: class } +"Flock": { shape: class } +"Feed": { shape: class } +"VeterinaryTreatment": { shape: class } +"Vaccination": { shape: class } +"AntibioticTreatment": { shape: class } +"Quarantine": { shape: class } +"IrrigationSystem": { shape: class } +"DripIrrigation": { shape: class } +"PivotIrrigation": { shape: class } +"Sprinkler": { shape: class } +"Pump": { shape: class } +"Valve": { shape: class } +"Sensor": { shape: class } +"SoilSensor": { shape: class } +"MoistureSensor": { shape: class } +"PhSensor": { shape: class } +"NitrogenSensor": { shape: class } +"WeatherStation": { shape: class } +"SensorReading": { shape: class } +"Soil": { shape: class } +"Fertilizer": { shape: class } +"Pesticide": { shape: class } +"FarmOperation": { shape: class } +"Planting": { shape: class } +"Irrigating": { shape: class } +"Fertilizing": { shape: class } +"Spraying": { shape: class } +"Harvesting": { shape: class } +"Milking": { shape: class } +"Grazing": { shape: class } +"Harvest": { shape: class } +"GrainHarvest": { shape: class } +"FruitHarvest": { shape: class } +"HarvestLot": { shape: class } +"FieldRecord": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "Object" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Farm" -> "Site" +"Field" -> "Site" +"ArableField" -> "Field" +"Pasture" -> "Field" +"Orchard" -> "Field" +"Greenhouse" -> "Field" +"Paddock" -> "Field" +"Barn" -> "Site" +"MilkingParlour" -> "Site" +"GrainSilo" -> "Site" +"WaterSource" -> "Site" +"Borehole" -> "WaterSource" +"Reservoir" -> "WaterSource" +"Person" -> "Agent" +"Farmer" -> "Person" +"FarmHand" -> "Person" +"Agronomist" -> "Person" +"Veterinarian" -> "Person" +"Inspector" -> "Person" +"Plant" -> "MaterialEntity" +"Crop" -> "Plant" +"CerealCrop" -> "Crop" +"Wheat" -> "CerealCrop" +"Maize" -> "CerealCrop" +"Barley" -> "CerealCrop" +"LegumeCrop" -> "Crop" +"Soybean" -> "LegumeCrop" +"VegetableCrop" -> "Crop" +"Tomato" -> "VegetableCrop" +"FruitCrop" -> "Crop" +"Apple" -> "FruitCrop" +"CoverCrop" -> "Crop" +"Weed" -> "Plant" +"Pest" -> "Object" +"CropDisease" -> "Quality" +"Animal" -> "MaterialEntity" +"Livestock" -> "Animal" +"Cattle" -> "Livestock" +"DairyCow" -> "Cattle" +"BeefCattle" -> "Cattle" +"Sheep" -> "Livestock" +"Pig" -> "Livestock" +"Poultry" -> "Livestock" +"Herd" -> "Object" +"Flock" -> "Object" +"Feed" -> "MaterialEntity" +"VeterinaryTreatment" -> "Process" +"Vaccination" -> "VeterinaryTreatment" +"AntibioticTreatment" -> "VeterinaryTreatment" +"Quarantine" -> "Process" +"IrrigationSystem" -> "Object" +"DripIrrigation" -> "IrrigationSystem" +"PivotIrrigation" -> "IrrigationSystem" +"Sprinkler" -> "IrrigationSystem" +"Pump" -> "Object" +"Valve" -> "Object" +"Sensor" -> "Object" +"SoilSensor" -> "Sensor" +"MoistureSensor" -> "SoilSensor" +"PhSensor" -> "SoilSensor" +"NitrogenSensor" -> "SoilSensor" +"WeatherStation" -> "Sensor" +"SensorReading" -> "InformationContentEntity" +"Soil" -> "MaterialEntity" +"Fertilizer" -> "MaterialEntity" +"Pesticide" -> "MaterialEntity" +"FarmOperation" -> "Process" +"Planting" -> "FarmOperation" +"Irrigating" -> "FarmOperation" +"Fertilizing" -> "FarmOperation" +"Spraying" -> "FarmOperation" +"Harvesting" -> "FarmOperation" +"Milking" -> "FarmOperation" +"Grazing" -> "FarmOperation" +"Harvest" -> "InformationContentEntity" +"GrainHarvest" -> "Harvest" +"FruitHarvest" -> "Harvest" +"HarvestLot" -> "InformationContentEntity" +"FieldRecord" -> "InformationContentEntity" +"Field"."area_hectares": Float +"SoilSensor"."soil_ph": Float +"MoistureSensor"."soil_moisture_percent": Integer +"NitrogenSensor"."soil_nitrogen_ppm": Integer +"Field"."needs_irrigation": Boolean +"IrrigationSystem"."irrigation_active": Boolean +"Pump"."flow_rate_lpm": Integer +"Reservoir"."tank_level_percent": Integer +"WeatherStation"."air_temperature_c": Integer +"Crop"."crop_variety": String +"Crop"."days_to_maturity": Integer +"Harvest"."expected_yield_tonnes": Float +"Harvest"."moisture_at_harvest": Integer +"HarvestLot"."has_traceability_lot": Boolean +"Herd"."animal_count": Integer +"Paddock"."stocking_density": Integer +"Livestock"."ear_tag": String +"Livestock"."body_weight_kg": Integer +"AntibioticTreatment"."withdrawal_days": Integer +"Livestock"."days_since_treatment": Integer +"Livestock"."in_quarantine": Boolean +"Livestock"."sold_for_slaughter": Boolean +"Spraying"."pesticide_applied": Boolean +"Spraying"."days_before_harvest": Integer +"Farmer" -> "Farm": owns +"Field" -> "Farm": part_of +"Field" -> "Crop": planted_with +"IrrigationSystem" -> "Field": irrigates +"IrrigationSystem" -> "WaterSource": supplied_by +"IrrigationSystem" -> "Pump": powered_by +"Valve" -> "IrrigationSystem": controls +"SoilSensor" -> "Field": installed_in +"SensorReading" -> "SoilSensor": measures +"Herd" -> "Paddock": grazes +"Livestock" -> "Herd": member_of +"Livestock" -> "Feed": fed_with +"Livestock" -> "VeterinaryTreatment": treated_with +"VeterinaryTreatment" -> "Veterinarian": administered_by +"Harvest" -> "Field": harvested_from +"Harvest" -> "HarvestLot": yields +"Field" -> "Agronomist": advised_by +"Pest" -> "Crop": threatens +"CropDisease" -> "Crop": affects +"Fertilizer" -> "Field": applied_to +"Livestock" -> "Barn": housed_in +# WARNING: The following axioms could not be mapped to field constraints: +# forall x (not Crop(x) and Livestock(x)) +# forall x (not Crop(x) and Weed(x)) +# forall x (not Fertilizer(x) and Pesticide(x)) +# forall x (not Farmer(x) and Inspector(x)) +# forall s (MoistureSensor(s) and lt(soil_moisture_percent, 20) implies exists i (IrrigationSystem(i))) +# forall a (Livestock(a) and in_quarantine = True implies sold_for_slaughter = False) +# forall s (Spraying(s) and pesticide_applied = True implies gte(days_before_harvest, 14)) diff --git a/examples/domain_agriculture.d2.svg b/examples/domain_agriculture.d2.svg new file mode 100644 index 0000000..1391cda --- /dev/null +++ b/examples/domain_agriculture.d2.svg @@ -0,0 +1,122 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentSiteOccurrentProcessRoleFunctionQualityInformationContentEntityFarmField+area_hectaresFloat+needs_irrigationBooleanArableFieldPastureOrchardGreenhousePaddock+stocking_densityIntegerBarnMilkingParlourGrainSiloWaterSourceBoreholeReservoir+tank_level_percentIntegerPersonFarmerFarmHandAgronomistVeterinarianInspectorPlantCrop+crop_varietyString+days_to_maturityIntegerCerealCropWheatMaizeBarleyLegumeCropSoybeanVegetableCropTomatoFruitCropAppleCoverCropWeedPestCropDiseaseAnimalLivestock+ear_tagString+body_weight_kgInteger+days_since_treatmentInteger+in_quarantineBoolean+sold_for_slaughterBooleanCattleDairyCowBeefCattleSheepPigPoultryHerd+animal_countIntegerFlockFeedVeterinaryTreatmentVaccinationAntibioticTreatment+withdrawal_daysIntegerQuarantineIrrigationSystem+irrigation_activeBooleanDripIrrigationPivotIrrigationSprinklerPump+flow_rate_lpmIntegerValveSensorSoilSensor+soil_phFloatMoistureSensor+soil_moisture_percentIntegerPhSensorNitrogenSensor+soil_nitrogen_ppmIntegerWeatherStation+air_temperature_cIntegerSensorReadingSoilFertilizerPesticideFarmOperationPlantingIrrigatingFertilizingSpraying+pesticide_appliedBoolean+days_before_harvestIntegerHarvestingMilkingGrazingHarvest+expected_yield_tonnesFloat+moisture_at_harvestIntegerGrainHarvestFruitHarvestHarvestLot+has_traceability_lotBooleanFieldRecord ownspart_ofplanted_withirrigatessupplied_bypowered_bycontrolsinstalled_inmeasuresgrazesmember_offed_withtreated_withadministered_byharvested_fromyieldsadvised_bythreatensaffectsapplied_tohoused_in + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_agriculture.logic b/examples/domain_agriculture.logic new file mode 100644 index 0000000..1950a44 --- /dev/null +++ b/examples/domain_agriculture.logic @@ -0,0 +1,192 @@ +; ===================================================================== +; Domain: Agriculture +; Models farms, fields, crops, livestock, irrigation, soil sensors and +; harvests on a condensed BFO upper level. +; Axioms enforce: agronomic limits (soil pH and moisture ranges, irrigation +; triggered by dry soil), livestock welfare and biosecurity (withdrawal +; periods, stocking density, quarantine), harvest traceability, and +; disjointness of crops and livestock. +; ===================================================================== + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent Object) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Farm Structure --- +(def-concept Farm Site) +(def-concept Field Site) +(def-concept ArableField Field) +(def-concept Pasture Field) +(def-concept Orchard Field) +(def-concept Greenhouse Field) +(def-concept Paddock Field) +(def-concept Barn Site) +(def-concept MilkingParlour Site) +(def-concept GrainSilo Site) +(def-concept WaterSource Site) +(def-concept Borehole WaterSource) +(def-concept Reservoir WaterSource) + +; --- People --- +(def-concept Person Agent) +(def-concept Farmer Person) +(def-concept FarmHand Person) +(def-concept Agronomist Person) +(def-concept Veterinarian Person) +(def-concept Inspector Person) + +; --- Crops --- +(def-concept Plant MaterialEntity) +(def-concept Crop Plant) +(def-concept CerealCrop Crop) +(def-concept Wheat CerealCrop) +(def-concept Maize CerealCrop) +(def-concept Barley CerealCrop) +(def-concept LegumeCrop Crop) +(def-concept Soybean LegumeCrop) +(def-concept VegetableCrop Crop) +(def-concept Tomato VegetableCrop) +(def-concept FruitCrop Crop) +(def-concept Apple FruitCrop) +(def-concept CoverCrop Crop) +(def-concept Weed Plant) +(def-concept Pest Object) +(def-concept CropDisease Quality) + +; --- Livestock --- +(def-concept Animal MaterialEntity) +(def-concept Livestock Animal) +(def-concept Cattle Livestock) +(def-concept DairyCow Cattle) +(def-concept BeefCattle Cattle) +(def-concept Sheep Livestock) +(def-concept Pig Livestock) +(def-concept Poultry Livestock) +(def-concept Herd Object) +(def-concept Flock Object) +(def-concept Feed MaterialEntity) +(def-concept VeterinaryTreatment Process) +(def-concept Vaccination VeterinaryTreatment) +(def-concept AntibioticTreatment VeterinaryTreatment) +(def-concept Quarantine Process) + +; --- Irrigation and Soil --- +(def-concept IrrigationSystem Object) +(def-concept DripIrrigation IrrigationSystem) +(def-concept PivotIrrigation IrrigationSystem) +(def-concept Sprinkler IrrigationSystem) +(def-concept Pump Object) +(def-concept Valve Object) +(def-concept Sensor Object) +(def-concept SoilSensor Sensor) +(def-concept MoistureSensor SoilSensor) +(def-concept PhSensor SoilSensor) +(def-concept NitrogenSensor SoilSensor) +(def-concept WeatherStation Sensor) +(def-concept SensorReading InformationContentEntity) +(def-concept Soil MaterialEntity) +(def-concept Fertilizer MaterialEntity) +(def-concept Pesticide MaterialEntity) + +; --- Processes --- +(def-concept FarmOperation Process) +(def-concept Planting FarmOperation) +(def-concept Irrigating FarmOperation) +(def-concept Fertilizing FarmOperation) +(def-concept Spraying FarmOperation) +(def-concept Harvesting FarmOperation) +(def-concept Milking FarmOperation) +(def-concept Grazing FarmOperation) +(def-concept Harvest InformationContentEntity) +(def-concept GrainHarvest Harvest) +(def-concept FruitHarvest Harvest) +(def-concept HarvestLot InformationContentEntity) +(def-concept FieldRecord InformationContentEntity) + +; --- Properties --- +(def-property area_hectares Field Float) +(def-property soil_ph SoilSensor Float) +(def-property soil_moisture_percent MoistureSensor Integer) +(def-property soil_nitrogen_ppm NitrogenSensor Integer) +(def-property needs_irrigation Field Boolean) +(def-property irrigation_active IrrigationSystem Boolean) +(def-property flow_rate_lpm Pump Integer) +(def-property tank_level_percent Reservoir Integer) +(def-property air_temperature_c WeatherStation Integer) +(def-property crop_variety Crop String) +(def-property days_to_maturity Crop Integer) +(def-property expected_yield_tonnes Harvest Float) +(def-property moisture_at_harvest Harvest Integer) +(def-property has_traceability_lot HarvestLot Boolean) +(def-property animal_count Herd Integer) +(def-property stocking_density Paddock Integer) +(def-property ear_tag Livestock String) +(def-property body_weight_kg Livestock Integer) +(def-property withdrawal_days AntibioticTreatment Integer) +(def-property days_since_treatment Livestock Integer) +(def-property in_quarantine Livestock Boolean) +(def-property sold_for_slaughter Livestock Boolean) +(def-property pesticide_applied Spraying Boolean) +(def-property days_before_harvest Spraying Integer) + +; --- Relations --- +(def-relation owns Farmer Farm) +(def-relation part_of Field Farm) +(def-relation planted_with Field Crop) +(def-relation irrigates IrrigationSystem Field) +(def-relation supplied_by IrrigationSystem WaterSource) +(def-relation powered_by IrrigationSystem Pump) +(def-relation controls Valve IrrigationSystem) +(def-relation installed_in SoilSensor Field) +(def-relation measures SensorReading SoilSensor) +(def-relation grazes Herd Paddock) +(def-relation member_of Livestock Herd) +(def-relation fed_with Livestock Feed) +(def-relation treated_with Livestock VeterinaryTreatment) +(def-relation administered_by VeterinaryTreatment Veterinarian) +(def-relation harvested_from Harvest Field) +(def-relation yields Harvest HarvestLot) +(def-relation advised_by Field Agronomist) +(def-relation threatens Pest Crop) +(def-relation affects CropDisease Crop) +(def-relation applied_to Fertilizer Field) +(def-relation housed_in Livestock Barn) + +; --- Axioms --- +; 1. Integrity: crops are never livestock +(forall (x) (not (and (Crop x) (Livestock x)))) +; 2. Integrity: weeds are never cultivated crops +(forall (x) (not (and (Crop x) (Weed x)))) +; 3. Integrity: fertilizers and pesticides are distinct agrochemicals +(forall (x) (not (and (Fertilizer x) (Pesticide x)))) +; 4. Integrity: farmers and inspectors are separate parties +(forall (x) (not (and (Farmer x) (Inspector x)))) +; 5. Agronomy: soil pH must lie in the physical range 3 to 10 +(forall (s) (implies (PhSensor s) (and (gte soil_ph 3) (lte soil_ph 10)))) +; 6. Agronomy: soil moisture is a percentage +(forall (s) (implies (MoistureSensor s) (and (gte soil_moisture_percent 0) (lte soil_moisture_percent 100)))) +; 7. Irrigation: below 20 percent soil moisture the field needs irrigation +(forall (s) (implies (and (MoistureSensor s) (lt soil_moisture_percent 20)) (exists (i) (IrrigationSystem i)))) +; 8. Irrigation: reservoir level is a percentage +(forall (r) (implies (Reservoir r) (and (gte tank_level_percent 0) (lte tank_level_percent 100)))) +; 9. Welfare: paddock stocking density is capped at 40 animals +(forall (p) (implies (Paddock p) (lte stocking_density 40))) +; 10. Biosecurity: animals in quarantine are never sold for slaughter +(forall (a) (implies (and (Livestock a) (eq in_quarantine True)) (eq sold_for_slaughter False))) +; 11. Residue safety: antibiotic withdrawal period is at least 7 days +(forall (t) (implies (AntibioticTreatment t) (gte withdrawal_days 7))) +; 12. Residue safety: pesticide must be sprayed at least 14 days before harvest +(forall (s) (implies (and (Spraying s) (eq pesticide_applied True)) (gte days_before_harvest 14))) +; 13. Traceability: every harvest lot carries a traceability lot code +(forall (l) (implies (HarvestLot l) (eq has_traceability_lot True))) diff --git a/examples/domain_agriculture.mmd b/examples/domain_agriculture.mmd new file mode 100644 index 0000000..deec517 --- /dev/null +++ b/examples/domain_agriculture.mmd @@ -0,0 +1,238 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Farm["Farm"] + class Field["Field"] + class ArableField["ArableField"] + class Pasture["Pasture"] + class Orchard["Orchard"] + class Greenhouse["Greenhouse"] + class Paddock["Paddock"] + class Barn["Barn"] + class MilkingParlour["MilkingParlour"] + class GrainSilo["GrainSilo"] + class WaterSource["WaterSource"] + class Borehole["Borehole"] + class Reservoir["Reservoir"] + class Person["Person"] + class Farmer["Farmer"] + class FarmHand["FarmHand"] + class Agronomist["Agronomist"] + class Veterinarian["Veterinarian"] + class Inspector["Inspector"] + class Plant["Plant"] + class Crop["Crop"] + class CerealCrop["CerealCrop"] + class Wheat["Wheat"] + class Maize["Maize"] + class Barley["Barley"] + class LegumeCrop["LegumeCrop"] + class Soybean["Soybean"] + class VegetableCrop["VegetableCrop"] + class Tomato["Tomato"] + class FruitCrop["FruitCrop"] + class Apple["Apple"] + class CoverCrop["CoverCrop"] + class Weed["Weed"] + class Pest["Pest"] + class CropDisease["CropDisease"] + class Animal["Animal"] + class Livestock["Livestock"] + class Cattle["Cattle"] + class DairyCow["DairyCow"] + class BeefCattle["BeefCattle"] + class Sheep["Sheep"] + class Pig["Pig"] + class Poultry["Poultry"] + class Herd["Herd"] + class Flock["Flock"] + class Feed["Feed"] + class VeterinaryTreatment["VeterinaryTreatment"] + class Vaccination["Vaccination"] + class AntibioticTreatment["AntibioticTreatment"] + class Quarantine["Quarantine"] + class IrrigationSystem["IrrigationSystem"] + class DripIrrigation["DripIrrigation"] + class PivotIrrigation["PivotIrrigation"] + class Sprinkler["Sprinkler"] + class Pump["Pump"] + class Valve["Valve"] + class Sensor["Sensor"] + class SoilSensor["SoilSensor"] + class MoistureSensor["MoistureSensor"] + class PhSensor["PhSensor"] + class NitrogenSensor["NitrogenSensor"] + class WeatherStation["WeatherStation"] + class SensorReading["SensorReading"] + class Soil["Soil"] + class Fertilizer["Fertilizer"] + class Pesticide["Pesticide"] + class FarmOperation["FarmOperation"] + class Planting["Planting"] + class Irrigating["Irrigating"] + class Fertilizing["Fertilizing"] + class Spraying["Spraying"] + class Harvesting["Harvesting"] + class Milking["Milking"] + class Grazing["Grazing"] + class Harvest["Harvest"] + class GrainHarvest["GrainHarvest"] + class FruitHarvest["FruitHarvest"] + class HarvestLot["HarvestLot"] + class FieldRecord["FieldRecord"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Object <|-- Agent + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Site <|-- Farm + Site <|-- Field + Field <|-- ArableField + Field <|-- Pasture + Field <|-- Orchard + Field <|-- Greenhouse + Field <|-- Paddock + Site <|-- Barn + Site <|-- MilkingParlour + Site <|-- GrainSilo + Site <|-- WaterSource + WaterSource <|-- Borehole + WaterSource <|-- Reservoir + Agent <|-- Person + Person <|-- Farmer + Person <|-- FarmHand + Person <|-- Agronomist + Person <|-- Veterinarian + Person <|-- Inspector + MaterialEntity <|-- Plant + Plant <|-- Crop + Crop <|-- CerealCrop + CerealCrop <|-- Wheat + CerealCrop <|-- Maize + CerealCrop <|-- Barley + Crop <|-- LegumeCrop + LegumeCrop <|-- Soybean + Crop <|-- VegetableCrop + VegetableCrop <|-- Tomato + Crop <|-- FruitCrop + FruitCrop <|-- Apple + Crop <|-- CoverCrop + Plant <|-- Weed + Object <|-- Pest + Quality <|-- CropDisease + MaterialEntity <|-- Animal + Animal <|-- Livestock + Livestock <|-- Cattle + Cattle <|-- DairyCow + Cattle <|-- BeefCattle + Livestock <|-- Sheep + Livestock <|-- Pig + Livestock <|-- Poultry + Object <|-- Herd + Object <|-- Flock + MaterialEntity <|-- Feed + Process <|-- VeterinaryTreatment + VeterinaryTreatment <|-- Vaccination + VeterinaryTreatment <|-- AntibioticTreatment + Process <|-- Quarantine + Object <|-- IrrigationSystem + IrrigationSystem <|-- DripIrrigation + IrrigationSystem <|-- PivotIrrigation + IrrigationSystem <|-- Sprinkler + Object <|-- Pump + Object <|-- Valve + Object <|-- Sensor + Sensor <|-- SoilSensor + SoilSensor <|-- MoistureSensor + SoilSensor <|-- PhSensor + SoilSensor <|-- NitrogenSensor + Sensor <|-- WeatherStation + InformationContentEntity <|-- SensorReading + MaterialEntity <|-- Soil + MaterialEntity <|-- Fertilizer + MaterialEntity <|-- Pesticide + Process <|-- FarmOperation + FarmOperation <|-- Planting + FarmOperation <|-- Irrigating + FarmOperation <|-- Fertilizing + FarmOperation <|-- Spraying + FarmOperation <|-- Harvesting + FarmOperation <|-- Milking + FarmOperation <|-- Grazing + InformationContentEntity <|-- Harvest + Harvest <|-- GrainHarvest + Harvest <|-- FruitHarvest + InformationContentEntity <|-- HarvestLot + InformationContentEntity <|-- FieldRecord + Field : +Float area_hectares + SoilSensor : +Float soil_ph + MoistureSensor : +Integer soil_moisture_percent + NitrogenSensor : +Integer soil_nitrogen_ppm + Field : +Boolean needs_irrigation + IrrigationSystem : +Boolean irrigation_active + Pump : +Integer flow_rate_lpm + Reservoir : +Integer tank_level_percent + WeatherStation : +Integer air_temperature_c + Crop : +String crop_variety + Crop : +Integer days_to_maturity + Harvest : +Float expected_yield_tonnes + Harvest : +Integer moisture_at_harvest + HarvestLot : +Boolean has_traceability_lot + Herd : +Integer animal_count + Paddock : +Integer stocking_density + Livestock : +String ear_tag + Livestock : +Integer body_weight_kg + AntibioticTreatment : +Integer withdrawal_days + Livestock : +Integer days_since_treatment + Livestock : +Boolean in_quarantine + Livestock : +Boolean sold_for_slaughter + Spraying : +Boolean pesticide_applied + Spraying : +Integer days_before_harvest + Farmer --> Farm : owns + Field --> Farm : part_of + Field --> Crop : planted_with + IrrigationSystem --> Field : irrigates + IrrigationSystem --> WaterSource : supplied_by + IrrigationSystem --> Pump : powered_by + Valve --> IrrigationSystem : controls + SoilSensor --> Field : installed_in + SensorReading --> SoilSensor : measures + Herd --> Paddock : grazes + Livestock --> Herd : member_of + Livestock --> Feed : fed_with + Livestock --> VeterinaryTreatment : treated_with + VeterinaryTreatment --> Veterinarian : administered_by + Harvest --> Field : harvested_from + Harvest --> HarvestLot : yields + Field --> Agronomist : advised_by + Pest --> Crop : threatens + CropDisease --> Crop : affects + Fertilizer --> Field : applied_to + Livestock --> Barn : housed_in + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall x (not Crop(x) and Livestock(x)) +%% forall x (not Crop(x) and Weed(x)) +%% forall x (not Fertilizer(x) and Pesticide(x)) +%% forall x (not Farmer(x) and Inspector(x)) +%% forall s (MoistureSensor(s) and lt(soil_moisture_percent, 20) implies exists i (IrrigationSystem(i))) +%% forall a (Livestock(a) and in_quarantine = True implies sold_for_slaughter = False) +%% forall s (Spraying(s) and pesticide_applied = True implies gte(days_before_harvest, 14)) diff --git a/examples/domain_clinical_medicine.cypher b/examples/domain_clinical_medicine.cypher new file mode 100644 index 0000000..ac19539 --- /dev/null +++ b/examples/domain_clinical_medicine.cypher @@ -0,0 +1,291 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Patient'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PediatricPatient'}) +MERGE (p:OntologyClass {name: 'Patient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GeriatricPatient'}) +MERGE (p:OntologyClass {name: 'Patient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PregnantPatient'}) +MERGE (p:OntologyClass {name: 'Patient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Clinician'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Physician'}) +MERGE (p:OntologyClass {name: 'Clinician'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Surgeon'}) +MERGE (p:OntologyClass {name: 'Physician'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Nurse'}) +MERGE (p:OntologyClass {name: 'Clinician'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pharmacist'}) +MERGE (p:OntologyClass {name: 'Clinician'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Therapist'}) +MERGE (p:OntologyClass {name: 'Clinician'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PrescriberRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AttendingRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CareTeam'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Facility'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Hospital'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Clinic'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Ward'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IntensiveCareUnit'}) +MERGE (p:OntologyClass {name: 'Ward'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OperatingTheatre'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pharmacy'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Encounter'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InpatientAdmission'}) +MERGE (p:OntologyClass {name: 'Encounter'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OutpatientVisit'}) +MERGE (p:OntologyClass {name: 'Encounter'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EmergencyVisit'}) +MERGE (p:OntologyClass {name: 'Encounter'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TelehealthVisit'}) +MERGE (p:OntologyClass {name: 'Encounter'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Procedure'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SurgicalProcedure'}) +MERGE (p:OntologyClass {name: 'Procedure'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Administration'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Discharge'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Condition'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Diagnosis'}) +MERGE (p:OntologyClass {name: 'Condition'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChronicCondition'}) +MERGE (p:OntologyClass {name: 'Diagnosis'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AcuteCondition'}) +MERGE (p:OntologyClass {name: 'Diagnosis'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Allergy'}) +MERGE (p:OntologyClass {name: 'Condition'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DrugAllergy'}) +MERGE (p:OntologyClass {name: 'Allergy'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FoodAllergy'}) +MERGE (p:OntologyClass {name: 'Allergy'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Contraindication'}) +MERGE (p:OntologyClass {name: 'Condition'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VitalSign'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Observation'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LabResult'}) +MERGE (p:OntologyClass {name: 'Observation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ImagingResult'}) +MERGE (p:OntologyClass {name: 'Observation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DischargeSummary'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ClinicalNote'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EscalationRecord'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ClinicalOrder'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MedicationOrder'}) +MERGE (p:OntologyClass {name: 'ClinicalOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlledSubstanceOrder'}) +MERGE (p:OntologyClass {name: 'MedicationOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LabOrder'}) +MERGE (p:OntologyClass {name: 'ClinicalOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ImagingOrder'}) +MERGE (p:OntologyClass {name: 'ClinicalOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReferralOrder'}) +MERGE (p:OntologyClass {name: 'ClinicalOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Medication'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Antibiotic'}) +MERGE (p:OntologyClass {name: 'Medication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PenicillinAntibiotic'}) +MERGE (p:OntologyClass {name: 'Antibiotic'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Anticoagulant'}) +MERGE (p:OntologyClass {name: 'Medication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Analgesic'}) +MERGE (p:OntologyClass {name: 'Medication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Opioid'}) +MERGE (p:OntologyClass {name: 'Analgesic'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NSAID'}) +MERGE (p:OntologyClass {name: 'Analgesic'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ACEInhibitor'}) +MERGE (p:OntologyClass {name: 'Medication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ActiveIngredient'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Patient'}) +MERGE (t:OntologyClass {name: 'Clinician'}) +MERGE (s)-[:RELATION {name: 'treated_by'}]->(t); +MERGE (s:OntologyClass {name: 'Clinician'}) +MERGE (t:OntologyClass {name: 'Encounter'}) +MERGE (s)-[:RELATION {name: 'attends'}]->(t); +MERGE (s:OntologyClass {name: 'Patient'}) +MERGE (t:OntologyClass {name: 'Encounter'}) +MERGE (s)-[:RELATION {name: 'subject_of'}]->(t); +MERGE (s:OntologyClass {name: 'Patient'}) +MERGE (t:OntologyClass {name: 'Diagnosis'}) +MERGE (s)-[:RELATION {name: 'diagnosed_with'}]->(t); +MERGE (s:OntologyClass {name: 'Patient'}) +MERGE (t:OntologyClass {name: 'Allergy'}) +MERGE (s)-[:RELATION {name: 'has_allergy'}]->(t); +MERGE (s:OntologyClass {name: 'Clinician'}) +MERGE (t:OntologyClass {name: 'MedicationOrder'}) +MERGE (s)-[:RELATION {name: 'prescribes'}]->(t); +MERGE (s:OntologyClass {name: 'MedicationOrder'}) +MERGE (t:OntologyClass {name: 'Medication'}) +MERGE (s)-[:RELATION {name: 'orders_medication'}]->(t); +MERGE (s:OntologyClass {name: 'MedicationOrder'}) +MERGE (t:OntologyClass {name: 'Patient'}) +MERGE (s)-[:RELATION {name: 'received_by'}]->(t); +MERGE (s:OntologyClass {name: 'Contraindication'}) +MERGE (t:OntologyClass {name: 'Medication'}) +MERGE (s)-[:RELATION {name: 'contraindicates'}]->(t); +MERGE (s:OntologyClass {name: 'Allergy'}) +MERGE (t:OntologyClass {name: 'Medication'}) +MERGE (s)-[:RELATION {name: 'triggers_allergy'}]->(t); +MERGE (s:OntologyClass {name: 'Medication'}) +MERGE (t:OntologyClass {name: 'ActiveIngredient'}) +MERGE (s)-[:RELATION {name: 'has_ingredient'}]->(t); +MERGE (s:OntologyClass {name: 'Clinician'}) +MERGE (t:OntologyClass {name: 'CareTeam'}) +MERGE (s)-[:RELATION {name: 'member_of'}]->(t); +MERGE (s:OntologyClass {name: 'Encounter'}) +MERGE (t:OntologyClass {name: 'Facility'}) +MERGE (s)-[:RELATION {name: 'located_in'}]->(t); +MERGE (s:OntologyClass {name: 'LabResult'}) +MERGE (t:OntologyClass {name: 'LabOrder'}) +MERGE (s)-[:RELATION {name: 'results_from'}]->(t); +// Axiom Validations +// Axiom validation: Patient oxygen_saturation gte 0 +MATCH (n:`Patient`) WHERE NOT (n.`oxygen_saturation` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Patient oxygen_saturation lte 100 +MATCH (n:`Patient`) WHERE NOT (n.`oxygen_saturation` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Patient heart_rate gte 0 +MATCH (n:`Patient`) WHERE NOT (n.`heart_rate` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Patient heart_rate lte 300 +MATCH (n:`Patient`) WHERE NOT (n.`heart_rate` <= 300) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Physician is_licensed_prescriber eq True +MATCH (n:`Physician`) WHERE NOT (n.`is_licensed_prescriber` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: EmergencyVisit triage_level gte 1 +MATCH (n:`EmergencyVisit`) WHERE NOT (n.`triage_level` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: EmergencyVisit triage_level lte 5 +MATCH (n:`EmergencyVisit`) WHERE NOT (n.`triage_level` <= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Discharge has_summary eq True +MATCH (n:`Discharge`) WHERE NOT (n.`has_summary` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: MedicationOrder is_signed eq True +MATCH (n:`MedicationOrder`) WHERE NOT (n.`is_signed` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: ControlledSubstanceOrder dose_mg gt 0 +MATCH (n:`ControlledSubstanceOrder`) WHERE NOT (n.`dose_mg` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: ControlledSubstanceOrder dose_mg lte 200 +MATCH (n:`ControlledSubstanceOrder`) WHERE NOT (n.`dose_mg` <= 200) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall x (not Patient(x) and Clinician(x)) +// forall x (not ClinicalOrder(x) and Observation(x)) +// forall x (not Medication(x) and ActiveIngredient(x)) +// forall p (forall a (forall m (forall o (has_allergy(p, a) and triggers_allergy(a, m) and orders_medication(o, m) implies not received_by(o, p))))) +// forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists e (EscalationRecord(e))) diff --git a/examples/domain_clinical_medicine.d2 b/examples/domain_clinical_medicine.d2 new file mode 100644 index 0000000..9c253a9 --- /dev/null +++ b/examples/domain_clinical_medicine.d2 @@ -0,0 +1,183 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Person": { shape: class } +"Patient": { shape: class } +"PediatricPatient": { shape: class } +"GeriatricPatient": { shape: class } +"PregnantPatient": { shape: class } +"Clinician": { shape: class } +"Physician": { shape: class } +"Surgeon": { shape: class } +"Nurse": { shape: class } +"Pharmacist": { shape: class } +"Therapist": { shape: class } +"PrescriberRole": { shape: class } +"AttendingRole": { shape: class } +"CareTeam": { shape: class } +"Facility": { shape: class } +"Hospital": { shape: class } +"Clinic": { shape: class } +"Ward": { shape: class } +"IntensiveCareUnit": { shape: class } +"OperatingTheatre": { shape: class } +"Pharmacy": { shape: class } +"Encounter": { shape: class } +"InpatientAdmission": { shape: class } +"OutpatientVisit": { shape: class } +"EmergencyVisit": { shape: class } +"TelehealthVisit": { shape: class } +"Procedure": { shape: class } +"SurgicalProcedure": { shape: class } +"Administration": { shape: class } +"Discharge": { shape: class } +"Condition": { shape: class } +"Diagnosis": { shape: class } +"ChronicCondition": { shape: class } +"AcuteCondition": { shape: class } +"Allergy": { shape: class } +"DrugAllergy": { shape: class } +"FoodAllergy": { shape: class } +"Contraindication": { shape: class } +"VitalSign": { shape: class } +"Observation": { shape: class } +"LabResult": { shape: class } +"ImagingResult": { shape: class } +"DischargeSummary": { shape: class } +"ClinicalNote": { shape: class } +"EscalationRecord": { shape: class } +"ClinicalOrder": { shape: class } +"MedicationOrder": { shape: class } +"ControlledSubstanceOrder": { shape: class } +"LabOrder": { shape: class } +"ImagingOrder": { shape: class } +"ReferralOrder": { shape: class } +"Medication": { shape: class } +"Antibiotic": { shape: class } +"PenicillinAntibiotic": { shape: class } +"Anticoagulant": { shape: class } +"Analgesic": { shape: class } +"Opioid": { shape: class } +"NSAID": { shape: class } +"ACEInhibitor": { shape: class } +"ActiveIngredient": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "Object" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Person" -> "Agent" +"Patient" -> "Person" +"PediatricPatient" -> "Patient" +"GeriatricPatient" -> "Patient" +"PregnantPatient" -> "Patient" +"Clinician" -> "Person" +"Physician" -> "Clinician" +"Surgeon" -> "Physician" +"Nurse" -> "Clinician" +"Pharmacist" -> "Clinician" +"Therapist" -> "Clinician" +"PrescriberRole" -> "Role" +"AttendingRole" -> "Role" +"CareTeam" -> "Object" +"Facility" -> "Site" +"Hospital" -> "Facility" +"Clinic" -> "Facility" +"Ward" -> "Facility" +"IntensiveCareUnit" -> "Ward" +"OperatingTheatre" -> "Facility" +"Pharmacy" -> "Facility" +"Encounter" -> "Process" +"InpatientAdmission" -> "Encounter" +"OutpatientVisit" -> "Encounter" +"EmergencyVisit" -> "Encounter" +"TelehealthVisit" -> "Encounter" +"Procedure" -> "Process" +"SurgicalProcedure" -> "Procedure" +"Administration" -> "Process" +"Discharge" -> "Process" +"Condition" -> "Quality" +"Diagnosis" -> "Condition" +"ChronicCondition" -> "Diagnosis" +"AcuteCondition" -> "Diagnosis" +"Allergy" -> "Condition" +"DrugAllergy" -> "Allergy" +"FoodAllergy" -> "Allergy" +"Contraindication" -> "Condition" +"VitalSign" -> "Quality" +"Observation" -> "InformationContentEntity" +"LabResult" -> "Observation" +"ImagingResult" -> "Observation" +"DischargeSummary" -> "InformationContentEntity" +"ClinicalNote" -> "InformationContentEntity" +"EscalationRecord" -> "InformationContentEntity" +"ClinicalOrder" -> "InformationContentEntity" +"MedicationOrder" -> "ClinicalOrder" +"ControlledSubstanceOrder" -> "MedicationOrder" +"LabOrder" -> "ClinicalOrder" +"ImagingOrder" -> "ClinicalOrder" +"ReferralOrder" -> "ClinicalOrder" +"Medication" -> "MaterialEntity" +"Antibiotic" -> "Medication" +"PenicillinAntibiotic" -> "Antibiotic" +"Anticoagulant" -> "Medication" +"Analgesic" -> "Medication" +"Opioid" -> "Analgesic" +"NSAID" -> "Analgesic" +"ACEInhibitor" -> "Medication" +"ActiveIngredient" -> "MaterialEntity" +"Patient"."patient_age": Integer +"Patient"."weight_kg": Float +"Patient"."heart_rate": Integer +"Patient"."systolic_bp": Integer +"Patient"."oxygen_saturation": Integer +"Patient"."body_temperature": Float +"Patient"."medical_record_number": String +"Clinician"."license_number": String +"Clinician"."is_licensed_prescriber": Boolean +"MedicationOrder"."dose_mg": Integer +"Medication"."max_daily_dose_mg": Integer +"ClinicalOrder"."is_signed": Boolean +"InpatientAdmission"."length_of_stay_days": Integer +"Ward"."bed_count": Integer +"EmergencyVisit"."triage_level": Integer +"LabResult"."is_critical": Boolean +"Discharge"."has_summary": Boolean +"Patient" -> "Clinician": treated_by +"Clinician" -> "Encounter": attends +"Patient" -> "Encounter": subject_of +"Patient" -> "Diagnosis": diagnosed_with +"Patient" -> "Allergy": has_allergy +"Clinician" -> "MedicationOrder": prescribes +"MedicationOrder" -> "Medication": orders_medication +"MedicationOrder" -> "Patient": received_by +"Contraindication" -> "Medication": contraindicates +"Allergy" -> "Medication": triggers_allergy +"Medication" -> "ActiveIngredient": has_ingredient +"Clinician" -> "CareTeam": member_of +"Encounter" -> "Facility": located_in +"LabResult" -> "LabOrder": results_from +# WARNING: The following axioms could not be mapped to field constraints: +# forall x (not Patient(x) and Clinician(x)) +# forall x (not ClinicalOrder(x) and Observation(x)) +# forall x (not Medication(x) and ActiveIngredient(x)) +# forall p (forall a (forall m (forall o (has_allergy(p, a) and triggers_allergy(a, m) and orders_medication(o, m) implies not received_by(o, p))))) +# forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists e (EscalationRecord(e))) diff --git a/examples/domain_clinical_medicine.d2.svg b/examples/domain_clinical_medicine.d2.svg new file mode 100644 index 0000000..e34b120 --- /dev/null +++ b/examples/domain_clinical_medicine.d2.svg @@ -0,0 +1,115 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentSiteOccurrentProcessRoleFunctionQualityInformationContentEntityPersonPatient+patient_ageInteger+weight_kgFloat+heart_rateInteger+systolic_bpInteger+oxygen_saturationInteger+body_temperatureFloat+medical_record_numberStringPediatricPatientGeriatricPatientPregnantPatientClinician+license_numberString+is_licensed_prescriberBooleanPhysicianSurgeonNursePharmacistTherapistPrescriberRoleAttendingRoleCareTeamFacilityHospitalClinicWard+bed_countIntegerIntensiveCareUnitOperatingTheatrePharmacyEncounterInpatientAdmission+length_of_stay_daysIntegerOutpatientVisitEmergencyVisit+triage_levelIntegerTelehealthVisitProcedureSurgicalProcedureAdministrationDischarge+has_summaryBooleanConditionDiagnosisChronicConditionAcuteConditionAllergyDrugAllergyFoodAllergyContraindicationVitalSignObservationLabResult+is_criticalBooleanImagingResultDischargeSummaryClinicalNoteEscalationRecordClinicalOrder+is_signedBooleanMedicationOrder+dose_mgIntegerControlledSubstanceOrderLabOrderImagingOrderReferralOrderMedication+max_daily_dose_mgIntegerAntibioticPenicillinAntibioticAnticoagulantAnalgesicOpioidNSAIDACEInhibitorActiveIngredient treated_byattendssubject_ofdiagnosed_withhas_allergyprescribesorders_medicationreceived_bycontraindicatestriggers_allergyhas_ingredientmember_oflocated_inresults_from + + + + + + + + + + + + + + + + diff --git a/examples/domain_clinical_medicine.logic b/examples/domain_clinical_medicine.logic new file mode 100644 index 0000000..cbd5bb0 --- /dev/null +++ b/examples/domain_clinical_medicine.logic @@ -0,0 +1,157 @@ +; ===================================================================== +; Domain: Clinical Medicine +; Models patients, encounters, clinicians, diagnoses, orders, medications, +; allergies and contraindications on a condensed BFO upper level. +; Axioms enforce: patient safety (allergy/contraindication, dose limits, +; vital-sign escalation), integrity (patients and clinicians are disjoint, +; orders and results are distinct kinds of record) and business rules +; (controlled-substance orders need a prescriber licence, discharge needs a +; summary). +; ===================================================================== + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent Object) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- People and Roles --- +(def-concept Person Agent) +(def-concept Patient Person) +(def-concept PediatricPatient Patient) +(def-concept GeriatricPatient Patient) +(def-concept PregnantPatient Patient) +(def-concept Clinician Person) +(def-concept Physician Clinician) +(def-concept Surgeon Physician) +(def-concept Nurse Clinician) +(def-concept Pharmacist Clinician) +(def-concept Therapist Clinician) +(def-concept PrescriberRole Role) +(def-concept AttendingRole Role) +(def-concept CareTeam Object) + +; --- Facilities --- +(def-concept Facility Site) +(def-concept Hospital Facility) +(def-concept Clinic Facility) +(def-concept Ward Facility) +(def-concept IntensiveCareUnit Ward) +(def-concept OperatingTheatre Facility) +(def-concept Pharmacy Facility) + +; --- Encounters --- +(def-concept Encounter Process) +(def-concept InpatientAdmission Encounter) +(def-concept OutpatientVisit Encounter) +(def-concept EmergencyVisit Encounter) +(def-concept TelehealthVisit Encounter) +(def-concept Procedure Process) +(def-concept SurgicalProcedure Procedure) +(def-concept Administration Process) +(def-concept Discharge Process) + +; --- Clinical Findings --- +(def-concept Condition Quality) +(def-concept Diagnosis Condition) +(def-concept ChronicCondition Diagnosis) +(def-concept AcuteCondition Diagnosis) +(def-concept Allergy Condition) +(def-concept DrugAllergy Allergy) +(def-concept FoodAllergy Allergy) +(def-concept Contraindication Condition) +(def-concept VitalSign Quality) +(def-concept Observation InformationContentEntity) +(def-concept LabResult Observation) +(def-concept ImagingResult Observation) +(def-concept DischargeSummary InformationContentEntity) +(def-concept ClinicalNote InformationContentEntity) + +; --- Orders --- +(def-concept ClinicalOrder InformationContentEntity) +(def-concept MedicationOrder ClinicalOrder) +(def-concept ControlledSubstanceOrder MedicationOrder) +(def-concept LabOrder ClinicalOrder) +(def-concept ImagingOrder ClinicalOrder) +(def-concept ReferralOrder ClinicalOrder) + +; --- Medications --- +(def-concept Medication MaterialEntity) +(def-concept Antibiotic Medication) +(def-concept PenicillinAntibiotic Antibiotic) +(def-concept Anticoagulant Medication) +(def-concept Analgesic Medication) +(def-concept Opioid Analgesic) +(def-concept NSAID Analgesic) +(def-concept ACEInhibitor Medication) +(def-concept ActiveIngredient MaterialEntity) + +; --- Properties --- +(def-property patient_age Patient Integer :cardinality 1..1) +(def-property weight_kg Patient Float) +(def-property heart_rate Patient Integer) +(def-property systolic_bp Patient Integer) +(def-property oxygen_saturation Patient Integer) +(def-property body_temperature Patient Float) +(def-property medical_record_number Patient String :cardinality 1..1) +(def-property license_number Clinician String) +(def-property is_licensed_prescriber Clinician Boolean) +(def-property dose_mg MedicationOrder Integer) +(def-property max_daily_dose_mg Medication Integer) +(def-property is_signed ClinicalOrder Boolean) +(def-property length_of_stay_days InpatientAdmission Integer) +(def-property bed_count Ward Integer) +(def-property triage_level EmergencyVisit Integer) +(def-property is_critical LabResult Boolean) +(def-property has_summary Discharge Boolean) + +; --- Relations --- +(def-relation treated_by Patient Clinician :cardinality 1..*) +(def-relation attends Clinician Encounter) +(def-relation subject_of Patient Encounter :cardinality 0..*) +(def-relation diagnosed_with Patient Diagnosis :cardinality 0..*) +(def-relation has_allergy Patient Allergy :cardinality 0..*) +(def-relation prescribes Clinician MedicationOrder) +(def-relation orders_medication MedicationOrder Medication) +(def-relation received_by MedicationOrder Patient) +(def-relation contraindicates Contraindication Medication) +(def-relation triggers_allergy Allergy Medication) +(def-relation has_ingredient Medication ActiveIngredient :cardinality 1..*) +(def-relation member_of Clinician CareTeam) +(def-relation located_in Encounter Facility) +(def-relation results_from LabResult LabOrder) + +; --- Axioms --- +; 1. Integrity: a patient is never a clinician record (roles are modelled separately) +(forall (x) (not (and (Patient x) (Clinician x)))) +; 2. Integrity: orders and observations are distinct kinds of record +(forall (x) (not (and (ClinicalOrder x) (Observation x)))) +; 3. Integrity: medications and active ingredients are distinct materials +(forall (x) (not (and (Medication x) (ActiveIngredient x)))) +; 4. Safety: oxygen saturation is a percentage +(forall (p) (implies (Patient p) (and (gte oxygen_saturation 0) (lte oxygen_saturation 100)))) +; 5. Safety: recorded heart rate must be physiologically possible +(forall (p) (implies (Patient p) (and (gte heart_rate 0) (lte heart_rate 300)))) +; 6. Safety: a single opioid order may not exceed 200 mg +(forall (o) (implies (ControlledSubstanceOrder o) (and (gt dose_mg 0) (lte dose_mg 200)))) +; 7. Safety: an allergy to a drug means that drug must never be ordered for the patient +(forall (p a m) (implies (and (has_allergy p a) (triggers_allergy a m)) (not (exists (o) (and (MedicationOrder o) (orders_medication o m) (received_by o p)))))) +; 8. Safety: severe hypoxia requires an escalation record +(forall (p) (implies (and (Patient p) (lt oxygen_saturation 90)) (exists (n) (ClinicalNote n)))) +; 9. Business: orders must be signed to be actioned +(forall (o) (implies (MedicationOrder o) (eq is_signed True))) +; 10. Business: only licensed clinicians prescribe +(forall (c o) (implies (prescribes c o) (eq is_licensed_prescriber True))) +; 11. Business: discharge requires a discharge summary +(forall (d) (implies (Discharge d) (eq has_summary True))) +; 12. Business: triage level runs from 1 (resuscitation) to 5 (non-urgent) +(forall (e) (implies (EmergencyVisit e) (and (gte triage_level 1) (lte triage_level 5)))) diff --git a/examples/domain_clinical_medicine.mmd b/examples/domain_clinical_medicine.mmd new file mode 100644 index 0000000..1b2eca8 --- /dev/null +++ b/examples/domain_clinical_medicine.mmd @@ -0,0 +1,184 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Person["Person"] + class Patient["Patient"] + class PediatricPatient["PediatricPatient"] + class GeriatricPatient["GeriatricPatient"] + class PregnantPatient["PregnantPatient"] + class Clinician["Clinician"] + class Physician["Physician"] + class Surgeon["Surgeon"] + class Nurse["Nurse"] + class Pharmacist["Pharmacist"] + class Therapist["Therapist"] + class PrescriberRole["PrescriberRole"] + class AttendingRole["AttendingRole"] + class CareTeam["CareTeam"] + class Facility["Facility"] + class Hospital["Hospital"] + class Clinic["Clinic"] + class Ward["Ward"] + class IntensiveCareUnit["IntensiveCareUnit"] + class OperatingTheatre["OperatingTheatre"] + class Pharmacy["Pharmacy"] + class Encounter["Encounter"] + class InpatientAdmission["InpatientAdmission"] + class OutpatientVisit["OutpatientVisit"] + class EmergencyVisit["EmergencyVisit"] + class TelehealthVisit["TelehealthVisit"] + class Procedure["Procedure"] + class SurgicalProcedure["SurgicalProcedure"] + class Administration["Administration"] + class Discharge["Discharge"] + class Condition["Condition"] + class Diagnosis["Diagnosis"] + class ChronicCondition["ChronicCondition"] + class AcuteCondition["AcuteCondition"] + class Allergy["Allergy"] + class DrugAllergy["DrugAllergy"] + class FoodAllergy["FoodAllergy"] + class Contraindication["Contraindication"] + class VitalSign["VitalSign"] + class Observation["Observation"] + class LabResult["LabResult"] + class ImagingResult["ImagingResult"] + class DischargeSummary["DischargeSummary"] + class ClinicalNote["ClinicalNote"] + class EscalationRecord["EscalationRecord"] + class ClinicalOrder["ClinicalOrder"] + class MedicationOrder["MedicationOrder"] + class ControlledSubstanceOrder["ControlledSubstanceOrder"] + class LabOrder["LabOrder"] + class ImagingOrder["ImagingOrder"] + class ReferralOrder["ReferralOrder"] + class Medication["Medication"] + class Antibiotic["Antibiotic"] + class PenicillinAntibiotic["PenicillinAntibiotic"] + class Anticoagulant["Anticoagulant"] + class Analgesic["Analgesic"] + class Opioid["Opioid"] + class NSAID["NSAID"] + class ACEInhibitor["ACEInhibitor"] + class ActiveIngredient["ActiveIngredient"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Object <|-- Agent + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Agent <|-- Person + Person <|-- Patient + Patient <|-- PediatricPatient + Patient <|-- GeriatricPatient + Patient <|-- PregnantPatient + Person <|-- Clinician + Clinician <|-- Physician + Physician <|-- Surgeon + Clinician <|-- Nurse + Clinician <|-- Pharmacist + Clinician <|-- Therapist + Role <|-- PrescriberRole + Role <|-- AttendingRole + Object <|-- CareTeam + Site <|-- Facility + Facility <|-- Hospital + Facility <|-- Clinic + Facility <|-- Ward + Ward <|-- IntensiveCareUnit + Facility <|-- OperatingTheatre + Facility <|-- Pharmacy + Process <|-- Encounter + Encounter <|-- InpatientAdmission + Encounter <|-- OutpatientVisit + Encounter <|-- EmergencyVisit + Encounter <|-- TelehealthVisit + Process <|-- Procedure + Procedure <|-- SurgicalProcedure + Process <|-- Administration + Process <|-- Discharge + Quality <|-- Condition + Condition <|-- Diagnosis + Diagnosis <|-- ChronicCondition + Diagnosis <|-- AcuteCondition + Condition <|-- Allergy + Allergy <|-- DrugAllergy + Allergy <|-- FoodAllergy + Condition <|-- Contraindication + Quality <|-- VitalSign + InformationContentEntity <|-- Observation + Observation <|-- LabResult + Observation <|-- ImagingResult + InformationContentEntity <|-- DischargeSummary + InformationContentEntity <|-- ClinicalNote + InformationContentEntity <|-- EscalationRecord + InformationContentEntity <|-- ClinicalOrder + ClinicalOrder <|-- MedicationOrder + MedicationOrder <|-- ControlledSubstanceOrder + ClinicalOrder <|-- LabOrder + ClinicalOrder <|-- ImagingOrder + ClinicalOrder <|-- ReferralOrder + MaterialEntity <|-- Medication + Medication <|-- Antibiotic + Antibiotic <|-- PenicillinAntibiotic + Medication <|-- Anticoagulant + Medication <|-- Analgesic + Analgesic <|-- Opioid + Analgesic <|-- NSAID + Medication <|-- ACEInhibitor + MaterialEntity <|-- ActiveIngredient + Patient : +Integer patient_age + Patient : +Float weight_kg + Patient : +Integer heart_rate + Patient : +Integer systolic_bp + Patient : +Integer oxygen_saturation + Patient : +Float body_temperature + Patient : +String medical_record_number + Clinician : +String license_number + Clinician : +Boolean is_licensed_prescriber + MedicationOrder : +Integer dose_mg + Medication : +Integer max_daily_dose_mg + ClinicalOrder : +Boolean is_signed + InpatientAdmission : +Integer length_of_stay_days + Ward : +Integer bed_count + EmergencyVisit : +Integer triage_level + LabResult : +Boolean is_critical + Discharge : +Boolean has_summary + Patient --> Clinician : treated_by + Clinician --> Encounter : attends + Patient --> Encounter : subject_of + Patient --> Diagnosis : diagnosed_with + Patient --> Allergy : has_allergy + Clinician --> MedicationOrder : prescribes + MedicationOrder --> Medication : orders_medication + MedicationOrder --> Patient : received_by + Contraindication --> Medication : contraindicates + Allergy --> Medication : triggers_allergy + Medication --> ActiveIngredient : has_ingredient + Clinician --> CareTeam : member_of + Encounter --> Facility : located_in + LabResult --> LabOrder : results_from + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall x (not Patient(x) and Clinician(x)) +%% forall x (not ClinicalOrder(x) and Observation(x)) +%% forall x (not Medication(x) and ActiveIngredient(x)) +%% forall p (forall a (forall m (forall o (has_allergy(p, a) and triggers_allergy(a, m) and orders_medication(o, m) implies not received_by(o, p))))) +%% forall p (Patient(p) and lt(oxygen_saturation, 90) implies exists e (EscalationRecord(e))) diff --git a/examples/domain_customer_service.cypher b/examples/domain_customer_service.cypher new file mode 100644 index 0000000..6c88ae0 --- /dev/null +++ b/examples/domain_customer_service.cypher @@ -0,0 +1,292 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Customer'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EnterpriseCustomer'}) +MERGE (p:OntologyClass {name: 'Customer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConsumerCustomer'}) +MERGE (p:OntologyClass {name: 'Customer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SupportStaff'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SupportAgent'}) +MERGE (p:OntologyClass {name: 'SupportStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SeniorAgent'}) +MERGE (p:OntologyClass {name: 'SupportAgent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TeamLead'}) +MERGE (p:OntologyClass {name: 'SupportStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'KnowledgeAuthor'}) +MERGE (p:OntologyClass {name: 'SupportStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Bot'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SupportTeam'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TierOneTeam'}) +MERGE (p:OntologyClass {name: 'SupportTeam'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TierTwoTeam'}) +MERGE (p:OntologyClass {name: 'SupportTeam'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EngineeringTeam'}) +MERGE (p:OntologyClass {name: 'SupportTeam'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Ticket'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Incident'}) +MERGE (p:OntologyClass {name: 'Ticket'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ServiceRequest'}) +MERGE (p:OntologyClass {name: 'Ticket'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Question'}) +MERGE (p:OntologyClass {name: 'Ticket'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Complaint'}) +MERGE (p:OntologyClass {name: 'Ticket'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Problem'}) +MERGE (p:OntologyClass {name: 'Ticket'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TicketComment'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InternalNote'}) +MERGE (p:OntologyClass {name: 'TicketComment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PublicReply'}) +MERGE (p:OntologyClass {name: 'TicketComment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Resolution'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Attachment'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SatisfactionSurvey'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Priority'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CriticalPriority'}) +MERGE (p:OntologyClass {name: 'Priority'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HighPriority'}) +MERGE (p:OntologyClass {name: 'Priority'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NormalPriority'}) +MERGE (p:OntologyClass {name: 'Priority'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LowPriority'}) +MERGE (p:OntologyClass {name: 'Priority'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TicketStatus'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OpenStatus'}) +MERGE (p:OntologyClass {name: 'TicketStatus'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PendingStatus'}) +MERGE (p:OntologyClass {name: 'TicketStatus'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SolvedStatus'}) +MERGE (p:OntologyClass {name: 'TicketStatus'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ClosedStatus'}) +MERGE (p:OntologyClass {name: 'TicketStatus'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Channel'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EmailChannel'}) +MERGE (p:OntologyClass {name: 'Channel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PhoneChannel'}) +MERGE (p:OntologyClass {name: 'Channel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChatChannel'}) +MERGE (p:OntologyClass {name: 'Channel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SocialChannel'}) +MERGE (p:OntologyClass {name: 'Channel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PortalChannel'}) +MERGE (p:OntologyClass {name: 'Channel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Queue'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GeneralQueue'}) +MERGE (p:OntologyClass {name: 'Queue'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BillingQueue'}) +MERGE (p:OntologyClass {name: 'Queue'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TechnicalQueue'}) +MERGE (p:OntologyClass {name: 'Queue'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PriorityQueue'}) +MERGE (p:OntologyClass {name: 'Queue'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PremiumSLA'}) +MERGE (p:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StandardSLA'}) +MERGE (p:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SLABreach'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Escalation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ManagerEscalation'}) +MERGE (p:OntologyClass {name: 'Escalation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EngineeringEscalation'}) +MERGE (p:OntologyClass {name: 'Escalation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Assignment'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Handover'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'KnowledgeArticle'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FAQArticle'}) +MERGE (p:OntologyClass {name: 'KnowledgeArticle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TroubleshootingGuide'}) +MERGE (p:OntologyClass {name: 'KnowledgeArticle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InternalRunbook'}) +MERGE (p:OntologyClass {name: 'KnowledgeArticle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ArticleVersion'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MacroTemplate'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'Customer'}) +MERGE (s)-[:RELATION {name: 'raised_by'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'Channel'}) +MERGE (s)-[:RELATION {name: 'received_via'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'SupportAgent'}) +MERGE (s)-[:RELATION {name: 'assigned_to'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'Queue'}) +MERGE (s)-[:RELATION {name: 'held_in'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (s)-[:RELATION {name: 'governed_by'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'Priority'}) +MERGE (s)-[:RELATION {name: 'has_priority'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'TicketStatus'}) +MERGE (s)-[:RELATION {name: 'has_status'}]->(t); +MERGE (s:OntologyClass {name: 'Escalation'}) +MERGE (t:OntologyClass {name: 'Ticket'}) +MERGE (s)-[:RELATION {name: 'escalates'}]->(t); +MERGE (s:OntologyClass {name: 'Escalation'}) +MERGE (t:OntologyClass {name: 'SupportTeam'}) +MERGE (s)-[:RELATION {name: 'escalated_to'}]->(t); +MERGE (s:OntologyClass {name: 'Ticket'}) +MERGE (t:OntologyClass {name: 'Resolution'}) +MERGE (s)-[:RELATION {name: 'resolved_with'}]->(t); +MERGE (s:OntologyClass {name: 'Resolution'}) +MERGE (t:OntologyClass {name: 'KnowledgeArticle'}) +MERGE (s)-[:RELATION {name: 'cites'}]->(t); +MERGE (s:OntologyClass {name: 'TicketComment'}) +MERGE (t:OntologyClass {name: 'Ticket'}) +MERGE (s)-[:RELATION {name: 'commented_on'}]->(t); +MERGE (s:OntologyClass {name: 'SupportAgent'}) +MERGE (t:OntologyClass {name: 'SupportTeam'}) +MERGE (s)-[:RELATION {name: 'member_of'}]->(t); +MERGE (s:OntologyClass {name: 'SupportTeam'}) +MERGE (t:OntologyClass {name: 'Queue'}) +MERGE (s)-[:RELATION {name: 'staffs'}]->(t); +MERGE (s:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (t:OntologyClass {name: 'Customer'}) +MERGE (s)-[:RELATION {name: 'covers_customer'}]->(t); +MERGE (s:OntologyClass {name: 'SatisfactionSurvey'}) +MERGE (t:OntologyClass {name: 'Ticket'}) +MERGE (s)-[:RELATION {name: 'rates'}]->(t); +MERGE (s:OntologyClass {name: 'KnowledgeArticle'}) +MERGE (t:OntologyClass {name: 'KnowledgeAuthor'}) +MERGE (s)-[:RELATION {name: 'authored_by'}]->(t); +// Axiom Validations +// Axiom validation: SupportAgent max_concurrent_chats lte 5 +MATCH (n:`SupportAgent`) WHERE NOT (n.`max_concurrent_chats` <= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SatisfactionSurvey csat_score gte 1 +MATCH (n:`SatisfactionSurvey`) WHERE NOT (n.`csat_score` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SatisfactionSurvey csat_score lte 5 +MATCH (n:`SatisfactionSurvey`) WHERE NOT (n.`csat_score` <= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: PremiumSLA response_target_minutes lte 60 +MATCH (n:`PremiumSLA`) WHERE NOT (n.`response_target_minutes` <= 60) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: StandardSLA response_target_minutes lte 1440 +MATCH (n:`StandardSLA`) WHERE NOT (n.`response_target_minutes` <= 1440) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: InternalRunbook is_internal_only eq True +MATCH (n:`InternalRunbook`) WHERE NOT (n.`is_internal_only` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall x (not Customer(x) and SupportStaff(x)) +// forall x (not Bot(x) and SupportStaff(x)) +// forall x (not Ticket(x) and KnowledgeArticle(x)) +// forall x (not CriticalPriority(x) and LowPriority(x)) +// forall x (not OpenStatus(x) and ClosedStatus(x)) +// forall t (Ticket(t) and is_breached = True implies is_escalated = True) +// forall t (Ticket(t) and gt(reopen_count, 3) implies is_escalated = True) diff --git a/examples/domain_customer_service.d2 b/examples/domain_customer_service.d2 new file mode 100644 index 0000000..8717f2b --- /dev/null +++ b/examples/domain_customer_service.d2 @@ -0,0 +1,187 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Person": { shape: class } +"Customer": { shape: class } +"EnterpriseCustomer": { shape: class } +"ConsumerCustomer": { shape: class } +"SupportStaff": { shape: class } +"SupportAgent": { shape: class } +"SeniorAgent": { shape: class } +"TeamLead": { shape: class } +"KnowledgeAuthor": { shape: class } +"Bot": { shape: class } +"SupportTeam": { shape: class } +"TierOneTeam": { shape: class } +"TierTwoTeam": { shape: class } +"EngineeringTeam": { shape: class } +"Ticket": { shape: class } +"Incident": { shape: class } +"ServiceRequest": { shape: class } +"Question": { shape: class } +"Complaint": { shape: class } +"Problem": { shape: class } +"TicketComment": { shape: class } +"InternalNote": { shape: class } +"PublicReply": { shape: class } +"Resolution": { shape: class } +"Attachment": { shape: class } +"SatisfactionSurvey": { shape: class } +"Priority": { shape: class } +"CriticalPriority": { shape: class } +"HighPriority": { shape: class } +"NormalPriority": { shape: class } +"LowPriority": { shape: class } +"TicketStatus": { shape: class } +"OpenStatus": { shape: class } +"PendingStatus": { shape: class } +"SolvedStatus": { shape: class } +"ClosedStatus": { shape: class } +"Channel": { shape: class } +"EmailChannel": { shape: class } +"PhoneChannel": { shape: class } +"ChatChannel": { shape: class } +"SocialChannel": { shape: class } +"PortalChannel": { shape: class } +"Queue": { shape: class } +"GeneralQueue": { shape: class } +"BillingQueue": { shape: class } +"TechnicalQueue": { shape: class } +"PriorityQueue": { shape: class } +"ServiceLevelAgreement": { shape: class } +"PremiumSLA": { shape: class } +"StandardSLA": { shape: class } +"SLABreach": { shape: class } +"Escalation": { shape: class } +"ManagerEscalation": { shape: class } +"EngineeringEscalation": { shape: class } +"Assignment": { shape: class } +"Handover": { shape: class } +"KnowledgeArticle": { shape: class } +"FAQArticle": { shape: class } +"TroubleshootingGuide": { shape: class } +"InternalRunbook": { shape: class } +"ArticleVersion": { shape: class } +"MacroTemplate": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "Object" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Person" -> "Agent" +"Customer" -> "Person" +"EnterpriseCustomer" -> "Customer" +"ConsumerCustomer" -> "Customer" +"SupportStaff" -> "Person" +"SupportAgent" -> "SupportStaff" +"SeniorAgent" -> "SupportAgent" +"TeamLead" -> "SupportStaff" +"KnowledgeAuthor" -> "SupportStaff" +"Bot" -> "Agent" +"SupportTeam" -> "Object" +"TierOneTeam" -> "SupportTeam" +"TierTwoTeam" -> "SupportTeam" +"EngineeringTeam" -> "SupportTeam" +"Ticket" -> "InformationContentEntity" +"Incident" -> "Ticket" +"ServiceRequest" -> "Ticket" +"Question" -> "Ticket" +"Complaint" -> "Ticket" +"Problem" -> "Ticket" +"TicketComment" -> "InformationContentEntity" +"InternalNote" -> "TicketComment" +"PublicReply" -> "TicketComment" +"Resolution" -> "InformationContentEntity" +"Attachment" -> "InformationContentEntity" +"SatisfactionSurvey" -> "InformationContentEntity" +"Priority" -> "Quality" +"CriticalPriority" -> "Priority" +"HighPriority" -> "Priority" +"NormalPriority" -> "Priority" +"LowPriority" -> "Priority" +"TicketStatus" -> "Quality" +"OpenStatus" -> "TicketStatus" +"PendingStatus" -> "TicketStatus" +"SolvedStatus" -> "TicketStatus" +"ClosedStatus" -> "TicketStatus" +"Channel" -> "Object" +"EmailChannel" -> "Channel" +"PhoneChannel" -> "Channel" +"ChatChannel" -> "Channel" +"SocialChannel" -> "Channel" +"PortalChannel" -> "Channel" +"Queue" -> "Object" +"GeneralQueue" -> "Queue" +"BillingQueue" -> "Queue" +"TechnicalQueue" -> "Queue" +"PriorityQueue" -> "Queue" +"ServiceLevelAgreement" -> "InformationContentEntity" +"PremiumSLA" -> "ServiceLevelAgreement" +"StandardSLA" -> "ServiceLevelAgreement" +"SLABreach" -> "Process" +"Escalation" -> "Process" +"ManagerEscalation" -> "Escalation" +"EngineeringEscalation" -> "Escalation" +"Assignment" -> "Process" +"Handover" -> "Process" +"KnowledgeArticle" -> "InformationContentEntity" +"FAQArticle" -> "KnowledgeArticle" +"TroubleshootingGuide" -> "KnowledgeArticle" +"InternalRunbook" -> "KnowledgeArticle" +"ArticleVersion" -> "InformationContentEntity" +"MacroTemplate" -> "InformationContentEntity" +"Ticket"."ticket_id": String +"Ticket"."first_response_minutes": Integer +"Ticket"."resolution_minutes": Integer +"Ticket"."reopen_count": Integer +"Ticket"."is_breached": Boolean +"Ticket"."is_escalated": Boolean +"Ticket"."has_resolution": Boolean +"SatisfactionSurvey"."csat_score": Integer +"ServiceLevelAgreement"."response_target_minutes": Integer +"ServiceLevelAgreement"."resolution_target_minutes": Integer +"SupportAgent"."open_ticket_count": Integer +"SupportAgent"."max_concurrent_chats": Integer +"Queue"."queue_depth": Integer +"KnowledgeArticle"."is_published": Boolean +"KnowledgeArticle"."helpful_votes": Integer +"KnowledgeArticle"."is_internal_only": Boolean +"Ticket" -> "Customer": raised_by +"Ticket" -> "Channel": received_via +"Ticket" -> "SupportAgent": assigned_to +"Ticket" -> "Queue": held_in +"Ticket" -> "ServiceLevelAgreement": governed_by +"Ticket" -> "Priority": has_priority +"Ticket" -> "TicketStatus": has_status +"Escalation" -> "Ticket": escalates +"Escalation" -> "SupportTeam": escalated_to +"Ticket" -> "Resolution": resolved_with +"Resolution" -> "KnowledgeArticle": cites +"TicketComment" -> "Ticket": commented_on +"SupportAgent" -> "SupportTeam": member_of +"SupportTeam" -> "Queue": staffs +"ServiceLevelAgreement" -> "Customer": covers_customer +"SatisfactionSurvey" -> "Ticket": rates +"KnowledgeArticle" -> "KnowledgeAuthor": authored_by +# WARNING: The following axioms could not be mapped to field constraints: +# forall x (not Customer(x) and SupportStaff(x)) +# forall x (not Bot(x) and SupportStaff(x)) +# forall x (not Ticket(x) and KnowledgeArticle(x)) +# forall x (not CriticalPriority(x) and LowPriority(x)) +# forall x (not OpenStatus(x) and ClosedStatus(x)) +# forall t (Ticket(t) and is_breached = True implies is_escalated = True) +# forall t (Ticket(t) and gt(reopen_count, 3) implies is_escalated = True) diff --git a/examples/domain_customer_service.d2.svg b/examples/domain_customer_service.d2.svg new file mode 100644 index 0000000..066428a --- /dev/null +++ b/examples/domain_customer_service.d2.svg @@ -0,0 +1,118 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentOccurrentProcessRoleQualityInformationContentEntityPersonCustomerEnterpriseCustomerConsumerCustomerSupportStaffSupportAgent+open_ticket_countInteger+max_concurrent_chatsIntegerSeniorAgentTeamLeadKnowledgeAuthorBotSupportTeamTierOneTeamTierTwoTeamEngineeringTeamTicket+ticket_idString+first_response_minutesInteger+resolution_minutesInteger+reopen_countInteger+is_breachedBoolean+is_escalatedBoolean+has_resolutionBooleanIncidentServiceRequestQuestionComplaintProblemTicketCommentInternalNotePublicReplyResolutionAttachmentSatisfactionSurvey+csat_scoreIntegerPriorityCriticalPriorityHighPriorityNormalPriorityLowPriorityTicketStatusOpenStatusPendingStatusSolvedStatusClosedStatusChannelEmailChannelPhoneChannelChatChannelSocialChannelPortalChannelQueue+queue_depthIntegerGeneralQueueBillingQueueTechnicalQueuePriorityQueueServiceLevelAgreement+response_target_minutesInteger+resolution_target_minutesIntegerPremiumSLAStandardSLASLABreachEscalationManagerEscalationEngineeringEscalationAssignmentHandoverKnowledgeArticle+is_publishedBoolean+helpful_votesInteger+is_internal_onlyBooleanFAQArticleTroubleshootingGuideInternalRunbookArticleVersionMacroTemplate raised_byreceived_viaassigned_toheld_ingoverned_byhas_priorityhas_statusescalatesescalated_toresolved_withcitescommented_onmember_ofstaffscovers_customerratesauthored_by + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_customer_service.logic b/examples/domain_customer_service.logic new file mode 100644 index 0000000..e220cbc --- /dev/null +++ b/examples/domain_customer_service.logic @@ -0,0 +1,159 @@ +; ===================================================================== +; Domain: Customer Service +; Models support tickets, contact channels, agents, queues, SLAs, +; escalations and knowledge articles on a condensed BFO upper level. +; Axioms enforce: SLA integrity (response before resolution targets, +; priority-driven targets), escalation rules (breached or critical tickets +; escalate), disjointness of customers and agents, and business rules +; (closed tickets need a resolution, satisfaction scores are 1-5). +; ===================================================================== + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent Object) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- People and Organisations --- +(def-concept Person Agent) +(def-concept Customer Person) +(def-concept EnterpriseCustomer Customer) +(def-concept ConsumerCustomer Customer) +(def-concept SupportStaff Person) +(def-concept SupportAgent SupportStaff) +(def-concept SeniorAgent SupportAgent) +(def-concept TeamLead SupportStaff) +(def-concept KnowledgeAuthor SupportStaff) +(def-concept Bot Agent) +(def-concept SupportTeam Object) +(def-concept TierOneTeam SupportTeam) +(def-concept TierTwoTeam SupportTeam) +(def-concept EngineeringTeam SupportTeam) + +; --- Tickets --- +(def-concept Ticket InformationContentEntity) +(def-concept Incident Ticket) +(def-concept ServiceRequest Ticket) +(def-concept Question Ticket) +(def-concept Complaint Ticket) +(def-concept Problem Ticket) +(def-concept TicketComment InformationContentEntity) +(def-concept InternalNote TicketComment) +(def-concept PublicReply TicketComment) +(def-concept Resolution InformationContentEntity) +(def-concept Attachment InformationContentEntity) +(def-concept SatisfactionSurvey InformationContentEntity) + +; --- Priority and Status --- +(def-concept Priority Quality) +(def-concept CriticalPriority Priority) +(def-concept HighPriority Priority) +(def-concept NormalPriority Priority) +(def-concept LowPriority Priority) +(def-concept TicketStatus Quality) +(def-concept OpenStatus TicketStatus) +(def-concept PendingStatus TicketStatus) +(def-concept SolvedStatus TicketStatus) +(def-concept ClosedStatus TicketStatus) + +; --- Channels --- +(def-concept Channel Object) +(def-concept EmailChannel Channel) +(def-concept PhoneChannel Channel) +(def-concept ChatChannel Channel) +(def-concept SocialChannel Channel) +(def-concept PortalChannel Channel) + +; --- Queues, SLAs, Escalations --- +(def-concept Queue Object) +(def-concept GeneralQueue Queue) +(def-concept BillingQueue Queue) +(def-concept TechnicalQueue Queue) +(def-concept PriorityQueue Queue) +(def-concept ServiceLevelAgreement InformationContentEntity) +(def-concept PremiumSLA ServiceLevelAgreement) +(def-concept StandardSLA ServiceLevelAgreement) +(def-concept SLABreach Process) +(def-concept Escalation Process) +(def-concept ManagerEscalation Escalation) +(def-concept EngineeringEscalation Escalation) +(def-concept Assignment Process) +(def-concept Handover Process) + +; --- Knowledge --- +(def-concept KnowledgeArticle InformationContentEntity) +(def-concept FAQArticle KnowledgeArticle) +(def-concept TroubleshootingGuide KnowledgeArticle) +(def-concept InternalRunbook KnowledgeArticle) +(def-concept ArticleVersion InformationContentEntity) +(def-concept MacroTemplate InformationContentEntity) + +; --- Properties --- +(def-property ticket_id Ticket String :cardinality 1..1) +(def-property first_response_minutes Ticket Integer) +(def-property resolution_minutes Ticket Integer) +(def-property reopen_count Ticket Integer) +(def-property is_breached Ticket Boolean) +(def-property is_escalated Ticket Boolean) +(def-property has_resolution Ticket Boolean) +(def-property csat_score SatisfactionSurvey Integer) +(def-property response_target_minutes ServiceLevelAgreement Integer) +(def-property resolution_target_minutes ServiceLevelAgreement Integer) +(def-property open_ticket_count SupportAgent Integer) +(def-property max_concurrent_chats SupportAgent Integer) +(def-property queue_depth Queue Integer) +(def-property is_published KnowledgeArticle Boolean) +(def-property helpful_votes KnowledgeArticle Integer) +(def-property is_internal_only KnowledgeArticle Boolean) + +; --- Relations --- +(def-relation raised_by Ticket Customer :cardinality 1..1) +(def-relation received_via Ticket Channel) +(def-relation assigned_to Ticket SupportAgent :cardinality 0..1) +(def-relation held_in Ticket Queue) +(def-relation governed_by Ticket ServiceLevelAgreement) +(def-relation has_priority Ticket Priority :cardinality 1..1) +(def-relation has_status Ticket TicketStatus :cardinality 1..1) +(def-relation escalates Escalation Ticket) +(def-relation escalated_to Escalation SupportTeam) +(def-relation resolved_with Ticket Resolution) +(def-relation cites Resolution KnowledgeArticle :cardinality 0..*) +(def-relation commented_on TicketComment Ticket) +(def-relation member_of SupportAgent SupportTeam) +(def-relation staffs SupportTeam Queue) +(def-relation covers_customer ServiceLevelAgreement Customer) +(def-relation rates SatisfactionSurvey Ticket) +(def-relation authored_by KnowledgeArticle KnowledgeAuthor) + +; --- Axioms --- +; 1. Integrity: customers are never support staff +(forall (x) (not (and (Customer x) (SupportStaff x)))) +; 2. Integrity: bots are not human support staff +(forall (x) (not (and (Bot x) (SupportStaff x)))) +; 3. Integrity: a ticket is not a knowledge article +(forall (x) (not (and (Ticket x) (KnowledgeArticle x)))) +; 4. Integrity: the four priority levels are mutually exclusive +(forall (x) (not (and (CriticalPriority x) (LowPriority x)))) +; 5. Integrity: a ticket cannot be open and closed at once +(forall (x) (not (and (OpenStatus x) (ClosedStatus x)))) +; 6. SLA: customer satisfaction scores run from 1 to 5 +(forall (s) (implies (SatisfactionSurvey s) (and (gte csat_score 1) (lte csat_score 5)))) +; 7. SLA: premium plans must respond within 60 minutes +(forall (s) (implies (PremiumSLA s) (lte response_target_minutes 60))) +; 8. SLA: standard plans respond within a business day (1440 minutes) +(forall (s) (implies (StandardSLA s) (lte response_target_minutes 1440))) +; 9. Escalation: a breached ticket must be flagged as escalated +(forall (t) (implies (and (Ticket t) (eq is_breached True)) (eq is_escalated True))) +; 10. Escalation: more than 3 reopenings force escalation +(forall (t) (implies (and (Ticket t) (gt reopen_count 3)) (eq is_escalated True))) +; 11. Business: an agent never carries more than 5 concurrent chats +(forall (a) (implies (SupportAgent a) (lte max_concurrent_chats 5))) +; 12. Business: internal runbooks are never published to customers +(forall (k) (implies (InternalRunbook k) (eq is_internal_only True))) diff --git a/examples/domain_customer_service.mmd b/examples/domain_customer_service.mmd new file mode 100644 index 0000000..c3ff661 --- /dev/null +++ b/examples/domain_customer_service.mmd @@ -0,0 +1,188 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Person["Person"] + class Customer["Customer"] + class EnterpriseCustomer["EnterpriseCustomer"] + class ConsumerCustomer["ConsumerCustomer"] + class SupportStaff["SupportStaff"] + class SupportAgent["SupportAgent"] + class SeniorAgent["SeniorAgent"] + class TeamLead["TeamLead"] + class KnowledgeAuthor["KnowledgeAuthor"] + class Bot["Bot"] + class SupportTeam["SupportTeam"] + class TierOneTeam["TierOneTeam"] + class TierTwoTeam["TierTwoTeam"] + class EngineeringTeam["EngineeringTeam"] + class Ticket["Ticket"] + class Incident["Incident"] + class ServiceRequest["ServiceRequest"] + class Question["Question"] + class Complaint["Complaint"] + class Problem["Problem"] + class TicketComment["TicketComment"] + class InternalNote["InternalNote"] + class PublicReply["PublicReply"] + class Resolution["Resolution"] + class Attachment["Attachment"] + class SatisfactionSurvey["SatisfactionSurvey"] + class Priority["Priority"] + class CriticalPriority["CriticalPriority"] + class HighPriority["HighPriority"] + class NormalPriority["NormalPriority"] + class LowPriority["LowPriority"] + class TicketStatus["TicketStatus"] + class OpenStatus["OpenStatus"] + class PendingStatus["PendingStatus"] + class SolvedStatus["SolvedStatus"] + class ClosedStatus["ClosedStatus"] + class Channel["Channel"] + class EmailChannel["EmailChannel"] + class PhoneChannel["PhoneChannel"] + class ChatChannel["ChatChannel"] + class SocialChannel["SocialChannel"] + class PortalChannel["PortalChannel"] + class Queue["Queue"] + class GeneralQueue["GeneralQueue"] + class BillingQueue["BillingQueue"] + class TechnicalQueue["TechnicalQueue"] + class PriorityQueue["PriorityQueue"] + class ServiceLevelAgreement["ServiceLevelAgreement"] + class PremiumSLA["PremiumSLA"] + class StandardSLA["StandardSLA"] + class SLABreach["SLABreach"] + class Escalation["Escalation"] + class ManagerEscalation["ManagerEscalation"] + class EngineeringEscalation["EngineeringEscalation"] + class Assignment["Assignment"] + class Handover["Handover"] + class KnowledgeArticle["KnowledgeArticle"] + class FAQArticle["FAQArticle"] + class TroubleshootingGuide["TroubleshootingGuide"] + class InternalRunbook["InternalRunbook"] + class ArticleVersion["ArticleVersion"] + class MacroTemplate["MacroTemplate"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Object <|-- Agent + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Agent <|-- Person + Person <|-- Customer + Customer <|-- EnterpriseCustomer + Customer <|-- ConsumerCustomer + Person <|-- SupportStaff + SupportStaff <|-- SupportAgent + SupportAgent <|-- SeniorAgent + SupportStaff <|-- TeamLead + SupportStaff <|-- KnowledgeAuthor + Agent <|-- Bot + Object <|-- SupportTeam + SupportTeam <|-- TierOneTeam + SupportTeam <|-- TierTwoTeam + SupportTeam <|-- EngineeringTeam + InformationContentEntity <|-- Ticket + Ticket <|-- Incident + Ticket <|-- ServiceRequest + Ticket <|-- Question + Ticket <|-- Complaint + Ticket <|-- Problem + InformationContentEntity <|-- TicketComment + TicketComment <|-- InternalNote + TicketComment <|-- PublicReply + InformationContentEntity <|-- Resolution + InformationContentEntity <|-- Attachment + InformationContentEntity <|-- SatisfactionSurvey + Quality <|-- Priority + Priority <|-- CriticalPriority + Priority <|-- HighPriority + Priority <|-- NormalPriority + Priority <|-- LowPriority + Quality <|-- TicketStatus + TicketStatus <|-- OpenStatus + TicketStatus <|-- PendingStatus + TicketStatus <|-- SolvedStatus + TicketStatus <|-- ClosedStatus + Object <|-- Channel + Channel <|-- EmailChannel + Channel <|-- PhoneChannel + Channel <|-- ChatChannel + Channel <|-- SocialChannel + Channel <|-- PortalChannel + Object <|-- Queue + Queue <|-- GeneralQueue + Queue <|-- BillingQueue + Queue <|-- TechnicalQueue + Queue <|-- PriorityQueue + InformationContentEntity <|-- ServiceLevelAgreement + ServiceLevelAgreement <|-- PremiumSLA + ServiceLevelAgreement <|-- StandardSLA + Process <|-- SLABreach + Process <|-- Escalation + Escalation <|-- ManagerEscalation + Escalation <|-- EngineeringEscalation + Process <|-- Assignment + Process <|-- Handover + InformationContentEntity <|-- KnowledgeArticle + KnowledgeArticle <|-- FAQArticle + KnowledgeArticle <|-- TroubleshootingGuide + KnowledgeArticle <|-- InternalRunbook + InformationContentEntity <|-- ArticleVersion + InformationContentEntity <|-- MacroTemplate + Ticket : +String ticket_id + Ticket : +Integer first_response_minutes + Ticket : +Integer resolution_minutes + Ticket : +Integer reopen_count + Ticket : +Boolean is_breached + Ticket : +Boolean is_escalated + Ticket : +Boolean has_resolution + SatisfactionSurvey : +Integer csat_score + ServiceLevelAgreement : +Integer response_target_minutes + ServiceLevelAgreement : +Integer resolution_target_minutes + SupportAgent : +Integer open_ticket_count + SupportAgent : +Integer max_concurrent_chats + Queue : +Integer queue_depth + KnowledgeArticle : +Boolean is_published + KnowledgeArticle : +Integer helpful_votes + KnowledgeArticle : +Boolean is_internal_only + Ticket --> Customer : raised_by + Ticket --> Channel : received_via + Ticket --> SupportAgent : assigned_to + Ticket --> Queue : held_in + Ticket --> ServiceLevelAgreement : governed_by + Ticket --> Priority : has_priority + Ticket --> TicketStatus : has_status + Escalation --> Ticket : escalates + Escalation --> SupportTeam : escalated_to + Ticket --> Resolution : resolved_with + Resolution --> KnowledgeArticle : cites + TicketComment --> Ticket : commented_on + SupportAgent --> SupportTeam : member_of + SupportTeam --> Queue : staffs + ServiceLevelAgreement --> Customer : covers_customer + SatisfactionSurvey --> Ticket : rates + KnowledgeArticle --> KnowledgeAuthor : authored_by + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall x (not Customer(x) and SupportStaff(x)) +%% forall x (not Bot(x) and SupportStaff(x)) +%% forall x (not Ticket(x) and KnowledgeArticle(x)) +%% forall x (not CriticalPriority(x) and LowPriority(x)) +%% forall x (not OpenStatus(x) and ClosedStatus(x)) +%% forall t (Ticket(t) and is_breached = True implies is_escalated = True) +%% forall t (Ticket(t) and gt(reopen_count, 3) implies is_escalated = True) diff --git a/examples/domain_customer_success.cypher b/examples/domain_customer_success.cypher new file mode 100644 index 0000000..7d581f1 --- /dev/null +++ b/examples/domain_customer_success.cypher @@ -0,0 +1,308 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Organization'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Account'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EnterpriseAccount'}) +MERGE (p:OntologyClass {name: 'Account'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MidMarketAccount'}) +MERGE (p:OntologyClass {name: 'Account'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SmallBusinessAccount'}) +MERGE (p:OntologyClass {name: 'Account'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustomerContact'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ExecutiveSponsor'}) +MERGE (p:OntologyClass {name: 'CustomerContact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Champion'}) +MERGE (p:OntologyClass {name: 'CustomerContact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Administrator'}) +MERGE (p:OntologyClass {name: 'CustomerContact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EndUser'}) +MERGE (p:OntologyClass {name: 'CustomerContact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Detractor'}) +MERGE (p:OntologyClass {name: 'CustomerContact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VendorStaff'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustomerSuccessManager'}) +MERGE (p:OntologyClass {name: 'VendorStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SolutionsEngineer'}) +MERGE (p:OntologyClass {name: 'VendorStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AccountExecutive'}) +MERGE (p:OntologyClass {name: 'VendorStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SupportLiaison'}) +MERGE (p:OntologyClass {name: 'VendorStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SuccessTeam'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LifecycleStage'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProspectStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OnboardingStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AdoptionStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ExpansionStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RenewalStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChurnedStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OnboardingProcess'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Kickoff'}) +MERGE (p:OntologyClass {name: 'OnboardingProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataMigration'}) +MERGE (p:OntologyClass {name: 'OnboardingProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IntegrationSetup'}) +MERGE (p:OntologyClass {name: 'OnboardingProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'UserTraining'}) +MERGE (p:OntologyClass {name: 'OnboardingProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GoLive'}) +MERGE (p:OntologyClass {name: 'OnboardingProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OnboardingPlan'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Milestone'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SuccessPlan'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SuccessGoal'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HealthScore'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HealthyScore'}) +MERGE (p:OntologyClass {name: 'HealthScore'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NeutralScore'}) +MERGE (p:OntologyClass {name: 'HealthScore'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AtRiskScore'}) +MERGE (p:OntologyClass {name: 'HealthScore'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HealthSignal'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'UsageSignal'}) +MERGE (p:OntologyClass {name: 'HealthSignal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SupportSignal'}) +MERGE (p:OntologyClass {name: 'HealthSignal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SentimentSignal'}) +MERGE (p:OntologyClass {name: 'HealthSignal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FinancialSignal'}) +MERGE (p:OntologyClass {name: 'HealthSignal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChurnRisk'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HighChurnRisk'}) +MERGE (p:OntologyClass {name: 'ChurnRisk'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LowChurnRisk'}) +MERGE (p:OntologyClass {name: 'ChurnRisk'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RiskAlert'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SaveCampaign'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Contract'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Subscription'}) +MERGE (p:OntologyClass {name: 'Contract'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Renewal'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AutoRenewal'}) +MERGE (p:OntologyClass {name: 'Renewal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NegotiatedRenewal'}) +MERGE (p:OntologyClass {name: 'Renewal'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Expansion'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Upsell'}) +MERGE (p:OntologyClass {name: 'Expansion'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CrossSell'}) +MERGE (p:OntologyClass {name: 'Expansion'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Churn'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VoluntaryChurn'}) +MERGE (p:OntologyClass {name: 'Churn'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InvoluntaryChurn'}) +MERGE (p:OntologyClass {name: 'Churn'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Invoice'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BusinessReview'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ExecutiveBusinessReview'}) +MERGE (p:OntologyClass {name: 'BusinessReview'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'QuarterlyBusinessReview'}) +MERGE (p:OntologyClass {name: 'BusinessReview'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReviewDeck'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ActionItem'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NPSSurvey'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'CustomerSuccessManager'}) +MERGE (s)-[:RELATION {name: 'managed_by'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'CustomerContact'}) +MERGE (s)-[:RELATION {name: 'has_contact'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'ExecutiveSponsor'}) +MERGE (s)-[:RELATION {name: 'sponsored_by'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'LifecycleStage'}) +MERGE (s)-[:RELATION {name: 'in_stage'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'Contract'}) +MERGE (s)-[:RELATION {name: 'holds_contract'}]->(t); +MERGE (s:OntologyClass {name: 'Renewal'}) +MERGE (t:OntologyClass {name: 'Contract'}) +MERGE (s)-[:RELATION {name: 'renews'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'OnboardingPlan'}) +MERGE (s)-[:RELATION {name: 'onboarded_via'}]->(t); +MERGE (s:OntologyClass {name: 'OnboardingPlan'}) +MERGE (t:OntologyClass {name: 'Milestone'}) +MERGE (s)-[:RELATION {name: 'contains_milestone'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'HealthScore'}) +MERGE (s)-[:RELATION {name: 'scored_as'}]->(t); +MERGE (s:OntologyClass {name: 'HealthScore'}) +MERGE (t:OntologyClass {name: 'HealthSignal'}) +MERGE (s)-[:RELATION {name: 'derived_from'}]->(t); +MERGE (s:OntologyClass {name: 'RiskAlert'}) +MERGE (t:OntologyClass {name: 'Account'}) +MERGE (s)-[:RELATION {name: 'raises'}]->(t); +MERGE (s:OntologyClass {name: 'Account'}) +MERGE (t:OntologyClass {name: 'BusinessReview'}) +MERGE (s)-[:RELATION {name: 'reviewed_in'}]->(t); +MERGE (s:OntologyClass {name: 'BusinessReview'}) +MERGE (t:OntologyClass {name: 'ActionItem'}) +MERGE (s)-[:RELATION {name: 'produces'}]->(t); +MERGE (s:OntologyClass {name: 'SaveCampaign'}) +MERGE (t:OntologyClass {name: 'Account'}) +MERGE (s)-[:RELATION {name: 'targets'}]->(t); +MERGE (s:OntologyClass {name: 'CustomerSuccessManager'}) +MERGE (t:OntologyClass {name: 'SuccessTeam'}) +MERGE (s)-[:RELATION {name: 'member_of'}]->(t); +MERGE (s:OntologyClass {name: 'Expansion'}) +MERGE (t:OntologyClass {name: 'Account'}) +MERGE (s)-[:RELATION {name: 'expands'}]->(t); +// Axiom Validations +// Axiom validation: Account health_score gte 0 +MATCH (n:`Account`) WHERE NOT (n.`health_score` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Account health_score lte 100 +MATCH (n:`Account`) WHERE NOT (n.`health_score` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: EnterpriseAccount has_executive_sponsor eq True +MATCH (n:`EnterpriseAccount`) WHERE NOT (n.`has_executive_sponsor` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: CustomerSuccessManager portfolio_size lte 60 +MATCH (n:`CustomerSuccessManager`) WHERE NOT (n.`portfolio_size` <= 60) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Renewal discount_percent gte 0 +MATCH (n:`Renewal`) WHERE NOT (n.`discount_percent` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Renewal discount_percent lte 30 +MATCH (n:`Renewal`) WHERE NOT (n.`discount_percent` <= 30) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: NPSSurvey nps_score gte 0 +MATCH (n:`NPSSurvey`) WHERE NOT (n.`nps_score` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: NPSSurvey nps_score lte 10 +MATCH (n:`NPSSurvey`) WHERE NOT (n.`nps_score` <= 10) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall x (not CustomerContact(x) and VendorStaff(x)) +// forall x (not EnterpriseAccount(x) and SmallBusinessAccount(x)) +// forall x (not HealthyScore(x) and AtRiskScore(x)) +// forall x (not ChurnedStage(x) and RenewalStage(x)) +// forall x (not VoluntaryChurn(x) and InvoluntaryChurn(x)) +// forall a (Account(a) and lt(health_score, 40) implies is_at_risk = True) +// forall a (Account(a) and is_at_risk = True implies has_success_plan = True) diff --git a/examples/domain_customer_success.d2 b/examples/domain_customer_success.d2 new file mode 100644 index 0000000..99cd555 --- /dev/null +++ b/examples/domain_customer_success.d2 @@ -0,0 +1,195 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Organization": { shape: class } +"Account": { shape: class } +"EnterpriseAccount": { shape: class } +"MidMarketAccount": { shape: class } +"SmallBusinessAccount": { shape: class } +"Person": { shape: class } +"CustomerContact": { shape: class } +"ExecutiveSponsor": { shape: class } +"Champion": { shape: class } +"Administrator": { shape: class } +"EndUser": { shape: class } +"Detractor": { shape: class } +"VendorStaff": { shape: class } +"CustomerSuccessManager": { shape: class } +"SolutionsEngineer": { shape: class } +"AccountExecutive": { shape: class } +"SupportLiaison": { shape: class } +"SuccessTeam": { shape: class } +"LifecycleStage": { shape: class } +"ProspectStage": { shape: class } +"OnboardingStage": { shape: class } +"AdoptionStage": { shape: class } +"ExpansionStage": { shape: class } +"RenewalStage": { shape: class } +"ChurnedStage": { shape: class } +"OnboardingProcess": { shape: class } +"Kickoff": { shape: class } +"DataMigration": { shape: class } +"IntegrationSetup": { shape: class } +"UserTraining": { shape: class } +"GoLive": { shape: class } +"OnboardingPlan": { shape: class } +"Milestone": { shape: class } +"SuccessPlan": { shape: class } +"SuccessGoal": { shape: class } +"HealthScore": { shape: class } +"HealthyScore": { shape: class } +"NeutralScore": { shape: class } +"AtRiskScore": { shape: class } +"HealthSignal": { shape: class } +"UsageSignal": { shape: class } +"SupportSignal": { shape: class } +"SentimentSignal": { shape: class } +"FinancialSignal": { shape: class } +"ChurnRisk": { shape: class } +"HighChurnRisk": { shape: class } +"LowChurnRisk": { shape: class } +"RiskAlert": { shape: class } +"SaveCampaign": { shape: class } +"Contract": { shape: class } +"Subscription": { shape: class } +"Renewal": { shape: class } +"AutoRenewal": { shape: class } +"NegotiatedRenewal": { shape: class } +"Expansion": { shape: class } +"Upsell": { shape: class } +"CrossSell": { shape: class } +"Churn": { shape: class } +"VoluntaryChurn": { shape: class } +"InvoluntaryChurn": { shape: class } +"Invoice": { shape: class } +"BusinessReview": { shape: class } +"ExecutiveBusinessReview": { shape: class } +"QuarterlyBusinessReview": { shape: class } +"ReviewDeck": { shape: class } +"ActionItem": { shape: class } +"NPSSurvey": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "Object" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Organization" -> "Agent" +"Account" -> "Organization" +"EnterpriseAccount" -> "Account" +"MidMarketAccount" -> "Account" +"SmallBusinessAccount" -> "Account" +"Person" -> "Agent" +"CustomerContact" -> "Person" +"ExecutiveSponsor" -> "CustomerContact" +"Champion" -> "CustomerContact" +"Administrator" -> "CustomerContact" +"EndUser" -> "CustomerContact" +"Detractor" -> "CustomerContact" +"VendorStaff" -> "Person" +"CustomerSuccessManager" -> "VendorStaff" +"SolutionsEngineer" -> "VendorStaff" +"AccountExecutive" -> "VendorStaff" +"SupportLiaison" -> "VendorStaff" +"SuccessTeam" -> "Object" +"LifecycleStage" -> "Quality" +"ProspectStage" -> "LifecycleStage" +"OnboardingStage" -> "LifecycleStage" +"AdoptionStage" -> "LifecycleStage" +"ExpansionStage" -> "LifecycleStage" +"RenewalStage" -> "LifecycleStage" +"ChurnedStage" -> "LifecycleStage" +"OnboardingProcess" -> "Process" +"Kickoff" -> "OnboardingProcess" +"DataMigration" -> "OnboardingProcess" +"IntegrationSetup" -> "OnboardingProcess" +"UserTraining" -> "OnboardingProcess" +"GoLive" -> "OnboardingProcess" +"OnboardingPlan" -> "InformationContentEntity" +"Milestone" -> "InformationContentEntity" +"SuccessPlan" -> "InformationContentEntity" +"SuccessGoal" -> "InformationContentEntity" +"HealthScore" -> "Quality" +"HealthyScore" -> "HealthScore" +"NeutralScore" -> "HealthScore" +"AtRiskScore" -> "HealthScore" +"HealthSignal" -> "InformationContentEntity" +"UsageSignal" -> "HealthSignal" +"SupportSignal" -> "HealthSignal" +"SentimentSignal" -> "HealthSignal" +"FinancialSignal" -> "HealthSignal" +"ChurnRisk" -> "Quality" +"HighChurnRisk" -> "ChurnRisk" +"LowChurnRisk" -> "ChurnRisk" +"RiskAlert" -> "InformationContentEntity" +"SaveCampaign" -> "Process" +"Contract" -> "InformationContentEntity" +"Subscription" -> "Contract" +"Renewal" -> "Process" +"AutoRenewal" -> "Renewal" +"NegotiatedRenewal" -> "Renewal" +"Expansion" -> "Process" +"Upsell" -> "Expansion" +"CrossSell" -> "Expansion" +"Churn" -> "Process" +"VoluntaryChurn" -> "Churn" +"InvoluntaryChurn" -> "Churn" +"Invoice" -> "InformationContentEntity" +"BusinessReview" -> "Process" +"ExecutiveBusinessReview" -> "BusinessReview" +"QuarterlyBusinessReview" -> "BusinessReview" +"ReviewDeck" -> "InformationContentEntity" +"ActionItem" -> "InformationContentEntity" +"NPSSurvey" -> "InformationContentEntity" +"Account"."account_name": String +"Account"."annual_recurring_revenue": Integer +"Account"."seat_count": Integer +"Account"."active_seat_count": Integer +"Account"."health_score": Integer +"Account"."days_to_renewal": Integer +"Account"."onboarding_days": Integer +"Account"."is_at_risk": Boolean +"Account"."has_success_plan": Boolean +"Account"."has_executive_sponsor": Boolean +"Account"."login_count_30d": Integer +"NPSSurvey"."nps_score": Integer +"Renewal"."discount_percent": Integer +"Milestone"."is_completed": Boolean +"CustomerSuccessManager"."portfolio_size": Integer +"Account" -> "CustomerSuccessManager": managed_by +"Account" -> "CustomerContact": has_contact +"Account" -> "ExecutiveSponsor": sponsored_by +"Account" -> "LifecycleStage": in_stage +"Account" -> "Contract": holds_contract +"Renewal" -> "Contract": renews +"Account" -> "OnboardingPlan": onboarded_via +"OnboardingPlan" -> "Milestone": contains_milestone +"Account" -> "HealthScore": scored_as +"HealthScore" -> "HealthSignal": derived_from +"RiskAlert" -> "Account": raises +"Account" -> "BusinessReview": reviewed_in +"BusinessReview" -> "ActionItem": produces +"SaveCampaign" -> "Account": targets +"CustomerSuccessManager" -> "SuccessTeam": member_of +"Expansion" -> "Account": expands +# WARNING: The following axioms could not be mapped to field constraints: +# forall x (not CustomerContact(x) and VendorStaff(x)) +# forall x (not EnterpriseAccount(x) and SmallBusinessAccount(x)) +# forall x (not HealthyScore(x) and AtRiskScore(x)) +# forall x (not ChurnedStage(x) and RenewalStage(x)) +# forall x (not VoluntaryChurn(x) and InvoluntaryChurn(x)) +# forall a (Account(a) and lt(health_score, 40) implies is_at_risk = True) +# forall a (Account(a) and is_at_risk = True implies has_success_plan = True) diff --git a/examples/domain_customer_success.d2.svg b/examples/domain_customer_success.d2.svg new file mode 100644 index 0000000..234b37f --- /dev/null +++ b/examples/domain_customer_success.d2.svg @@ -0,0 +1,117 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentOccurrentProcessRoleQualityInformationContentEntityOrganizationAccount+account_nameString+annual_recurring_revenueInteger+seat_countInteger+active_seat_countInteger+health_scoreInteger+days_to_renewalInteger+onboarding_daysInteger+is_at_riskBoolean+has_success_planBoolean+has_executive_sponsorBoolean+login_count_30dIntegerEnterpriseAccountMidMarketAccountSmallBusinessAccountPersonCustomerContactExecutiveSponsorChampionAdministratorEndUserDetractorVendorStaffCustomerSuccessManager+portfolio_sizeIntegerSolutionsEngineerAccountExecutiveSupportLiaisonSuccessTeamLifecycleStageProspectStageOnboardingStageAdoptionStageExpansionStageRenewalStageChurnedStageOnboardingProcessKickoffDataMigrationIntegrationSetupUserTrainingGoLiveOnboardingPlanMilestone+is_completedBooleanSuccessPlanSuccessGoalHealthScoreHealthyScoreNeutralScoreAtRiskScoreHealthSignalUsageSignalSupportSignalSentimentSignalFinancialSignalChurnRiskHighChurnRiskLowChurnRiskRiskAlertSaveCampaignContractSubscriptionRenewal+discount_percentIntegerAutoRenewalNegotiatedRenewalExpansionUpsellCrossSellChurnVoluntaryChurnInvoluntaryChurnInvoiceBusinessReviewExecutiveBusinessReviewQuarterlyBusinessReviewReviewDeckActionItemNPSSurvey+nps_scoreInteger managed_byhas_contactsponsored_byin_stageholds_contractrenewsonboarded_viacontains_milestonescored_asderived_fromraisesreviewed_inproducestargetsmember_ofexpands + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_customer_success.logic b/examples/domain_customer_success.logic new file mode 100644 index 0000000..b1753bc --- /dev/null +++ b/examples/domain_customer_success.logic @@ -0,0 +1,163 @@ +; ===================================================================== +; Domain: Customer Success +; Models customer accounts, onboarding, health scores, renewals, churn +; risk, success managers and business reviews on a condensed BFO upper +; level. +; Axioms enforce: health-score bounds and risk classification, renewal and +; onboarding business rules (at-risk accounts need a plan, enterprise +; accounts need an executive sponsor), and disjointness of account tiers +; and lifecycle stages. +; ===================================================================== + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent Object) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Organisations and People --- +(def-concept Organization Agent) +(def-concept Account Organization) +(def-concept EnterpriseAccount Account) +(def-concept MidMarketAccount Account) +(def-concept SmallBusinessAccount Account) +(def-concept Person Agent) +(def-concept CustomerContact Person) +(def-concept ExecutiveSponsor CustomerContact) +(def-concept Champion CustomerContact) +(def-concept Administrator CustomerContact) +(def-concept EndUser CustomerContact) +(def-concept Detractor CustomerContact) +(def-concept VendorStaff Person) +(def-concept CustomerSuccessManager VendorStaff) +(def-concept SolutionsEngineer VendorStaff) +(def-concept AccountExecutive VendorStaff) +(def-concept SupportLiaison VendorStaff) +(def-concept SuccessTeam Object) + +; --- Lifecycle --- +(def-concept LifecycleStage Quality) +(def-concept ProspectStage LifecycleStage) +(def-concept OnboardingStage LifecycleStage) +(def-concept AdoptionStage LifecycleStage) +(def-concept ExpansionStage LifecycleStage) +(def-concept RenewalStage LifecycleStage) +(def-concept ChurnedStage LifecycleStage) + +; --- Onboarding --- +(def-concept OnboardingProcess Process) +(def-concept Kickoff OnboardingProcess) +(def-concept DataMigration OnboardingProcess) +(def-concept IntegrationSetup OnboardingProcess) +(def-concept UserTraining OnboardingProcess) +(def-concept GoLive OnboardingProcess) +(def-concept OnboardingPlan InformationContentEntity) +(def-concept Milestone InformationContentEntity) +(def-concept SuccessPlan InformationContentEntity) +(def-concept SuccessGoal InformationContentEntity) + +; --- Health and Risk --- +(def-concept HealthScore Quality) +(def-concept HealthyScore HealthScore) +(def-concept NeutralScore HealthScore) +(def-concept AtRiskScore HealthScore) +(def-concept HealthSignal InformationContentEntity) +(def-concept UsageSignal HealthSignal) +(def-concept SupportSignal HealthSignal) +(def-concept SentimentSignal HealthSignal) +(def-concept FinancialSignal HealthSignal) +(def-concept ChurnRisk Quality) +(def-concept HighChurnRisk ChurnRisk) +(def-concept LowChurnRisk ChurnRisk) +(def-concept RiskAlert InformationContentEntity) +(def-concept SaveCampaign Process) + +; --- Commercial --- +(def-concept Contract InformationContentEntity) +(def-concept Subscription Contract) +(def-concept Renewal Process) +(def-concept AutoRenewal Renewal) +(def-concept NegotiatedRenewal Renewal) +(def-concept Expansion Process) +(def-concept Upsell Expansion) +(def-concept CrossSell Expansion) +(def-concept Churn Process) +(def-concept VoluntaryChurn Churn) +(def-concept InvoluntaryChurn Churn) +(def-concept Invoice InformationContentEntity) + +; --- Reviews --- +(def-concept BusinessReview Process) +(def-concept ExecutiveBusinessReview BusinessReview) +(def-concept QuarterlyBusinessReview BusinessReview) +(def-concept ReviewDeck InformationContentEntity) +(def-concept ActionItem InformationContentEntity) +(def-concept NPSSurvey InformationContentEntity) + +; --- Properties --- +(def-property account_name Account String :cardinality 1..1) +(def-property annual_recurring_revenue Account Integer) +(def-property seat_count Account Integer) +(def-property active_seat_count Account Integer) +(def-property health_score Account Integer) +(def-property days_to_renewal Account Integer) +(def-property onboarding_days Account Integer) +(def-property is_at_risk Account Boolean) +(def-property has_success_plan Account Boolean) +(def-property has_executive_sponsor Account Boolean) +(def-property login_count_30d Account Integer) +(def-property nps_score NPSSurvey Integer) +(def-property discount_percent Renewal Integer) +(def-property is_completed Milestone Boolean) +(def-property portfolio_size CustomerSuccessManager Integer) + +; --- Relations --- +(def-relation managed_by Account CustomerSuccessManager :cardinality 1..1) +(def-relation has_contact Account CustomerContact :cardinality 1..*) +(def-relation sponsored_by Account ExecutiveSponsor :cardinality 0..1) +(def-relation in_stage Account LifecycleStage :cardinality 1..1) +(def-relation holds_contract Account Contract) +(def-relation renews Renewal Contract) +(def-relation onboarded_via Account OnboardingPlan) +(def-relation contains_milestone OnboardingPlan Milestone :cardinality 1..*) +(def-relation scored_as Account HealthScore) +(def-relation derived_from HealthScore HealthSignal :cardinality 1..*) +(def-relation raises RiskAlert Account) +(def-relation reviewed_in Account BusinessReview) +(def-relation produces BusinessReview ActionItem) +(def-relation targets SaveCampaign Account) +(def-relation member_of CustomerSuccessManager SuccessTeam) +(def-relation expands Expansion Account) + +; --- Axioms --- +; 1. Integrity: customer contacts are never vendor staff +(forall (x) (not (and (CustomerContact x) (VendorStaff x)))) +; 2. Integrity: an account cannot be both enterprise and small-business tier +(forall (x) (not (and (EnterpriseAccount x) (SmallBusinessAccount x)))) +; 3. Integrity: churned and healthy are mutually exclusive classifications +(forall (x) (not (and (HealthyScore x) (AtRiskScore x)))) +; 4. Integrity: churned stage and renewal stage are distinct lifecycle states +(forall (x) (not (and (ChurnedStage x) (RenewalStage x)))) +; 5. Integrity: voluntary and involuntary churn are distinct causes +(forall (x) (not (and (VoluntaryChurn x) (InvoluntaryChurn x)))) +; 6. Health: the health score is a 0-100 index +(forall (a) (implies (Account a) (and (gte health_score 0) (lte health_score 100)))) +; 7. Health: NPS survey responses are scored 0 to 10 +(forall (n) (implies (NPSSurvey n) (and (gte nps_score 0) (lte nps_score 10)))) +; 8. Risk: an account scoring below 40 is flagged at risk +(forall (a) (implies (and (Account a) (lt health_score 40)) (eq is_at_risk True))) +; 9. Risk: an at-risk account must have a documented success plan +(forall (a) (implies (and (Account a) (eq is_at_risk True)) (eq has_success_plan True))) +; 10. Business: enterprise accounts must have an executive sponsor +(forall (a) (implies (EnterpriseAccount a) (eq has_executive_sponsor True))) +; 11. Business: renewal discounts are capped at 30 percent +(forall (r) (implies (Renewal r) (and (gte discount_percent 0) (lte discount_percent 30)))) +; 12. Business: a customer success manager carries at most 60 accounts +(forall (m) (implies (CustomerSuccessManager m) (lte portfolio_size 60))) diff --git a/examples/domain_customer_success.mmd b/examples/domain_customer_success.mmd new file mode 100644 index 0000000..e6ed551 --- /dev/null +++ b/examples/domain_customer_success.mmd @@ -0,0 +1,196 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Organization["Organization"] + class Account["Account"] + class EnterpriseAccount["EnterpriseAccount"] + class MidMarketAccount["MidMarketAccount"] + class SmallBusinessAccount["SmallBusinessAccount"] + class Person["Person"] + class CustomerContact["CustomerContact"] + class ExecutiveSponsor["ExecutiveSponsor"] + class Champion["Champion"] + class Administrator["Administrator"] + class EndUser["EndUser"] + class Detractor["Detractor"] + class VendorStaff["VendorStaff"] + class CustomerSuccessManager["CustomerSuccessManager"] + class SolutionsEngineer["SolutionsEngineer"] + class AccountExecutive["AccountExecutive"] + class SupportLiaison["SupportLiaison"] + class SuccessTeam["SuccessTeam"] + class LifecycleStage["LifecycleStage"] + class ProspectStage["ProspectStage"] + class OnboardingStage["OnboardingStage"] + class AdoptionStage["AdoptionStage"] + class ExpansionStage["ExpansionStage"] + class RenewalStage["RenewalStage"] + class ChurnedStage["ChurnedStage"] + class OnboardingProcess["OnboardingProcess"] + class Kickoff["Kickoff"] + class DataMigration["DataMigration"] + class IntegrationSetup["IntegrationSetup"] + class UserTraining["UserTraining"] + class GoLive["GoLive"] + class OnboardingPlan["OnboardingPlan"] + class Milestone["Milestone"] + class SuccessPlan["SuccessPlan"] + class SuccessGoal["SuccessGoal"] + class HealthScore["HealthScore"] + class HealthyScore["HealthyScore"] + class NeutralScore["NeutralScore"] + class AtRiskScore["AtRiskScore"] + class HealthSignal["HealthSignal"] + class UsageSignal["UsageSignal"] + class SupportSignal["SupportSignal"] + class SentimentSignal["SentimentSignal"] + class FinancialSignal["FinancialSignal"] + class ChurnRisk["ChurnRisk"] + class HighChurnRisk["HighChurnRisk"] + class LowChurnRisk["LowChurnRisk"] + class RiskAlert["RiskAlert"] + class SaveCampaign["SaveCampaign"] + class Contract["Contract"] + class Subscription["Subscription"] + class Renewal["Renewal"] + class AutoRenewal["AutoRenewal"] + class NegotiatedRenewal["NegotiatedRenewal"] + class Expansion["Expansion"] + class Upsell["Upsell"] + class CrossSell["CrossSell"] + class Churn["Churn"] + class VoluntaryChurn["VoluntaryChurn"] + class InvoluntaryChurn["InvoluntaryChurn"] + class Invoice["Invoice"] + class BusinessReview["BusinessReview"] + class ExecutiveBusinessReview["ExecutiveBusinessReview"] + class QuarterlyBusinessReview["QuarterlyBusinessReview"] + class ReviewDeck["ReviewDeck"] + class ActionItem["ActionItem"] + class NPSSurvey["NPSSurvey"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Object <|-- Agent + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Agent <|-- Organization + Organization <|-- Account + Account <|-- EnterpriseAccount + Account <|-- MidMarketAccount + Account <|-- SmallBusinessAccount + Agent <|-- Person + Person <|-- CustomerContact + CustomerContact <|-- ExecutiveSponsor + CustomerContact <|-- Champion + CustomerContact <|-- Administrator + CustomerContact <|-- EndUser + CustomerContact <|-- Detractor + Person <|-- VendorStaff + VendorStaff <|-- CustomerSuccessManager + VendorStaff <|-- SolutionsEngineer + VendorStaff <|-- AccountExecutive + VendorStaff <|-- SupportLiaison + Object <|-- SuccessTeam + Quality <|-- LifecycleStage + LifecycleStage <|-- ProspectStage + LifecycleStage <|-- OnboardingStage + LifecycleStage <|-- AdoptionStage + LifecycleStage <|-- ExpansionStage + LifecycleStage <|-- RenewalStage + LifecycleStage <|-- ChurnedStage + Process <|-- OnboardingProcess + OnboardingProcess <|-- Kickoff + OnboardingProcess <|-- DataMigration + OnboardingProcess <|-- IntegrationSetup + OnboardingProcess <|-- UserTraining + OnboardingProcess <|-- GoLive + InformationContentEntity <|-- OnboardingPlan + InformationContentEntity <|-- Milestone + InformationContentEntity <|-- SuccessPlan + InformationContentEntity <|-- SuccessGoal + Quality <|-- HealthScore + HealthScore <|-- HealthyScore + HealthScore <|-- NeutralScore + HealthScore <|-- AtRiskScore + InformationContentEntity <|-- HealthSignal + HealthSignal <|-- UsageSignal + HealthSignal <|-- SupportSignal + HealthSignal <|-- SentimentSignal + HealthSignal <|-- FinancialSignal + Quality <|-- ChurnRisk + ChurnRisk <|-- HighChurnRisk + ChurnRisk <|-- LowChurnRisk + InformationContentEntity <|-- RiskAlert + Process <|-- SaveCampaign + InformationContentEntity <|-- Contract + Contract <|-- Subscription + Process <|-- Renewal + Renewal <|-- AutoRenewal + Renewal <|-- NegotiatedRenewal + Process <|-- Expansion + Expansion <|-- Upsell + Expansion <|-- CrossSell + Process <|-- Churn + Churn <|-- VoluntaryChurn + Churn <|-- InvoluntaryChurn + InformationContentEntity <|-- Invoice + Process <|-- BusinessReview + BusinessReview <|-- ExecutiveBusinessReview + BusinessReview <|-- QuarterlyBusinessReview + InformationContentEntity <|-- ReviewDeck + InformationContentEntity <|-- ActionItem + InformationContentEntity <|-- NPSSurvey + Account : +String account_name + Account : +Integer annual_recurring_revenue + Account : +Integer seat_count + Account : +Integer active_seat_count + Account : +Integer health_score + Account : +Integer days_to_renewal + Account : +Integer onboarding_days + Account : +Boolean is_at_risk + Account : +Boolean has_success_plan + Account : +Boolean has_executive_sponsor + Account : +Integer login_count_30d + NPSSurvey : +Integer nps_score + Renewal : +Integer discount_percent + Milestone : +Boolean is_completed + CustomerSuccessManager : +Integer portfolio_size + Account --> CustomerSuccessManager : managed_by + Account --> CustomerContact : has_contact + Account --> ExecutiveSponsor : sponsored_by + Account --> LifecycleStage : in_stage + Account --> Contract : holds_contract + Renewal --> Contract : renews + Account --> OnboardingPlan : onboarded_via + OnboardingPlan --> Milestone : contains_milestone + Account --> HealthScore : scored_as + HealthScore --> HealthSignal : derived_from + RiskAlert --> Account : raises + Account --> BusinessReview : reviewed_in + BusinessReview --> ActionItem : produces + SaveCampaign --> Account : targets + CustomerSuccessManager --> SuccessTeam : member_of + Expansion --> Account : expands + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall x (not CustomerContact(x) and VendorStaff(x)) +%% forall x (not EnterpriseAccount(x) and SmallBusinessAccount(x)) +%% forall x (not HealthyScore(x) and AtRiskScore(x)) +%% forall x (not ChurnedStage(x) and RenewalStage(x)) +%% forall x (not VoluntaryChurn(x) and InvoluntaryChurn(x)) +%% forall a (Account(a) and lt(health_score, 40) implies is_at_risk = True) +%% forall a (Account(a) and is_at_risk = True implies has_success_plan = True) diff --git a/examples/domain_cybersecurity_soc.cypher b/examples/domain_cybersecurity_soc.cypher new file mode 100644 index 0000000..0d978b8 --- /dev/null +++ b/examples/domain_cybersecurity_soc.cypher @@ -0,0 +1,364 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Asset'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Endpoint'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Workstation'}) +MERGE (p:OntologyClass {name: 'Endpoint'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Server'}) +MERGE (p:OntologyClass {name: 'Endpoint'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DomainController'}) +MERGE (p:OntologyClass {name: 'Server'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DatabaseServer'}) +MERGE (p:OntologyClass {name: 'Server'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MobileDevice'}) +MERGE (p:OntologyClass {name: 'Endpoint'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NetworkDevice'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Firewall'}) +MERGE (p:OntologyClass {name: 'NetworkDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Router'}) +MERGE (p:OntologyClass {name: 'NetworkDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CloudWorkload'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Application'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'UserAccount'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ServiceAccount'}) +MERGE (p:OntologyClass {name: 'UserAccount'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PrivilegedAccount'}) +MERGE (p:OntologyClass {name: 'UserAccount'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataStore'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BusinessUnit'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Vulnerability'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'KnownExploitedVulnerability'}) +MERGE (p:OntologyClass {name: 'Vulnerability'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Weakness'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Misconfiguration'}) +MERGE (p:OntologyClass {name: 'Weakness'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Patch'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThreatActor'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CriminalGroup'}) +MERGE (p:OntologyClass {name: 'ThreatActor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StateSponsoredGroup'}) +MERGE (p:OntologyClass {name: 'ThreatActor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Insider'}) +MERGE (p:OntologyClass {name: 'ThreatActor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Technique'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tactic'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Malware'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Ransomware'}) +MERGE (p:OntologyClass {name: 'Malware'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThreatIntelFeed'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Indicator'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IpIndicator'}) +MERGE (p:OntologyClass {name: 'Indicator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DomainIndicator'}) +MERGE (p:OntologyClass {name: 'Indicator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HashIndicator'}) +MERGE (p:OntologyClass {name: 'Indicator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sensor'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EdrAgent'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NetworkSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LogCollector'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SiemPlatform'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DetectionRule'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Alert'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FalsePositiveAlert'}) +MERGE (p:OntologyClass {name: 'Alert'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TruePositiveAlert'}) +MERGE (p:OntologyClass {name: 'Alert'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LogEvent'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Evidence'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MemoryImage'}) +MERGE (p:OntologyClass {name: 'Evidence'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PacketCapture'}) +MERGE (p:OntologyClass {name: 'Evidence'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DiskImage'}) +MERGE (p:OntologyClass {name: 'Evidence'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Incident'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PhishingIncident'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MalwareIncident'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataBreachIncident'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DenialOfServiceIncident'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Severity'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Playbook'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PlaybookStep'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ContainmentAction'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IsolateHost'}) +MERGE (p:OntologyClass {name: 'ContainmentAction'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DisableAccount'}) +MERGE (p:OntologyClass {name: 'ContainmentAction'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BlockIndicator'}) +MERGE (p:OntologyClass {name: 'ContainmentAction'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Triage'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Investigation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Eradication'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Recovery'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PostIncidentReview'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Escalation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Analyst'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tier1Analyst'}) +MERGE (p:OntologyClass {name: 'Analyst'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tier2Analyst'}) +MERGE (p:OntologyClass {name: 'Analyst'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tier3Analyst'}) +MERGE (p:OntologyClass {name: 'Analyst'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IncidentCommander'}) +MERGE (p:OntologyClass {name: 'Analyst'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThreatHunter'}) +MERGE (p:OntologyClass {name: 'Analyst'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SocManager'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OnCallRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ApproverRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Application'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'runs_on'}]->(t); +MERGE (s:OntologyClass {name: 'Asset'}) +MERGE (t:OntologyClass {name: 'BusinessUnit'}) +MERGE (s)-[:RELATION {name: 'owned_by'}]->(t); +MERGE (s:OntologyClass {name: 'Asset'}) +MERGE (t:OntologyClass {name: 'Vulnerability'}) +MERGE (s)-[:RELATION {name: 'affected_by'}]->(t); +MERGE (s:OntologyClass {name: 'Vulnerability'}) +MERGE (t:OntologyClass {name: 'Patch'}) +MERGE (s)-[:RELATION {name: 'remediated_by'}]->(t); +MERGE (s:OntologyClass {name: 'Technique'}) +MERGE (t:OntologyClass {name: 'Vulnerability'}) +MERGE (s)-[:RELATION {name: 'exploits'}]->(t); +MERGE (s:OntologyClass {name: 'ThreatActor'}) +MERGE (t:OntologyClass {name: 'Technique'}) +MERGE (s)-[:RELATION {name: 'uses_technique'}]->(t); +MERGE (s:OntologyClass {name: 'ThreatActor'}) +MERGE (t:OntologyClass {name: 'Malware'}) +MERGE (s)-[:RELATION {name: 'deploys'}]->(t); +MERGE (s:OntologyClass {name: 'Sensor'}) +MERGE (t:OntologyClass {name: 'LogEvent'}) +MERGE (s)-[:RELATION {name: 'generates'}]->(t); +MERGE (s:OntologyClass {name: 'LogEvent'}) +MERGE (t:OntologyClass {name: 'SiemPlatform'}) +MERGE (s)-[:RELATION {name: 'collected_by'}]->(t); +MERGE (s:OntologyClass {name: 'DetectionRule'}) +MERGE (t:OntologyClass {name: 'Alert'}) +MERGE (s)-[:RELATION {name: 'fires'}]->(t); +MERGE (s:OntologyClass {name: 'Alert'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'concerns_asset'}]->(t); +MERGE (s:OntologyClass {name: 'Alert'}) +MERGE (t:OntologyClass {name: 'Indicator'}) +MERGE (s)-[:RELATION {name: 'matches'}]->(t); +MERGE (s:OntologyClass {name: 'Alert'}) +MERGE (t:OntologyClass {name: 'Incident'}) +MERGE (s)-[:RELATION {name: 'escalates_to'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'involves'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'ThreatActor'}) +MERGE (s)-[:RELATION {name: 'attributed_to'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'Analyst'}) +MERGE (s)-[:RELATION {name: 'assigned_to'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'Playbook'}) +MERGE (s)-[:RELATION {name: 'handled_by_playbook'}]->(t); +MERGE (s:OntologyClass {name: 'Playbook'}) +MERGE (t:OntologyClass {name: 'PlaybookStep'}) +MERGE (s)-[:RELATION {name: 'has_step'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'ContainmentAction'}) +MERGE (s)-[:RELATION {name: 'contains'}]->(t); +MERGE (s:OntologyClass {name: 'ContainmentAction'}) +MERGE (t:OntologyClass {name: 'Analyst'}) +MERGE (s)-[:RELATION {name: 'approved_by'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'Evidence'}) +MERGE (s)-[:RELATION {name: 'supported_by'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'ServiceLevelAgreement'}) +MERGE (s)-[:RELATION {name: 'bound_by'}]->(t); +MERGE (s:OntologyClass {name: 'Analyst'}) +MERGE (t:OntologyClass {name: 'SocManager'}) +MERGE (s)-[:RELATION {name: 'reports_to'}]->(t); +// Axiom Validations +// Axiom validation: PrivilegedAccount is_mfa_enabled eq True +MATCH (n:`PrivilegedAccount`) WHERE NOT (n.`is_mfa_enabled` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Vulnerability cvss_score gte 0 +MATCH (n:`Vulnerability`) WHERE NOT (n.`cvss_score` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Vulnerability cvss_score lte 100 +MATCH (n:`Vulnerability`) WHERE NOT (n.`cvss_score` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Alert alert_confidence gte 0 +MATCH (n:`Alert`) WHERE NOT (n.`alert_confidence` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Alert alert_confidence lte 100 +MATCH (n:`Alert`) WHERE NOT (n.`alert_confidence` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Evidence chain_of_custody_intact eq True +MATCH (n:`Evidence`) WHERE NOT (n.`chain_of_custody_intact` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Incident incident_severity gte 1 +MATCH (n:`Incident`) WHERE NOT (n.`incident_severity` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Incident incident_severity lte 4 +MATCH (n:`Incident`) WHERE NOT (n.`incident_severity` <= 4) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Incident minutes_to_acknowledge lte 240 +MATCH (n:`Incident`) WHERE NOT (n.`minutes_to_acknowledge` <= 240) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall i (Incident(i) and incident_severity = 4 implies is_escalated = True) +// forall c (DisableAccount(c) implies exists a (Analyst(a) and approved_by(c, a))) +// forall c (IsolateHost(c) implies exists a (Analyst(a) and approved_by(c, a))) +// forall i (Incident(i) implies exists p (Playbook(p) and handled_by_playbook(i, p))) +// forall i (Incident(i) and is_closed = True implies has_post_incident_review = True) +// forall a (FalsePositiveAlert(a) implies not TruePositiveAlert(a)) +// forall a (Tier1Analyst(a) implies not Tier3Analyst(a)) diff --git a/examples/domain_cybersecurity_soc.d2 b/examples/domain_cybersecurity_soc.d2 new file mode 100644 index 0000000..7a17ea3 --- /dev/null +++ b/examples/domain_cybersecurity_soc.d2 @@ -0,0 +1,233 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Asset": { shape: class } +"Endpoint": { shape: class } +"Workstation": { shape: class } +"Server": { shape: class } +"DomainController": { shape: class } +"DatabaseServer": { shape: class } +"MobileDevice": { shape: class } +"NetworkDevice": { shape: class } +"Firewall": { shape: class } +"Router": { shape: class } +"CloudWorkload": { shape: class } +"Application": { shape: class } +"UserAccount": { shape: class } +"ServiceAccount": { shape: class } +"PrivilegedAccount": { shape: class } +"DataStore": { shape: class } +"BusinessUnit": { shape: class } +"Vulnerability": { shape: class } +"KnownExploitedVulnerability": { shape: class } +"Weakness": { shape: class } +"Misconfiguration": { shape: class } +"Patch": { shape: class } +"ThreatActor": { shape: class } +"CriminalGroup": { shape: class } +"StateSponsoredGroup": { shape: class } +"Insider": { shape: class } +"Technique": { shape: class } +"Tactic": { shape: class } +"Malware": { shape: class } +"Ransomware": { shape: class } +"ThreatIntelFeed": { shape: class } +"Indicator": { shape: class } +"IpIndicator": { shape: class } +"DomainIndicator": { shape: class } +"HashIndicator": { shape: class } +"Sensor": { shape: class } +"EdrAgent": { shape: class } +"NetworkSensor": { shape: class } +"LogCollector": { shape: class } +"SiemPlatform": { shape: class } +"DetectionRule": { shape: class } +"Alert": { shape: class } +"FalsePositiveAlert": { shape: class } +"TruePositiveAlert": { shape: class } +"LogEvent": { shape: class } +"Evidence": { shape: class } +"MemoryImage": { shape: class } +"PacketCapture": { shape: class } +"DiskImage": { shape: class } +"Incident": { shape: class } +"PhishingIncident": { shape: class } +"MalwareIncident": { shape: class } +"DataBreachIncident": { shape: class } +"DenialOfServiceIncident": { shape: class } +"Severity": { shape: class } +"ServiceLevelAgreement": { shape: class } +"Playbook": { shape: class } +"PlaybookStep": { shape: class } +"ContainmentAction": { shape: class } +"IsolateHost": { shape: class } +"DisableAccount": { shape: class } +"BlockIndicator": { shape: class } +"Triage": { shape: class } +"Investigation": { shape: class } +"Eradication": { shape: class } +"Recovery": { shape: class } +"PostIncidentReview": { shape: class } +"Escalation": { shape: class } +"Analyst": { shape: class } +"Tier1Analyst": { shape: class } +"Tier2Analyst": { shape: class } +"Tier3Analyst": { shape: class } +"IncidentCommander": { shape: class } +"ThreatHunter": { shape: class } +"SocManager": { shape: class } +"OnCallRole": { shape: class } +"ApproverRole": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Asset" -> "Object" +"Endpoint" -> "Asset" +"Workstation" -> "Endpoint" +"Server" -> "Endpoint" +"DomainController" -> "Server" +"DatabaseServer" -> "Server" +"MobileDevice" -> "Endpoint" +"NetworkDevice" -> "Asset" +"Firewall" -> "NetworkDevice" +"Router" -> "NetworkDevice" +"CloudWorkload" -> "Asset" +"Application" -> "Asset" +"UserAccount" -> "Asset" +"ServiceAccount" -> "UserAccount" +"PrivilegedAccount" -> "UserAccount" +"DataStore" -> "Asset" +"BusinessUnit" -> "Agent" +"Vulnerability" -> "InformationContentEntity" +"KnownExploitedVulnerability" -> "Vulnerability" +"Weakness" -> "InformationContentEntity" +"Misconfiguration" -> "Weakness" +"Patch" -> "InformationContentEntity" +"ThreatActor" -> "Agent" +"CriminalGroup" -> "ThreatActor" +"StateSponsoredGroup" -> "ThreatActor" +"Insider" -> "ThreatActor" +"Technique" -> "InformationContentEntity" +"Tactic" -> "InformationContentEntity" +"Malware" -> "InformationContentEntity" +"Ransomware" -> "Malware" +"ThreatIntelFeed" -> "InformationContentEntity" +"Indicator" -> "InformationContentEntity" +"IpIndicator" -> "Indicator" +"DomainIndicator" -> "Indicator" +"HashIndicator" -> "Indicator" +"Sensor" -> "Object" +"EdrAgent" -> "Sensor" +"NetworkSensor" -> "Sensor" +"LogCollector" -> "Sensor" +"SiemPlatform" -> "Object" +"DetectionRule" -> "InformationContentEntity" +"Alert" -> "InformationContentEntity" +"FalsePositiveAlert" -> "Alert" +"TruePositiveAlert" -> "Alert" +"LogEvent" -> "InformationContentEntity" +"Evidence" -> "InformationContentEntity" +"MemoryImage" -> "Evidence" +"PacketCapture" -> "Evidence" +"DiskImage" -> "Evidence" +"Incident" -> "InformationContentEntity" +"PhishingIncident" -> "Incident" +"MalwareIncident" -> "Incident" +"DataBreachIncident" -> "Incident" +"DenialOfServiceIncident" -> "Incident" +"Severity" -> "Quality" +"ServiceLevelAgreement" -> "InformationContentEntity" +"Playbook" -> "InformationContentEntity" +"PlaybookStep" -> "InformationContentEntity" +"ContainmentAction" -> "Process" +"IsolateHost" -> "ContainmentAction" +"DisableAccount" -> "ContainmentAction" +"BlockIndicator" -> "ContainmentAction" +"Triage" -> "Process" +"Investigation" -> "Process" +"Eradication" -> "Process" +"Recovery" -> "Process" +"PostIncidentReview" -> "Process" +"Escalation" -> "Process" +"Analyst" -> "Agent" +"Tier1Analyst" -> "Analyst" +"Tier2Analyst" -> "Analyst" +"Tier3Analyst" -> "Analyst" +"IncidentCommander" -> "Analyst" +"ThreatHunter" -> "Analyst" +"SocManager" -> "Agent" +"OnCallRole" -> "Role" +"ApproverRole" -> "Role" +"Asset"."hostname": String +"Asset"."criticality": Integer +"Asset"."is_internet_facing": Boolean +"Asset"."is_crown_jewel": Boolean +"Vulnerability"."cvss_score": Integer +"Vulnerability"."epss_percent": Integer +"Vulnerability"."is_patched": Boolean +"Vulnerability"."days_open": Integer +"Alert"."alert_confidence": Integer +"Alert"."alert_severity": Integer +"Incident"."incident_severity": Integer +"Incident"."is_escalated": Boolean +"Incident"."is_contained": Boolean +"Incident"."minutes_to_acknowledge": Integer +"Incident"."minutes_to_contain": Integer +"Incident"."is_closed": Boolean +"Incident"."has_post_incident_review": Boolean +"ServiceLevelAgreement"."sla_ack_minutes": Integer +"ServiceLevelAgreement"."sla_contain_minutes": Integer +"ContainmentAction"."requires_approval": Boolean +"ContainmentAction"."is_approved": Boolean +"Evidence"."chain_of_custody_intact": Boolean +"UserAccount"."is_mfa_enabled": Boolean +"DataStore"."is_legal_hold": Boolean +"Application" -> "Asset": runs_on +"Asset" -> "BusinessUnit": owned_by +"Asset" -> "Vulnerability": affected_by +"Vulnerability" -> "Patch": remediated_by +"Technique" -> "Vulnerability": exploits +"ThreatActor" -> "Technique": uses_technique +"ThreatActor" -> "Malware": deploys +"Sensor" -> "LogEvent": generates +"LogEvent" -> "SiemPlatform": collected_by +"DetectionRule" -> "Alert": fires +"Alert" -> "Asset": concerns_asset +"Alert" -> "Indicator": matches +"Alert" -> "Incident": escalates_to +"Incident" -> "Asset": involves +"Incident" -> "ThreatActor": attributed_to +"Incident" -> "Analyst": assigned_to +"Incident" -> "Playbook": handled_by_playbook +"Playbook" -> "PlaybookStep": has_step +"Incident" -> "ContainmentAction": contains +"ContainmentAction" -> "Analyst": approved_by +"Incident" -> "Evidence": supported_by +"Incident" -> "ServiceLevelAgreement": bound_by +"Analyst" -> "SocManager": reports_to +# WARNING: The following axioms could not be mapped to field constraints: +# forall i (Incident(i) and incident_severity = 4 implies is_escalated = True) +# forall c (DisableAccount(c) implies exists a (Analyst(a) and approved_by(c, a))) +# forall c (IsolateHost(c) implies exists a (Analyst(a) and approved_by(c, a))) +# forall i (Incident(i) implies exists p (Playbook(p) and handled_by_playbook(i, p))) +# forall i (Incident(i) and is_closed = True implies has_post_incident_review = True) +# forall a (FalsePositiveAlert(a) implies not TruePositiveAlert(a)) +# forall a (Tier1Analyst(a) implies not Tier3Analyst(a)) diff --git a/examples/domain_cybersecurity_soc.d2.svg b/examples/domain_cybersecurity_soc.d2.svg new file mode 100644 index 0000000..63d88af --- /dev/null +++ b/examples/domain_cybersecurity_soc.d2.svg @@ -0,0 +1,124 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentOccurrentProcessRoleFunctionQualityInformationContentEntityAsset+hostnameString+criticalityInteger+is_internet_facingBoolean+is_crown_jewelBooleanEndpointWorkstationServerDomainControllerDatabaseServerMobileDeviceNetworkDeviceFirewallRouterCloudWorkloadApplicationUserAccount+is_mfa_enabledBooleanServiceAccountPrivilegedAccountDataStore+is_legal_holdBooleanBusinessUnitVulnerability+cvss_scoreInteger+epss_percentInteger+is_patchedBoolean+days_openIntegerKnownExploitedVulnerabilityWeaknessMisconfigurationPatchThreatActorCriminalGroupStateSponsoredGroupInsiderTechniqueTacticMalwareRansomwareThreatIntelFeedIndicatorIpIndicatorDomainIndicatorHashIndicatorSensorEdrAgentNetworkSensorLogCollectorSiemPlatformDetectionRuleAlert+alert_confidenceInteger+alert_severityIntegerFalsePositiveAlertTruePositiveAlertLogEventEvidence+chain_of_custody_intactBooleanMemoryImagePacketCaptureDiskImageIncident+incident_severityInteger+is_escalatedBoolean+is_containedBoolean+minutes_to_acknowledgeInteger+minutes_to_containInteger+is_closedBoolean+has_post_incident_reviewBooleanPhishingIncidentMalwareIncidentDataBreachIncidentDenialOfServiceIncidentSeverityServiceLevelAgreement+sla_ack_minutesInteger+sla_contain_minutesIntegerPlaybookPlaybookStepContainmentAction+requires_approvalBoolean+is_approvedBooleanIsolateHostDisableAccountBlockIndicatorTriageInvestigationEradicationRecoveryPostIncidentReviewEscalationAnalystTier1AnalystTier2AnalystTier3AnalystIncidentCommanderThreatHunterSocManagerOnCallRoleApproverRole runs_onowned_byaffected_byremediated_byexploitsuses_techniquedeploysgeneratescollected_byfiresconcerns_assetmatchesescalates_toinvolvesattributed_toassigned_tohandled_by_playbookhas_stepcontainsapproved_bysupported_bybound_byreports_to + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_cybersecurity_soc.logic b/examples/domain_cybersecurity_soc.logic new file mode 100644 index 0000000..3a065f1 --- /dev/null +++ b/examples/domain_cybersecurity_soc.logic @@ -0,0 +1,220 @@ +; --- Cybersecurity Operations (SOC) --- +; Models assets, vulnerabilities, detections, alerts, incidents, analysts, +; playbooks, and severity / SLA rules. +; Axioms enforce: severity-to-SLA timing, escalation of critical incidents, +; containment approvals, evidence handling and analyst tier separation. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Assets --- +(def-concept Asset Object) +(def-concept Endpoint Asset) +(def-concept Workstation Endpoint) +(def-concept Server Endpoint) +(def-concept DomainController Server) +(def-concept DatabaseServer Server) +(def-concept MobileDevice Endpoint) +(def-concept NetworkDevice Asset) +(def-concept Firewall NetworkDevice) +(def-concept Router NetworkDevice) +(def-concept CloudWorkload Asset) +(def-concept Application Asset) +(def-concept UserAccount Asset) +(def-concept ServiceAccount UserAccount) +(def-concept PrivilegedAccount UserAccount) +(def-concept DataStore Asset) +(def-concept BusinessUnit Agent) + +; --- Vulnerabilities and Threats --- +(def-concept Vulnerability InformationContentEntity) +(def-concept KnownExploitedVulnerability Vulnerability) +(def-concept Weakness InformationContentEntity) +(def-concept Misconfiguration Weakness) +(def-concept Patch InformationContentEntity) +(def-concept ThreatActor Agent) +(def-concept CriminalGroup ThreatActor) +(def-concept StateSponsoredGroup ThreatActor) +(def-concept Insider ThreatActor) +(def-concept Technique InformationContentEntity) +(def-concept Tactic InformationContentEntity) +(def-concept Malware InformationContentEntity) +(def-concept Ransomware Malware) +(def-concept ThreatIntelFeed InformationContentEntity) +(def-concept Indicator InformationContentEntity) +(def-concept IpIndicator Indicator) +(def-concept DomainIndicator Indicator) +(def-concept HashIndicator Indicator) + +; --- Detection and Alerting --- +(def-concept Sensor Object) +(def-concept EdrAgent Sensor) +(def-concept NetworkSensor Sensor) +(def-concept LogCollector Sensor) +(def-concept SiemPlatform Object) +(def-concept DetectionRule InformationContentEntity) +(def-concept Alert InformationContentEntity) +(def-concept FalsePositiveAlert Alert) +(def-concept TruePositiveAlert Alert) +(def-concept LogEvent InformationContentEntity) +(def-concept Evidence InformationContentEntity) +(def-concept MemoryImage Evidence) +(def-concept PacketCapture Evidence) +(def-concept DiskImage Evidence) + +; --- Incident Management --- +(def-concept Incident InformationContentEntity) +(def-concept PhishingIncident Incident) +(def-concept MalwareIncident Incident) +(def-concept DataBreachIncident Incident) +(def-concept DenialOfServiceIncident Incident) +(def-concept Severity Quality) +(def-concept ServiceLevelAgreement InformationContentEntity) +(def-concept Playbook InformationContentEntity) +(def-concept PlaybookStep InformationContentEntity) +(def-concept ContainmentAction Process) +(def-concept IsolateHost ContainmentAction) +(def-concept DisableAccount ContainmentAction) +(def-concept BlockIndicator ContainmentAction) +(def-concept Triage Process) +(def-concept Investigation Process) +(def-concept Eradication Process) +(def-concept Recovery Process) +(def-concept PostIncidentReview Process) +(def-concept Escalation Process) + +; --- People and Roles --- +(def-concept Analyst Agent) +(def-concept Tier1Analyst Analyst) +(def-concept Tier2Analyst Analyst) +(def-concept Tier3Analyst Analyst) +(def-concept IncidentCommander Analyst) +(def-concept ThreatHunter Analyst) +(def-concept SocManager Agent) +(def-concept OnCallRole Role) +(def-concept ApproverRole Role) + +; --- Relations --- +(def-relation runs_on Application Asset) +(def-relation owned_by Asset BusinessUnit) +(def-relation affected_by Asset Vulnerability :cardinality 0..*) +(def-relation remediated_by Vulnerability Patch :cardinality 0..*) +(def-relation exploits Technique Vulnerability :cardinality 0..*) +(def-relation uses_technique ThreatActor Technique :cardinality 0..*) +(def-relation deploys ThreatActor Malware :cardinality 0..*) +(def-relation generates Sensor LogEvent :cardinality 0..*) +(def-relation collected_by LogEvent SiemPlatform) +(def-relation fires DetectionRule Alert :cardinality 0..*) +(def-relation concerns_asset Alert Asset :cardinality 1..*) +(def-relation matches Alert Indicator :cardinality 0..*) +(def-relation escalates_to Alert Incident) +(def-relation involves Incident Asset :cardinality 1..*) +(def-relation attributed_to Incident ThreatActor :cardinality 0..1) +(def-relation assigned_to Incident Analyst :cardinality 1..1) +(def-relation handled_by_playbook Incident Playbook) +(def-relation has_step Playbook PlaybookStep :cardinality 1..*) +(def-relation contains Incident ContainmentAction :cardinality 0..*) +(def-relation approved_by ContainmentAction Analyst) +(def-relation supported_by Incident Evidence :cardinality 0..*) +(def-relation bound_by Incident ServiceLevelAgreement :cardinality 1..1) +(def-relation reports_to Analyst SocManager) + +; --- Properties --- +(def-property hostname Asset String) +(def-property criticality Asset Integer) +(def-property is_internet_facing Asset Boolean) +(def-property is_crown_jewel Asset Boolean) +(def-property cvss_score Vulnerability Integer) +(def-property epss_percent Vulnerability Integer) +(def-property is_patched Vulnerability Boolean) +(def-property days_open Vulnerability Integer) +(def-property alert_confidence Alert Integer) +(def-property alert_severity Alert Integer) +(def-property incident_severity Incident Integer) +(def-property is_escalated Incident Boolean) +(def-property is_contained Incident Boolean) +(def-property minutes_to_acknowledge Incident Integer) +(def-property minutes_to_contain Incident Integer) +(def-property is_closed Incident Boolean) +(def-property has_post_incident_review Incident Boolean) +(def-property sla_ack_minutes ServiceLevelAgreement Integer) +(def-property sla_contain_minutes ServiceLevelAgreement Integer) +(def-property requires_approval ContainmentAction Boolean) +(def-property is_approved ContainmentAction Boolean) +(def-property chain_of_custody_intact Evidence Boolean) +(def-property is_mfa_enabled UserAccount Boolean) +(def-property is_legal_hold DataStore Boolean) + +; --- Axioms --- + +; 1. CVSS scores are scaled 0..100 (score x 10) +(forall (v) + (implies (Vulnerability v) + (and (gte cvss_score 0) (lte cvss_score 100)))) + +; 2. Incident severity scale is 1 (informational) to 4 (critical) +(forall (i) + (implies (Incident i) + (and (gte incident_severity 1) (lte incident_severity 4)))) + +; 3. Alert confidence is a percentage +(forall (a) + (implies (Alert a) + (and (gte alert_confidence 0) (lte alert_confidence 100)))) + +; 4. Critical incidents (severity 4) are always escalated +(forall (i) + (implies (and (Incident i) (eq incident_severity 4)) + (eq is_escalated True))) + +; 5. Acknowledgement SLA: an incident is acknowledged within 240 minutes +(forall (i) + (implies (Incident i) + (lte minutes_to_acknowledge 240))) + +; 6. Privileged accounts must have MFA enabled +(forall (a) + (implies (PrivilegedAccount a) (eq is_mfa_enabled True))) + +; 7. Disabling an account requires a named approver +(forall (c) + (implies (DisableAccount c) + (exists (a) (and (Analyst a) (approved_by c a))))) + +; 8. Host isolation also requires a named approver +(forall (c) + (implies (IsolateHost c) + (exists (a) (and (Analyst a) (approved_by c a))))) + +; 9. Evidence must keep an intact chain of custody +(forall (e) + (implies (Evidence e) (eq chain_of_custody_intact True))) + +; 10. Every incident has a playbook to follow +(forall (i) + (implies (Incident i) + (exists (p) (and (Playbook p) (handled_by_playbook i p))))) + +; 11. Closed incidents must have completed a post-incident review +(forall (i) + (implies (and (Incident i) (eq is_closed True)) + (eq has_post_incident_review True))) + +; 12. A false positive alert is never a true positive alert +(forall (a) + (implies (FalsePositiveAlert a) (not (TruePositiveAlert a)))) + +; 13. Tier 1 and Tier 3 analyst roles are distinct positions +(forall (a) + (implies (Tier1Analyst a) (not (Tier3Analyst a)))) diff --git a/examples/domain_cybersecurity_soc.mmd b/examples/domain_cybersecurity_soc.mmd new file mode 100644 index 0000000..192b1de --- /dev/null +++ b/examples/domain_cybersecurity_soc.mmd @@ -0,0 +1,234 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Asset["Asset"] + class Endpoint["Endpoint"] + class Workstation["Workstation"] + class Server["Server"] + class DomainController["DomainController"] + class DatabaseServer["DatabaseServer"] + class MobileDevice["MobileDevice"] + class NetworkDevice["NetworkDevice"] + class Firewall["Firewall"] + class Router["Router"] + class CloudWorkload["CloudWorkload"] + class Application["Application"] + class UserAccount["UserAccount"] + class ServiceAccount["ServiceAccount"] + class PrivilegedAccount["PrivilegedAccount"] + class DataStore["DataStore"] + class BusinessUnit["BusinessUnit"] + class Vulnerability["Vulnerability"] + class KnownExploitedVulnerability["KnownExploitedVulnerability"] + class Weakness["Weakness"] + class Misconfiguration["Misconfiguration"] + class Patch["Patch"] + class ThreatActor["ThreatActor"] + class CriminalGroup["CriminalGroup"] + class StateSponsoredGroup["StateSponsoredGroup"] + class Insider["Insider"] + class Technique["Technique"] + class Tactic["Tactic"] + class Malware["Malware"] + class Ransomware["Ransomware"] + class ThreatIntelFeed["ThreatIntelFeed"] + class Indicator["Indicator"] + class IpIndicator["IpIndicator"] + class DomainIndicator["DomainIndicator"] + class HashIndicator["HashIndicator"] + class Sensor["Sensor"] + class EdrAgent["EdrAgent"] + class NetworkSensor["NetworkSensor"] + class LogCollector["LogCollector"] + class SiemPlatform["SiemPlatform"] + class DetectionRule["DetectionRule"] + class Alert["Alert"] + class FalsePositiveAlert["FalsePositiveAlert"] + class TruePositiveAlert["TruePositiveAlert"] + class LogEvent["LogEvent"] + class Evidence["Evidence"] + class MemoryImage["MemoryImage"] + class PacketCapture["PacketCapture"] + class DiskImage["DiskImage"] + class Incident["Incident"] + class PhishingIncident["PhishingIncident"] + class MalwareIncident["MalwareIncident"] + class DataBreachIncident["DataBreachIncident"] + class DenialOfServiceIncident["DenialOfServiceIncident"] + class Severity["Severity"] + class ServiceLevelAgreement["ServiceLevelAgreement"] + class Playbook["Playbook"] + class PlaybookStep["PlaybookStep"] + class ContainmentAction["ContainmentAction"] + class IsolateHost["IsolateHost"] + class DisableAccount["DisableAccount"] + class BlockIndicator["BlockIndicator"] + class Triage["Triage"] + class Investigation["Investigation"] + class Eradication["Eradication"] + class Recovery["Recovery"] + class PostIncidentReview["PostIncidentReview"] + class Escalation["Escalation"] + class Analyst["Analyst"] + class Tier1Analyst["Tier1Analyst"] + class Tier2Analyst["Tier2Analyst"] + class Tier3Analyst["Tier3Analyst"] + class IncidentCommander["IncidentCommander"] + class ThreatHunter["ThreatHunter"] + class SocManager["SocManager"] + class OnCallRole["OnCallRole"] + class ApproverRole["ApproverRole"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + MaterialEntity <|-- Agent + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Object <|-- Asset + Asset <|-- Endpoint + Endpoint <|-- Workstation + Endpoint <|-- Server + Server <|-- DomainController + Server <|-- DatabaseServer + Endpoint <|-- MobileDevice + Asset <|-- NetworkDevice + NetworkDevice <|-- Firewall + NetworkDevice <|-- Router + Asset <|-- CloudWorkload + Asset <|-- Application + Asset <|-- UserAccount + UserAccount <|-- ServiceAccount + UserAccount <|-- PrivilegedAccount + Asset <|-- DataStore + Agent <|-- BusinessUnit + InformationContentEntity <|-- Vulnerability + Vulnerability <|-- KnownExploitedVulnerability + InformationContentEntity <|-- Weakness + Weakness <|-- Misconfiguration + InformationContentEntity <|-- Patch + Agent <|-- ThreatActor + ThreatActor <|-- CriminalGroup + ThreatActor <|-- StateSponsoredGroup + ThreatActor <|-- Insider + InformationContentEntity <|-- Technique + InformationContentEntity <|-- Tactic + InformationContentEntity <|-- Malware + Malware <|-- Ransomware + InformationContentEntity <|-- ThreatIntelFeed + InformationContentEntity <|-- Indicator + Indicator <|-- IpIndicator + Indicator <|-- DomainIndicator + Indicator <|-- HashIndicator + Object <|-- Sensor + Sensor <|-- EdrAgent + Sensor <|-- NetworkSensor + Sensor <|-- LogCollector + Object <|-- SiemPlatform + InformationContentEntity <|-- DetectionRule + InformationContentEntity <|-- Alert + Alert <|-- FalsePositiveAlert + Alert <|-- TruePositiveAlert + InformationContentEntity <|-- LogEvent + InformationContentEntity <|-- Evidence + Evidence <|-- MemoryImage + Evidence <|-- PacketCapture + Evidence <|-- DiskImage + InformationContentEntity <|-- Incident + Incident <|-- PhishingIncident + Incident <|-- MalwareIncident + Incident <|-- DataBreachIncident + Incident <|-- DenialOfServiceIncident + Quality <|-- Severity + InformationContentEntity <|-- ServiceLevelAgreement + InformationContentEntity <|-- Playbook + InformationContentEntity <|-- PlaybookStep + Process <|-- ContainmentAction + ContainmentAction <|-- IsolateHost + ContainmentAction <|-- DisableAccount + ContainmentAction <|-- BlockIndicator + Process <|-- Triage + Process <|-- Investigation + Process <|-- Eradication + Process <|-- Recovery + Process <|-- PostIncidentReview + Process <|-- Escalation + Agent <|-- Analyst + Analyst <|-- Tier1Analyst + Analyst <|-- Tier2Analyst + Analyst <|-- Tier3Analyst + Analyst <|-- IncidentCommander + Analyst <|-- ThreatHunter + Agent <|-- SocManager + Role <|-- OnCallRole + Role <|-- ApproverRole + Asset : +String hostname + Asset : +Integer criticality + Asset : +Boolean is_internet_facing + Asset : +Boolean is_crown_jewel + Vulnerability : +Integer cvss_score + Vulnerability : +Integer epss_percent + Vulnerability : +Boolean is_patched + Vulnerability : +Integer days_open + Alert : +Integer alert_confidence + Alert : +Integer alert_severity + Incident : +Integer incident_severity + Incident : +Boolean is_escalated + Incident : +Boolean is_contained + Incident : +Integer minutes_to_acknowledge + Incident : +Integer minutes_to_contain + Incident : +Boolean is_closed + Incident : +Boolean has_post_incident_review + ServiceLevelAgreement : +Integer sla_ack_minutes + ServiceLevelAgreement : +Integer sla_contain_minutes + ContainmentAction : +Boolean requires_approval + ContainmentAction : +Boolean is_approved + Evidence : +Boolean chain_of_custody_intact + UserAccount : +Boolean is_mfa_enabled + DataStore : +Boolean is_legal_hold + Application --> Asset : runs_on + Asset --> BusinessUnit : owned_by + Asset --> Vulnerability : affected_by + Vulnerability --> Patch : remediated_by + Technique --> Vulnerability : exploits + ThreatActor --> Technique : uses_technique + ThreatActor --> Malware : deploys + Sensor --> LogEvent : generates + LogEvent --> SiemPlatform : collected_by + DetectionRule --> Alert : fires + Alert --> Asset : concerns_asset + Alert --> Indicator : matches + Alert --> Incident : escalates_to + Incident --> Asset : involves + Incident --> ThreatActor : attributed_to + Incident --> Analyst : assigned_to + Incident --> Playbook : handled_by_playbook + Playbook --> PlaybookStep : has_step + Incident --> ContainmentAction : contains + ContainmentAction --> Analyst : approved_by + Incident --> Evidence : supported_by + Incident --> ServiceLevelAgreement : bound_by + Analyst --> SocManager : reports_to + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall i (Incident(i) and incident_severity = 4 implies is_escalated = True) +%% forall c (DisableAccount(c) implies exists a (Analyst(a) and approved_by(c, a))) +%% forall c (IsolateHost(c) implies exists a (Analyst(a) and approved_by(c, a))) +%% forall i (Incident(i) implies exists p (Playbook(p) and handled_by_playbook(i, p))) +%% forall i (Incident(i) and is_closed = True implies has_post_incident_review = True) +%% forall a (FalsePositiveAlert(a) implies not TruePositiveAlert(a)) +%% forall a (Tier1Analyst(a) implies not Tier3Analyst(a)) diff --git a/examples/domain_food_service.cypher b/examples/domain_food_service.cypher new file mode 100644 index 0000000..ea95676 --- /dev/null +++ b/examples/domain_food_service.cypher @@ -0,0 +1,330 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Guest'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'KitchenStaff'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Chef'}) +MERGE (p:OntologyClass {name: 'KitchenStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SousChef'}) +MERGE (p:OntologyClass {name: 'Chef'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LineCook'}) +MERGE (p:OntologyClass {name: 'KitchenStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Dishwasher'}) +MERGE (p:OntologyClass {name: 'KitchenStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FrontOfHouseStaff'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Server'}) +MERGE (p:OntologyClass {name: 'FrontOfHouseStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Host'}) +MERGE (p:OntologyClass {name: 'FrontOfHouseStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Manager'}) +MERGE (p:OntologyClass {name: 'FrontOfHouseStaff'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FoodSafetyOfficer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Restaurant'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DiningRoom'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Kitchen'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Station'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GrillStation'}) +MERGE (p:OntologyClass {name: 'Station'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FryStation'}) +MERGE (p:OntologyClass {name: 'Station'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SaladStation'}) +MERGE (p:OntologyClass {name: 'Station'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PastryStation'}) +MERGE (p:OntologyClass {name: 'Station'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AllergenFreeStation'}) +MERGE (p:OntologyClass {name: 'Station'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ColdStorage'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WalkInFridge'}) +MERGE (p:OntologyClass {name: 'ColdStorage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Freezer'}) +MERGE (p:OntologyClass {name: 'ColdStorage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DryStorage'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HotHoldingUnit'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Ingredient'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Meat'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Poultry'}) +MERGE (p:OntologyClass {name: 'Meat'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Seafood'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Produce'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Dairy'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Grain'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Egg'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Nut'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Spice'}) +MERGE (p:OntologyClass {name: 'Ingredient'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Allergen'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PeanutAllergen'}) +MERGE (p:OntologyClass {name: 'Allergen'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GlutenAllergen'}) +MERGE (p:OntologyClass {name: 'Allergen'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MilkAllergen'}) +MERGE (p:OntologyClass {name: 'Allergen'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ShellfishAllergen'}) +MERGE (p:OntologyClass {name: 'Allergen'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EggAllergen'}) +MERGE (p:OntologyClass {name: 'Allergen'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SesameAllergen'}) +MERGE (p:OntologyClass {name: 'Allergen'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MenuItem'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Appetizer'}) +MERGE (p:OntologyClass {name: 'MenuItem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MainCourse'}) +MERGE (p:OntologyClass {name: 'MenuItem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Dessert'}) +MERGE (p:OntologyClass {name: 'MenuItem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Beverage'}) +MERGE (p:OntologyClass {name: 'MenuItem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VegetarianItem'}) +MERGE (p:OntologyClass {name: 'MenuItem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VeganItem'}) +MERGE (p:OntologyClass {name: 'VegetarianItem'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Menu'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Recipe'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AllergenLabel'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Order'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DineInOrder'}) +MERGE (p:OntologyClass {name: 'Order'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TakeawayOrder'}) +MERGE (p:OntologyClass {name: 'Order'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DeliveryOrder'}) +MERGE (p:OntologyClass {name: 'Order'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OrderLine'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AllergyNote'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'KitchenTicket'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Payment'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PreparationProcess'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Cooking'}) +MERGE (p:OntologyClass {name: 'PreparationProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Chilling'}) +MERGE (p:OntologyClass {name: 'PreparationProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HotHolding'}) +MERGE (p:OntologyClass {name: 'PreparationProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Reheating'}) +MERGE (p:OntologyClass {name: 'PreparationProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Thawing'}) +MERGE (p:OntologyClass {name: 'PreparationProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Plating'}) +MERGE (p:OntologyClass {name: 'PreparationProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FoodBatch'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TemperatureLog'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CriticalControlPoint'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CorrectiveAction'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HealthInspection'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'MenuItem'}) +MERGE (t:OntologyClass {name: 'Ingredient'}) +MERGE (s)-[:RELATION {name: 'contains'}]->(t); +MERGE (s:OntologyClass {name: 'Ingredient'}) +MERGE (t:OntologyClass {name: 'Allergen'}) +MERGE (s)-[:RELATION {name: 'has_allergen'}]->(t); +MERGE (s:OntologyClass {name: 'AllergenLabel'}) +MERGE (t:OntologyClass {name: 'Allergen'}) +MERGE (s)-[:RELATION {name: 'lists_allergen'}]->(t); +MERGE (s:OntologyClass {name: 'AllergenLabel'}) +MERGE (t:OntologyClass {name: 'MenuItem'}) +MERGE (s)-[:RELATION {name: 'labels'}]->(t); +MERGE (s:OntologyClass {name: 'MenuItem'}) +MERGE (t:OntologyClass {name: 'Menu'}) +MERGE (s)-[:RELATION {name: 'appears_on'}]->(t); +MERGE (s:OntologyClass {name: 'MenuItem'}) +MERGE (t:OntologyClass {name: 'Station'}) +MERGE (s)-[:RELATION {name: 'prepared_by'}]->(t); +MERGE (s:OntologyClass {name: 'Order'}) +MERGE (t:OntologyClass {name: 'OrderLine'}) +MERGE (s)-[:RELATION {name: 'has_line'}]->(t); +MERGE (s:OntologyClass {name: 'OrderLine'}) +MERGE (t:OntologyClass {name: 'MenuItem'}) +MERGE (s)-[:RELATION {name: 'orders'}]->(t); +MERGE (s:OntologyClass {name: 'Order'}) +MERGE (t:OntologyClass {name: 'Guest'}) +MERGE (s)-[:RELATION {name: 'placed_by'}]->(t); +MERGE (s:OntologyClass {name: 'Order'}) +MERGE (t:OntologyClass {name: 'Server'}) +MERGE (s)-[:RELATION {name: 'served_by'}]->(t); +MERGE (s:OntologyClass {name: 'KitchenStaff'}) +MERGE (t:OntologyClass {name: 'Station'}) +MERGE (s)-[:RELATION {name: 'works_at'}]->(t); +MERGE (s:OntologyClass {name: 'FoodBatch'}) +MERGE (t:OntologyClass {name: 'ColdStorage'}) +MERGE (s)-[:RELATION {name: 'stored_in'}]->(t); +MERGE (s:OntologyClass {name: 'FoodBatch'}) +MERGE (t:OntologyClass {name: 'Ingredient'}) +MERGE (s)-[:RELATION {name: 'batch_of'}]->(t); +MERGE (s:OntologyClass {name: 'TemperatureLog'}) +MERGE (t:OntologyClass {name: 'FoodBatch'}) +MERGE (s)-[:RELATION {name: 'records'}]->(t); +MERGE (s:OntologyClass {name: 'CriticalControlPoint'}) +MERGE (t:OntologyClass {name: 'Station'}) +MERGE (s)-[:RELATION {name: 'monitors'}]->(t); +MERGE (s:OntologyClass {name: 'CriticalControlPoint'}) +MERGE (t:OntologyClass {name: 'CorrectiveAction'}) +MERGE (s)-[:RELATION {name: 'triggers'}]->(t); +MERGE (s:OntologyClass {name: 'MenuItem'}) +MERGE (t:OntologyClass {name: 'Recipe'}) +MERGE (s)-[:RELATION {name: 'follows'}]->(t); +// Axiom Validations +// Axiom validation: KitchenStaff food_handler_certified eq True +MATCH (n:`KitchenStaff`) WHERE NOT (n.`food_handler_certified` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: WalkInFridge cold_holding_temp_c lte 5 +MATCH (n:`WalkInFridge`) WHERE NOT (n.`cold_holding_temp_c` <= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Freezer freezer_temp_c lte -18 +MATCH (n:`Freezer`) WHERE NOT (n.`freezer_temp_c` <= -18) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: HotHoldingUnit hot_holding_temp_c gte 60 +MATCH (n:`HotHoldingUnit`) WHERE NOT (n.`hot_holding_temp_c` >= 60) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Poultry poultry_core_temp_c gte 74 +MATCH (n:`Poultry`) WHERE NOT (n.`poultry_core_temp_c` >= 74) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Reheating reheat_temp_c gte 74 +MATCH (n:`Reheating`) WHERE NOT (n.`reheat_temp_c` >= 74) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall x (not Guest(x) and KitchenStaff(x)) +// forall x (not Ingredient(x) and Allergen(x)) +// forall x (not Dessert(x) and MainCourse(x)) +// forall b (FoodBatch(b) and gt(hours_in_danger_zone, 4) implies is_discarded = True) +// forall o (Order(o) and has_allergy_flag = True implies is_allergen_free_prepared = True) +// forall m (MenuItem(m) and is_available = True implies contains_allergen_declared = True) diff --git a/examples/domain_food_service.d2 b/examples/domain_food_service.d2 new file mode 100644 index 0000000..22276f7 --- /dev/null +++ b/examples/domain_food_service.d2 @@ -0,0 +1,215 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Person": { shape: class } +"Guest": { shape: class } +"KitchenStaff": { shape: class } +"Chef": { shape: class } +"SousChef": { shape: class } +"LineCook": { shape: class } +"Dishwasher": { shape: class } +"FrontOfHouseStaff": { shape: class } +"Server": { shape: class } +"Host": { shape: class } +"Manager": { shape: class } +"FoodSafetyOfficer": { shape: class } +"Restaurant": { shape: class } +"DiningRoom": { shape: class } +"Kitchen": { shape: class } +"Station": { shape: class } +"GrillStation": { shape: class } +"FryStation": { shape: class } +"SaladStation": { shape: class } +"PastryStation": { shape: class } +"AllergenFreeStation": { shape: class } +"ColdStorage": { shape: class } +"WalkInFridge": { shape: class } +"Freezer": { shape: class } +"DryStorage": { shape: class } +"HotHoldingUnit": { shape: class } +"Ingredient": { shape: class } +"Meat": { shape: class } +"Poultry": { shape: class } +"Seafood": { shape: class } +"Produce": { shape: class } +"Dairy": { shape: class } +"Grain": { shape: class } +"Egg": { shape: class } +"Nut": { shape: class } +"Spice": { shape: class } +"Allergen": { shape: class } +"PeanutAllergen": { shape: class } +"GlutenAllergen": { shape: class } +"MilkAllergen": { shape: class } +"ShellfishAllergen": { shape: class } +"EggAllergen": { shape: class } +"SesameAllergen": { shape: class } +"MenuItem": { shape: class } +"Appetizer": { shape: class } +"MainCourse": { shape: class } +"Dessert": { shape: class } +"Beverage": { shape: class } +"VegetarianItem": { shape: class } +"VeganItem": { shape: class } +"Menu": { shape: class } +"Recipe": { shape: class } +"AllergenLabel": { shape: class } +"Order": { shape: class } +"DineInOrder": { shape: class } +"TakeawayOrder": { shape: class } +"DeliveryOrder": { shape: class } +"OrderLine": { shape: class } +"AllergyNote": { shape: class } +"KitchenTicket": { shape: class } +"Payment": { shape: class } +"PreparationProcess": { shape: class } +"Cooking": { shape: class } +"Chilling": { shape: class } +"HotHolding": { shape: class } +"Reheating": { shape: class } +"Thawing": { shape: class } +"Plating": { shape: class } +"FoodBatch": { shape: class } +"TemperatureLog": { shape: class } +"CriticalControlPoint": { shape: class } +"CorrectiveAction": { shape: class } +"HealthInspection": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "Object" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Person" -> "Agent" +"Guest" -> "Person" +"KitchenStaff" -> "Person" +"Chef" -> "KitchenStaff" +"SousChef" -> "Chef" +"LineCook" -> "KitchenStaff" +"Dishwasher" -> "KitchenStaff" +"FrontOfHouseStaff" -> "Person" +"Server" -> "FrontOfHouseStaff" +"Host" -> "FrontOfHouseStaff" +"Manager" -> "FrontOfHouseStaff" +"FoodSafetyOfficer" -> "Role" +"Restaurant" -> "Site" +"DiningRoom" -> "Site" +"Kitchen" -> "Site" +"Station" -> "Site" +"GrillStation" -> "Station" +"FryStation" -> "Station" +"SaladStation" -> "Station" +"PastryStation" -> "Station" +"AllergenFreeStation" -> "Station" +"ColdStorage" -> "Site" +"WalkInFridge" -> "ColdStorage" +"Freezer" -> "ColdStorage" +"DryStorage" -> "Site" +"HotHoldingUnit" -> "Object" +"Ingredient" -> "MaterialEntity" +"Meat" -> "Ingredient" +"Poultry" -> "Meat" +"Seafood" -> "Ingredient" +"Produce" -> "Ingredient" +"Dairy" -> "Ingredient" +"Grain" -> "Ingredient" +"Egg" -> "Ingredient" +"Nut" -> "Ingredient" +"Spice" -> "Ingredient" +"Allergen" -> "Quality" +"PeanutAllergen" -> "Allergen" +"GlutenAllergen" -> "Allergen" +"MilkAllergen" -> "Allergen" +"ShellfishAllergen" -> "Allergen" +"EggAllergen" -> "Allergen" +"SesameAllergen" -> "Allergen" +"MenuItem" -> "InformationContentEntity" +"Appetizer" -> "MenuItem" +"MainCourse" -> "MenuItem" +"Dessert" -> "MenuItem" +"Beverage" -> "MenuItem" +"VegetarianItem" -> "MenuItem" +"VeganItem" -> "VegetarianItem" +"Menu" -> "InformationContentEntity" +"Recipe" -> "InformationContentEntity" +"AllergenLabel" -> "InformationContentEntity" +"Order" -> "InformationContentEntity" +"DineInOrder" -> "Order" +"TakeawayOrder" -> "Order" +"DeliveryOrder" -> "Order" +"OrderLine" -> "InformationContentEntity" +"AllergyNote" -> "InformationContentEntity" +"KitchenTicket" -> "InformationContentEntity" +"Payment" -> "Process" +"PreparationProcess" -> "Process" +"Cooking" -> "PreparationProcess" +"Chilling" -> "PreparationProcess" +"HotHolding" -> "PreparationProcess" +"Reheating" -> "PreparationProcess" +"Thawing" -> "PreparationProcess" +"Plating" -> "PreparationProcess" +"FoodBatch" -> "MaterialEntity" +"TemperatureLog" -> "InformationContentEntity" +"CriticalControlPoint" -> "InformationContentEntity" +"CorrectiveAction" -> "Process" +"HealthInspection" -> "Process" +"MenuItem"."price_cents": Integer +"MenuItem"."calories": Integer +"MenuItem"."is_available": Boolean +"MenuItem"."contains_allergen_declared": Boolean +"ColdStorage"."cold_holding_temp_c": Integer +"Freezer"."freezer_temp_c": Integer +"HotHoldingUnit"."hot_holding_temp_c": Integer +"Cooking"."core_cook_temp_c": Integer +"Reheating"."reheat_temp_c": Integer +"Poultry"."poultry_core_temp_c": Integer +"FoodBatch"."hours_in_danger_zone": Integer +"FoodBatch"."is_discarded": Boolean +"Ingredient"."shelf_life_days": Integer +"DineInOrder"."table_number": Integer +"DineInOrder"."party_size": Integer +"Order"."has_allergy_flag": Boolean +"Order"."is_allergen_free_prepared": Boolean +"Station"."station_capacity": Integer +"KitchenStaff"."food_handler_certified": Boolean +"MenuItem" -> "Ingredient": contains +"Ingredient" -> "Allergen": has_allergen +"AllergenLabel" -> "Allergen": lists_allergen +"AllergenLabel" -> "MenuItem": labels +"MenuItem" -> "Menu": appears_on +"MenuItem" -> "Station": prepared_by +"Order" -> "OrderLine": has_line +"OrderLine" -> "MenuItem": orders +"Order" -> "Guest": placed_by +"Order" -> "Server": served_by +"KitchenStaff" -> "Station": works_at +"FoodBatch" -> "ColdStorage": stored_in +"FoodBatch" -> "Ingredient": batch_of +"TemperatureLog" -> "FoodBatch": records +"CriticalControlPoint" -> "Station": monitors +"CriticalControlPoint" -> "CorrectiveAction": triggers +"MenuItem" -> "Recipe": follows +# WARNING: The following axioms could not be mapped to field constraints: +# forall x (not Guest(x) and KitchenStaff(x)) +# forall x (not Ingredient(x) and Allergen(x)) +# forall x (not Dessert(x) and MainCourse(x)) +# forall b (FoodBatch(b) and gt(hours_in_danger_zone, 4) implies is_discarded = True) +# forall o (Order(o) and has_allergy_flag = True implies is_allergen_free_prepared = True) +# forall m (MenuItem(m) and is_available = True implies contains_allergen_declared = True) diff --git a/examples/domain_food_service.d2.svg b/examples/domain_food_service.d2.svg new file mode 100644 index 0000000..db9925e --- /dev/null +++ b/examples/domain_food_service.d2.svg @@ -0,0 +1,118 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentSiteOccurrentProcessRoleFunctionQualityInformationContentEntityPersonGuestKitchenStaff+food_handler_certifiedBooleanChefSousChefLineCookDishwasherFrontOfHouseStaffServerHostManagerFoodSafetyOfficerRestaurantDiningRoomKitchenStation+station_capacityIntegerGrillStationFryStationSaladStationPastryStationAllergenFreeStationColdStorage+cold_holding_temp_cIntegerWalkInFridgeFreezer+freezer_temp_cIntegerDryStorageHotHoldingUnit+hot_holding_temp_cIntegerIngredient+shelf_life_daysIntegerMeatPoultry+poultry_core_temp_cIntegerSeafoodProduceDairyGrainEggNutSpiceAllergenPeanutAllergenGlutenAllergenMilkAllergenShellfishAllergenEggAllergenSesameAllergenMenuItem+price_centsInteger+caloriesInteger+is_availableBoolean+contains_allergen_declaredBooleanAppetizerMainCourseDessertBeverageVegetarianItemVeganItemMenuRecipeAllergenLabelOrder+has_allergy_flagBoolean+is_allergen_free_preparedBooleanDineInOrder+table_numberInteger+party_sizeIntegerTakeawayOrderDeliveryOrderOrderLineAllergyNoteKitchenTicketPaymentPreparationProcessCooking+core_cook_temp_cIntegerChillingHotHoldingReheating+reheat_temp_cIntegerThawingPlatingFoodBatch+hours_in_danger_zoneInteger+is_discardedBooleanTemperatureLogCriticalControlPointCorrectiveActionHealthInspection containshas_allergenlists_allergenlabelsappears_onprepared_byhas_lineordersplaced_byserved_byworks_atstored_inbatch_ofrecordsmonitorstriggersfollows + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_food_service.logic b/examples/domain_food_service.logic new file mode 100644 index 0000000..ea93920 --- /dev/null +++ b/examples/domain_food_service.logic @@ -0,0 +1,176 @@ +; ===================================================================== +; Domain: Food Service +; Models restaurant menu items, ingredients, allergens, orders, kitchen +; stations and HACCP food-safety temperature rules on a condensed BFO upper +; level. +; Axioms enforce: HACCP limits (cold holding at or below 5 C, hot holding +; at or above 60 C, poultry cook core temperature at least 74 C), +; allergen labelling rules, kitchen cross-contact separation and order +; integrity. +; ===================================================================== + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent Object) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- People --- +(def-concept Person Agent) +(def-concept Guest Person) +(def-concept KitchenStaff Person) +(def-concept Chef KitchenStaff) +(def-concept SousChef Chef) +(def-concept LineCook KitchenStaff) +(def-concept Dishwasher KitchenStaff) +(def-concept FrontOfHouseStaff Person) +(def-concept Server FrontOfHouseStaff) +(def-concept Host FrontOfHouseStaff) +(def-concept Manager FrontOfHouseStaff) +(def-concept FoodSafetyOfficer Role) + +; --- Premises and Stations --- +(def-concept Restaurant Site) +(def-concept DiningRoom Site) +(def-concept Kitchen Site) +(def-concept Station Site) +(def-concept GrillStation Station) +(def-concept FryStation Station) +(def-concept SaladStation Station) +(def-concept PastryStation Station) +(def-concept AllergenFreeStation Station) +(def-concept ColdStorage Site) +(def-concept WalkInFridge ColdStorage) +(def-concept Freezer ColdStorage) +(def-concept DryStorage Site) +(def-concept HotHoldingUnit Object) + +; --- Ingredients and Allergens --- +(def-concept Ingredient MaterialEntity) +(def-concept Meat Ingredient) +(def-concept Poultry Meat) +(def-concept Seafood Ingredient) +(def-concept Produce Ingredient) +(def-concept Dairy Ingredient) +(def-concept Grain Ingredient) +(def-concept Egg Ingredient) +(def-concept Nut Ingredient) +(def-concept Spice Ingredient) +(def-concept Allergen Quality) +(def-concept PeanutAllergen Allergen) +(def-concept GlutenAllergen Allergen) +(def-concept MilkAllergen Allergen) +(def-concept ShellfishAllergen Allergen) +(def-concept EggAllergen Allergen) +(def-concept SesameAllergen Allergen) + +; --- Menu --- +(def-concept MenuItem InformationContentEntity) +(def-concept Appetizer MenuItem) +(def-concept MainCourse MenuItem) +(def-concept Dessert MenuItem) +(def-concept Beverage MenuItem) +(def-concept VegetarianItem MenuItem) +(def-concept VeganItem VegetarianItem) +(def-concept Menu InformationContentEntity) +(def-concept Recipe InformationContentEntity) +(def-concept AllergenLabel InformationContentEntity) + +; --- Orders --- +(def-concept Order InformationContentEntity) +(def-concept DineInOrder Order) +(def-concept TakeawayOrder Order) +(def-concept DeliveryOrder Order) +(def-concept OrderLine InformationContentEntity) +(def-concept AllergyNote InformationContentEntity) +(def-concept KitchenTicket InformationContentEntity) +(def-concept Payment Process) + +; --- Food Preparation and Safety Processes --- +(def-concept PreparationProcess Process) +(def-concept Cooking PreparationProcess) +(def-concept Chilling PreparationProcess) +(def-concept HotHolding PreparationProcess) +(def-concept Reheating PreparationProcess) +(def-concept Thawing PreparationProcess) +(def-concept Plating PreparationProcess) +(def-concept FoodBatch MaterialEntity) +(def-concept TemperatureLog InformationContentEntity) +(def-concept CriticalControlPoint InformationContentEntity) +(def-concept CorrectiveAction Process) +(def-concept HealthInspection Process) + +; --- Properties --- +(def-property price_cents MenuItem Integer) +(def-property calories MenuItem Integer) +(def-property is_available MenuItem Boolean) +(def-property contains_allergen_declared MenuItem Boolean) +(def-property cold_holding_temp_c ColdStorage Integer) +(def-property freezer_temp_c Freezer Integer) +(def-property hot_holding_temp_c HotHoldingUnit Integer) +(def-property core_cook_temp_c Cooking Integer) +(def-property reheat_temp_c Reheating Integer) +(def-property poultry_core_temp_c Poultry Integer) +(def-property hours_in_danger_zone FoodBatch Integer) +(def-property is_discarded FoodBatch Boolean) +(def-property shelf_life_days Ingredient Integer) +(def-property table_number DineInOrder Integer) +(def-property party_size DineInOrder Integer) +(def-property has_allergy_flag Order Boolean) +(def-property is_allergen_free_prepared Order Boolean) +(def-property station_capacity Station Integer) +(def-property food_handler_certified KitchenStaff Boolean) + +; --- Relations --- +(def-relation contains MenuItem Ingredient :cardinality 1..*) +(def-relation has_allergen Ingredient Allergen :cardinality 0..*) +(def-relation lists_allergen AllergenLabel Allergen) +(def-relation labels AllergenLabel MenuItem) +(def-relation appears_on MenuItem Menu) +(def-relation prepared_by MenuItem Station) +(def-relation has_line Order OrderLine :cardinality 1..*) +(def-relation orders OrderLine MenuItem) +(def-relation placed_by Order Guest) +(def-relation served_by Order Server) +(def-relation works_at KitchenStaff Station) +(def-relation stored_in FoodBatch ColdStorage) +(def-relation batch_of FoodBatch Ingredient) +(def-relation records TemperatureLog FoodBatch) +(def-relation monitors CriticalControlPoint Station) +(def-relation triggers CriticalControlPoint CorrectiveAction) +(def-relation follows MenuItem Recipe) + +; --- Axioms --- +; 1. Integrity: guests are never kitchen staff +(forall (x) (not (and (Guest x) (KitchenStaff x)))) +; 2. Integrity: an ingredient is never an allergen declaration +(forall (x) (not (and (Ingredient x) (Allergen x)))) +; 3. Integrity: dessert and main course are distinct menu categories +(forall (x) (not (and (Dessert x) (MainCourse x)))) +; 4. HACCP: cold storage holds food at 5 C or below +(forall (c) (implies (WalkInFridge c) (lte cold_holding_temp_c 5))) +; 5. HACCP: freezers hold at minus 18 C or below +(forall (f) (implies (Freezer f) (lte freezer_temp_c -18))) +; 6. HACCP: hot holding at 60 C or above +(forall (h) (implies (HotHoldingUnit h) (gte hot_holding_temp_c 60))) +; 7. HACCP: poultry must reach a 74 C core temperature +(forall (p) (implies (Poultry p) (gte poultry_core_temp_c 74))) +; 8. HACCP: reheated food reaches 74 C +(forall (r) (implies (Reheating r) (gte reheat_temp_c 74))) +; 9. HACCP: food kept more than 4 hours in the danger zone must be discarded +(forall (b) (implies (and (FoodBatch b) (gt hours_in_danger_zone 4)) (eq is_discarded True))) +; 10. Allergens: orders with an allergy flag must be prepared allergen-free +(forall (o) (implies (and (Order o) (eq has_allergy_flag True)) (eq is_allergen_free_prepared True))) +; 11. Allergens: every menu item on offer has its allergens declared +(forall (m) (implies (and (MenuItem m) (eq is_available True)) (eq contains_allergen_declared True))) +; 12. Staff: kitchen staff must hold food-handler certification +(forall (k) (implies (KitchenStaff k) (eq food_handler_certified True))) diff --git a/examples/domain_food_service.mmd b/examples/domain_food_service.mmd new file mode 100644 index 0000000..1dcc8d0 --- /dev/null +++ b/examples/domain_food_service.mmd @@ -0,0 +1,216 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Person["Person"] + class Guest["Guest"] + class KitchenStaff["KitchenStaff"] + class Chef["Chef"] + class SousChef["SousChef"] + class LineCook["LineCook"] + class Dishwasher["Dishwasher"] + class FrontOfHouseStaff["FrontOfHouseStaff"] + class Server["Server"] + class Host["Host"] + class Manager["Manager"] + class FoodSafetyOfficer["FoodSafetyOfficer"] + class Restaurant["Restaurant"] + class DiningRoom["DiningRoom"] + class Kitchen["Kitchen"] + class Station["Station"] + class GrillStation["GrillStation"] + class FryStation["FryStation"] + class SaladStation["SaladStation"] + class PastryStation["PastryStation"] + class AllergenFreeStation["AllergenFreeStation"] + class ColdStorage["ColdStorage"] + class WalkInFridge["WalkInFridge"] + class Freezer["Freezer"] + class DryStorage["DryStorage"] + class HotHoldingUnit["HotHoldingUnit"] + class Ingredient["Ingredient"] + class Meat["Meat"] + class Poultry["Poultry"] + class Seafood["Seafood"] + class Produce["Produce"] + class Dairy["Dairy"] + class Grain["Grain"] + class Egg["Egg"] + class Nut["Nut"] + class Spice["Spice"] + class Allergen["Allergen"] + class PeanutAllergen["PeanutAllergen"] + class GlutenAllergen["GlutenAllergen"] + class MilkAllergen["MilkAllergen"] + class ShellfishAllergen["ShellfishAllergen"] + class EggAllergen["EggAllergen"] + class SesameAllergen["SesameAllergen"] + class MenuItem["MenuItem"] + class Appetizer["Appetizer"] + class MainCourse["MainCourse"] + class Dessert["Dessert"] + class Beverage["Beverage"] + class VegetarianItem["VegetarianItem"] + class VeganItem["VeganItem"] + class Menu["Menu"] + class Recipe["Recipe"] + class AllergenLabel["AllergenLabel"] + class Order["Order"] + class DineInOrder["DineInOrder"] + class TakeawayOrder["TakeawayOrder"] + class DeliveryOrder["DeliveryOrder"] + class OrderLine["OrderLine"] + class AllergyNote["AllergyNote"] + class KitchenTicket["KitchenTicket"] + class Payment["Payment"] + class PreparationProcess["PreparationProcess"] + class Cooking["Cooking"] + class Chilling["Chilling"] + class HotHolding["HotHolding"] + class Reheating["Reheating"] + class Thawing["Thawing"] + class Plating["Plating"] + class FoodBatch["FoodBatch"] + class TemperatureLog["TemperatureLog"] + class CriticalControlPoint["CriticalControlPoint"] + class CorrectiveAction["CorrectiveAction"] + class HealthInspection["HealthInspection"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Object <|-- Agent + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Agent <|-- Person + Person <|-- Guest + Person <|-- KitchenStaff + KitchenStaff <|-- Chef + Chef <|-- SousChef + KitchenStaff <|-- LineCook + KitchenStaff <|-- Dishwasher + Person <|-- FrontOfHouseStaff + FrontOfHouseStaff <|-- Server + FrontOfHouseStaff <|-- Host + FrontOfHouseStaff <|-- Manager + Role <|-- FoodSafetyOfficer + Site <|-- Restaurant + Site <|-- DiningRoom + Site <|-- Kitchen + Site <|-- Station + Station <|-- GrillStation + Station <|-- FryStation + Station <|-- SaladStation + Station <|-- PastryStation + Station <|-- AllergenFreeStation + Site <|-- ColdStorage + ColdStorage <|-- WalkInFridge + ColdStorage <|-- Freezer + Site <|-- DryStorage + Object <|-- HotHoldingUnit + MaterialEntity <|-- Ingredient + Ingredient <|-- Meat + Meat <|-- Poultry + Ingredient <|-- Seafood + Ingredient <|-- Produce + Ingredient <|-- Dairy + Ingredient <|-- Grain + Ingredient <|-- Egg + Ingredient <|-- Nut + Ingredient <|-- Spice + Quality <|-- Allergen + Allergen <|-- PeanutAllergen + Allergen <|-- GlutenAllergen + Allergen <|-- MilkAllergen + Allergen <|-- ShellfishAllergen + Allergen <|-- EggAllergen + Allergen <|-- SesameAllergen + InformationContentEntity <|-- MenuItem + MenuItem <|-- Appetizer + MenuItem <|-- MainCourse + MenuItem <|-- Dessert + MenuItem <|-- Beverage + MenuItem <|-- VegetarianItem + VegetarianItem <|-- VeganItem + InformationContentEntity <|-- Menu + InformationContentEntity <|-- Recipe + InformationContentEntity <|-- AllergenLabel + InformationContentEntity <|-- Order + Order <|-- DineInOrder + Order <|-- TakeawayOrder + Order <|-- DeliveryOrder + InformationContentEntity <|-- OrderLine + InformationContentEntity <|-- AllergyNote + InformationContentEntity <|-- KitchenTicket + Process <|-- Payment + Process <|-- PreparationProcess + PreparationProcess <|-- Cooking + PreparationProcess <|-- Chilling + PreparationProcess <|-- HotHolding + PreparationProcess <|-- Reheating + PreparationProcess <|-- Thawing + PreparationProcess <|-- Plating + MaterialEntity <|-- FoodBatch + InformationContentEntity <|-- TemperatureLog + InformationContentEntity <|-- CriticalControlPoint + Process <|-- CorrectiveAction + Process <|-- HealthInspection + MenuItem : +Integer price_cents + MenuItem : +Integer calories + MenuItem : +Boolean is_available + MenuItem : +Boolean contains_allergen_declared + ColdStorage : +Integer cold_holding_temp_c + Freezer : +Integer freezer_temp_c + HotHoldingUnit : +Integer hot_holding_temp_c + Cooking : +Integer core_cook_temp_c + Reheating : +Integer reheat_temp_c + Poultry : +Integer poultry_core_temp_c + FoodBatch : +Integer hours_in_danger_zone + FoodBatch : +Boolean is_discarded + Ingredient : +Integer shelf_life_days + DineInOrder : +Integer table_number + DineInOrder : +Integer party_size + Order : +Boolean has_allergy_flag + Order : +Boolean is_allergen_free_prepared + Station : +Integer station_capacity + KitchenStaff : +Boolean food_handler_certified + MenuItem --> Ingredient : contains + Ingredient --> Allergen : has_allergen + AllergenLabel --> Allergen : lists_allergen + AllergenLabel --> MenuItem : labels + MenuItem --> Menu : appears_on + MenuItem --> Station : prepared_by + Order --> OrderLine : has_line + OrderLine --> MenuItem : orders + Order --> Guest : placed_by + Order --> Server : served_by + KitchenStaff --> Station : works_at + FoodBatch --> ColdStorage : stored_in + FoodBatch --> Ingredient : batch_of + TemperatureLog --> FoodBatch : records + CriticalControlPoint --> Station : monitors + CriticalControlPoint --> CorrectiveAction : triggers + MenuItem --> Recipe : follows + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall x (not Guest(x) and KitchenStaff(x)) +%% forall x (not Ingredient(x) and Allergen(x)) +%% forall x (not Dessert(x) and MainCourse(x)) +%% forall b (FoodBatch(b) and gt(hours_in_danger_zone, 4) implies is_discarded = True) +%% forall o (Order(o) and has_allergy_flag = True implies is_allergen_free_prepared = True) +%% forall m (MenuItem(m) and is_available = True implies contains_allergen_declared = True) diff --git a/examples/domain_ics.cypher b/examples/domain_ics.cypher new file mode 100644 index 0000000..86e950a --- /dev/null +++ b/examples/domain_ics.cypher @@ -0,0 +1,309 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PurdueLevel'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Level0Process'}) +MERGE (p:OntologyClass {name: 'PurdueLevel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Level1BasicControl'}) +MERGE (p:OntologyClass {name: 'PurdueLevel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Level2Supervisory'}) +MERGE (p:OntologyClass {name: 'PurdueLevel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Level3SiteOperations'}) +MERGE (p:OntologyClass {name: 'PurdueLevel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Level35Dmz'}) +MERGE (p:OntologyClass {name: 'PurdueLevel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Level4Enterprise'}) +MERGE (p:OntologyClass {name: 'PurdueLevel'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PlantArea'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessUnit'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlZone'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyZone'}) +MERGE (p:OntologyClass {name: 'ControlZone'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FieldDevice'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sensor'}) +MERGE (p:OntologyClass {name: 'FieldDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PressureTransmitter'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TemperatureTransmitter'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LevelTransmitter'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FlowTransmitter'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GasDetector'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Actuator'}) +MERGE (p:OntologyClass {name: 'FieldDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlValve'}) +MERGE (p:OntologyClass {name: 'Actuator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ShutdownValve'}) +MERGE (p:OntologyClass {name: 'Actuator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MotorStarter'}) +MERGE (p:OntologyClass {name: 'Actuator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VariableFrequencyDrive'}) +MERGE (p:OntologyClass {name: 'Actuator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EmergencyStopButton'}) +MERGE (p:OntologyClass {name: 'FieldDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Controller'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Plc'}) +MERGE (p:OntologyClass {name: 'Controller'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Rtu'}) +MERGE (p:OntologyClass {name: 'Controller'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Dcs'}) +MERGE (p:OntologyClass {name: 'Controller'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyController'}) +MERGE (p:OntologyClass {name: 'Controller'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IoModule'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndustrialNetwork'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FieldbusSegment'}) +MERGE (p:OntologyClass {name: 'IndustrialNetwork'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlNetwork'}) +MERGE (p:OntologyClass {name: 'IndustrialNetwork'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FirewallConduit'}) +MERGE (p:OntologyClass {name: 'IndustrialNetwork'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Workstation'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ScadaServer'}) +MERGE (p:OntologyClass {name: 'Workstation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HmiStation'}) +MERGE (p:OntologyClass {name: 'Workstation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EngineeringWorkstation'}) +MERGE (p:OntologyClass {name: 'Workstation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Historian'}) +MERGE (p:OntologyClass {name: 'Workstation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlProgram'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LadderLogicProgram'}) +MERGE (p:OntologyClass {name: 'ControlProgram'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyProgram'}) +MERGE (p:OntologyClass {name: 'ControlProgram'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlLoop'}) +MERGE (p:OntologyClass {name: 'Function'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PidLoop'}) +MERGE (p:OntologyClass {name: 'ControlLoop'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyInstrumentedFunction'}) +MERGE (p:OntologyClass {name: 'Function'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Interlock'}) +MERGE (p:OntologyClass {name: 'SafetyInstrumentedFunction'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PermissiveInterlock'}) +MERGE (p:OntologyClass {name: 'Interlock'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProtectiveInterlock'}) +MERGE (p:OntologyClass {name: 'Interlock'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EmergencyShutdown'}) +MERGE (p:OntologyClass {name: 'SafetyInstrumentedFunction'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyInstrumentedSystem'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Setpoint'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessVariable'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AlarmLimit'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Alarm'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AdvisoryAlarm'}) +MERGE (p:OntologyClass {name: 'Alarm'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StandardAlarm'}) +MERGE (p:OntologyClass {name: 'Alarm'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CriticalAlarm'}) +MERGE (p:OntologyClass {name: 'Alarm'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Bypass'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ScanCycle'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessTrip'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProofTest'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FirmwareChange'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OperatorRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ShiftSupervisorRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlsEngineerRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyAuthorityRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Controller'}) +MERGE (t:OntologyClass {name: 'FieldDevice'}) +MERGE (s)-[:RELATION {name: 'controls'}]->(t); +MERGE (s:OntologyClass {name: 'Controller'}) +MERGE (t:OntologyClass {name: 'Sensor'}) +MERGE (s)-[:RELATION {name: 'reads_from'}]->(t); +MERGE (s:OntologyClass {name: 'ScadaServer'}) +MERGE (t:OntologyClass {name: 'Controller'}) +MERGE (s)-[:RELATION {name: 'supervises'}]->(t); +MERGE (s:OntologyClass {name: 'HmiStation'}) +MERGE (t:OntologyClass {name: 'ScadaServer'}) +MERGE (s)-[:RELATION {name: 'displays_on'}]->(t); +MERGE (s:OntologyClass {name: 'Controller'}) +MERGE (t:OntologyClass {name: 'PurdueLevel'}) +MERGE (s)-[:RELATION {name: 'resides_at_level'}]->(t); +MERGE (s:OntologyClass {name: 'Controller'}) +MERGE (t:OntologyClass {name: 'IndustrialNetwork'}) +MERGE (s)-[:RELATION {name: 'connected_to'}]->(t); +MERGE (s:OntologyClass {name: 'ShutdownValve'}) +MERGE (t:OntologyClass {name: 'ProcessUnit'}) +MERGE (s)-[:RELATION {name: 'protects'}]->(t); +MERGE (s:OntologyClass {name: 'Interlock'}) +MERGE (t:OntologyClass {name: 'ProcessTrip'}) +MERGE (s)-[:RELATION {name: 'initiates'}]->(t); +MERGE (s:OntologyClass {name: 'Sensor'}) +MERGE (t:OntologyClass {name: 'Alarm'}) +MERGE (s)-[:RELATION {name: 'raises'}]->(t); +MERGE (s:OntologyClass {name: 'Alarm'}) +MERGE (t:OntologyClass {name: 'OperatorRole'}) +MERGE (s)-[:RELATION {name: 'acknowledged_by'}]->(t); +MERGE (s:OntologyClass {name: 'Bypass'}) +MERGE (t:OntologyClass {name: 'Interlock'}) +MERGE (s)-[:RELATION {name: 'bypasses'}]->(t); +MERGE (s:OntologyClass {name: 'Bypass'}) +MERGE (t:OntologyClass {name: 'SafetyAuthorityRole'}) +MERGE (s)-[:RELATION {name: 'authorised_by'}]->(t); +MERGE (s:OntologyClass {name: 'Plc'}) +MERGE (t:OntologyClass {name: 'ControlProgram'}) +MERGE (s)-[:RELATION {name: 'executes'}]->(t); +MERGE (s:OntologyClass {name: 'FieldDevice'}) +MERGE (t:OntologyClass {name: 'ProcessUnit'}) +MERGE (s)-[:RELATION {name: 'located_in'}]->(t); +// Axiom Validations +// Axiom validation: Controller is_internet_facing eq False +MATCH (n:`Controller`) WHERE NOT (n.`is_internet_facing` = false) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Plc scan_time_ms gt 0 +MATCH (n:`Plc`) WHERE NOT (n.`scan_time_ms` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Plc scan_time_ms lt 500 +MATCH (n:`Plc`) WHERE NOT (n.`scan_time_ms` < 500) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SafetyInstrumentedFunction sil_level gte 1 +MATCH (n:`SafetyInstrumentedFunction`) WHERE NOT (n.`sil_level` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SafetyInstrumentedFunction sil_level lte 4 +MATCH (n:`SafetyInstrumentedFunction`) WHERE NOT (n.`sil_level` <= 4) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Setpoint setpoint_value gte 0 +MATCH (n:`Setpoint`) WHERE NOT (n.`setpoint_value` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Setpoint setpoint_value lte 10000 +MATCH (n:`Setpoint`) WHERE NOT (n.`setpoint_value` <= 10000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Alarm alarm_priority gte 1 +MATCH (n:`Alarm`) WHERE NOT (n.`alarm_priority` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Alarm alarm_priority lte 3 +MATCH (n:`Alarm`) WHERE NOT (n.`alarm_priority` <= 3) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: CriticalAlarm requires_acknowledgement eq True +MATCH (n:`CriticalAlarm`) WHERE NOT (n.`requires_acknowledgement` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Bypass bypass_duration_hours gt 0 +MATCH (n:`Bypass`) WHERE NOT (n.`bypass_duration_hours` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Bypass bypass_duration_hours lte 8 +MATCH (n:`Bypass`) WHERE NOT (n.`bypass_duration_hours` <= 8) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: FirmwareChange firmware_signed eq True +MATCH (n:`FirmwareChange`) WHERE NOT (n.`firmware_signed` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall c (SafetyController(c) implies not Plc(c)) +// forall b (Bypass(b) implies exists r (SafetyAuthorityRole(r) and authorised_by(b, r))) +// forall t (ProcessTrip(t) and is_tripped = True implies exists i (Interlock(i) and initiates(i, t))) +// forall x (Alarm(x) implies not Interlock(x)) diff --git a/examples/domain_ics.d2 b/examples/domain_ics.d2 new file mode 100644 index 0000000..961ce7c --- /dev/null +++ b/examples/domain_ics.d2 @@ -0,0 +1,193 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"PurdueLevel": { shape: class } +"Level0Process": { shape: class } +"Level1BasicControl": { shape: class } +"Level2Supervisory": { shape: class } +"Level3SiteOperations": { shape: class } +"Level35Dmz": { shape: class } +"Level4Enterprise": { shape: class } +"PlantArea": { shape: class } +"ProcessUnit": { shape: class } +"ControlZone": { shape: class } +"SafetyZone": { shape: class } +"FieldDevice": { shape: class } +"Sensor": { shape: class } +"PressureTransmitter": { shape: class } +"TemperatureTransmitter": { shape: class } +"LevelTransmitter": { shape: class } +"FlowTransmitter": { shape: class } +"GasDetector": { shape: class } +"Actuator": { shape: class } +"ControlValve": { shape: class } +"ShutdownValve": { shape: class } +"MotorStarter": { shape: class } +"VariableFrequencyDrive": { shape: class } +"EmergencyStopButton": { shape: class } +"Controller": { shape: class } +"Plc": { shape: class } +"Rtu": { shape: class } +"Dcs": { shape: class } +"SafetyController": { shape: class } +"IoModule": { shape: class } +"IndustrialNetwork": { shape: class } +"FieldbusSegment": { shape: class } +"ControlNetwork": { shape: class } +"FirewallConduit": { shape: class } +"Workstation": { shape: class } +"ScadaServer": { shape: class } +"HmiStation": { shape: class } +"EngineeringWorkstation": { shape: class } +"Historian": { shape: class } +"ControlProgram": { shape: class } +"LadderLogicProgram": { shape: class } +"SafetyProgram": { shape: class } +"ControlLoop": { shape: class } +"PidLoop": { shape: class } +"SafetyInstrumentedFunction": { shape: class } +"Interlock": { shape: class } +"PermissiveInterlock": { shape: class } +"ProtectiveInterlock": { shape: class } +"EmergencyShutdown": { shape: class } +"SafetyInstrumentedSystem": { shape: class } +"Setpoint": { shape: class } +"ProcessVariable": { shape: class } +"AlarmLimit": { shape: class } +"Alarm": { shape: class } +"AdvisoryAlarm": { shape: class } +"StandardAlarm": { shape: class } +"CriticalAlarm": { shape: class } +"Bypass": { shape: class } +"ScanCycle": { shape: class } +"ProcessTrip": { shape: class } +"ProofTest": { shape: class } +"FirmwareChange": { shape: class } +"OperatorRole": { shape: class } +"ShiftSupervisorRole": { shape: class } +"ControlsEngineerRole": { shape: class } +"SafetyAuthorityRole": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"PurdueLevel" -> "InformationContentEntity" +"Level0Process" -> "PurdueLevel" +"Level1BasicControl" -> "PurdueLevel" +"Level2Supervisory" -> "PurdueLevel" +"Level3SiteOperations" -> "PurdueLevel" +"Level35Dmz" -> "PurdueLevel" +"Level4Enterprise" -> "PurdueLevel" +"PlantArea" -> "Site" +"ProcessUnit" -> "Site" +"ControlZone" -> "Site" +"SafetyZone" -> "ControlZone" +"FieldDevice" -> "Object" +"Sensor" -> "FieldDevice" +"PressureTransmitter" -> "Sensor" +"TemperatureTransmitter" -> "Sensor" +"LevelTransmitter" -> "Sensor" +"FlowTransmitter" -> "Sensor" +"GasDetector" -> "Sensor" +"Actuator" -> "FieldDevice" +"ControlValve" -> "Actuator" +"ShutdownValve" -> "Actuator" +"MotorStarter" -> "Actuator" +"VariableFrequencyDrive" -> "Actuator" +"EmergencyStopButton" -> "FieldDevice" +"Controller" -> "Object" +"Plc" -> "Controller" +"Rtu" -> "Controller" +"Dcs" -> "Controller" +"SafetyController" -> "Controller" +"IoModule" -> "Object" +"IndustrialNetwork" -> "Object" +"FieldbusSegment" -> "IndustrialNetwork" +"ControlNetwork" -> "IndustrialNetwork" +"FirewallConduit" -> "IndustrialNetwork" +"Workstation" -> "Object" +"ScadaServer" -> "Workstation" +"HmiStation" -> "Workstation" +"EngineeringWorkstation" -> "Workstation" +"Historian" -> "Workstation" +"ControlProgram" -> "InformationContentEntity" +"LadderLogicProgram" -> "ControlProgram" +"SafetyProgram" -> "ControlProgram" +"ControlLoop" -> "Function" +"PidLoop" -> "ControlLoop" +"SafetyInstrumentedFunction" -> "Function" +"Interlock" -> "SafetyInstrumentedFunction" +"PermissiveInterlock" -> "Interlock" +"ProtectiveInterlock" -> "Interlock" +"EmergencyShutdown" -> "SafetyInstrumentedFunction" +"SafetyInstrumentedSystem" -> "InformationContentEntity" +"Setpoint" -> "Quality" +"ProcessVariable" -> "Quality" +"AlarmLimit" -> "Quality" +"Alarm" -> "InformationContentEntity" +"AdvisoryAlarm" -> "Alarm" +"StandardAlarm" -> "Alarm" +"CriticalAlarm" -> "Alarm" +"Bypass" -> "InformationContentEntity" +"ScanCycle" -> "Process" +"ProcessTrip" -> "Process" +"ProofTest" -> "Process" +"FirmwareChange" -> "Process" +"OperatorRole" -> "Role" +"ShiftSupervisorRole" -> "Role" +"ControlsEngineerRole" -> "Role" +"SafetyAuthorityRole" -> "Role" +"FieldDevice"."tag_name": String +"Plc"."scan_time_ms": Integer +"Setpoint"."setpoint_value": Integer +"Setpoint"."setpoint_low_limit": Integer +"Setpoint"."setpoint_high_limit": Integer +"ProcessVariable"."process_value": Integer +"AlarmLimit"."high_high_limit": Integer +"Alarm"."alarm_priority": Integer +"Alarm"."requires_acknowledgement": Boolean +"SafetyInstrumentedFunction"."sil_level": Integer +"SafetyInstrumentedFunction"."proof_test_interval_months": Integer +"ProcessTrip"."is_tripped": Boolean +"Interlock"."is_bypassed": Boolean +"Bypass"."bypass_duration_hours": Integer +"Controller"."is_remote_access_enabled": Boolean +"Controller"."is_internet_facing": Boolean +"Plc"."key_switch_in_run": Boolean +"FirmwareChange"."firmware_signed": Boolean +"Controller" -> "FieldDevice": controls +"Controller" -> "Sensor": reads_from +"ScadaServer" -> "Controller": supervises +"HmiStation" -> "ScadaServer": displays_on +"Controller" -> "PurdueLevel": resides_at_level +"Controller" -> "IndustrialNetwork": connected_to +"ShutdownValve" -> "ProcessUnit": protects +"Interlock" -> "ProcessTrip": initiates +"Sensor" -> "Alarm": raises +"Alarm" -> "OperatorRole": acknowledged_by +"Bypass" -> "Interlock": bypasses +"Bypass" -> "SafetyAuthorityRole": authorised_by +"Plc" -> "ControlProgram": executes +"FieldDevice" -> "ProcessUnit": located_in +# WARNING: The following axioms could not be mapped to field constraints: +# forall c (SafetyController(c) implies not Plc(c)) +# forall b (Bypass(b) implies exists r (SafetyAuthorityRole(r) and authorised_by(b, r))) +# forall t (ProcessTrip(t) and is_tripped = True implies exists i (Interlock(i) and initiates(i, t))) +# forall x (Alarm(x) implies not Interlock(x)) diff --git a/examples/domain_ics.d2.svg b/examples/domain_ics.d2.svg new file mode 100644 index 0000000..8078ac9 --- /dev/null +++ b/examples/domain_ics.d2.svg @@ -0,0 +1,115 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectSiteOccurrentProcessRoleFunctionQualityInformationContentEntityPurdueLevelLevel0ProcessLevel1BasicControlLevel2SupervisoryLevel3SiteOperationsLevel35DmzLevel4EnterprisePlantAreaProcessUnitControlZoneSafetyZoneFieldDevice+tag_nameStringSensorPressureTransmitterTemperatureTransmitterLevelTransmitterFlowTransmitterGasDetectorActuatorControlValveShutdownValveMotorStarterVariableFrequencyDriveEmergencyStopButtonController+is_remote_access_enabledBoolean+is_internet_facingBooleanPlc+scan_time_msInteger+key_switch_in_runBooleanRtuDcsSafetyControllerIoModuleIndustrialNetworkFieldbusSegmentControlNetworkFirewallConduitWorkstationScadaServerHmiStationEngineeringWorkstationHistorianControlProgramLadderLogicProgramSafetyProgramControlLoopPidLoopSafetyInstrumentedFunction+sil_levelInteger+proof_test_interval_monthsIntegerInterlock+is_bypassedBooleanPermissiveInterlockProtectiveInterlockEmergencyShutdownSafetyInstrumentedSystemSetpoint+setpoint_valueInteger+setpoint_low_limitInteger+setpoint_high_limitIntegerProcessVariable+process_valueIntegerAlarmLimit+high_high_limitIntegerAlarm+alarm_priorityInteger+requires_acknowledgementBooleanAdvisoryAlarmStandardAlarmCriticalAlarmBypass+bypass_duration_hoursIntegerScanCycleProcessTrip+is_trippedBooleanProofTestFirmwareChange+firmware_signedBooleanOperatorRoleShiftSupervisorRoleControlsEngineerRoleSafetyAuthorityRole controlsreads_fromsupervisesdisplays_onresides_at_levelconnected_toprotectsinitiatesraisesacknowledged_bybypassesauthorised_byexecuteslocated_in + + + + + + + + + + + + + + + + diff --git a/examples/domain_ics.logic b/examples/domain_ics.logic new file mode 100644 index 0000000..1448cee --- /dev/null +++ b/examples/domain_ics.logic @@ -0,0 +1,195 @@ +; --- Industrial Control Systems (ICS / OT) --- +; Models PLCs, SCADA/HMI, Purdue-model network levels, safety instrumented +; systems, setpoints, alarms and interlocks. +; Axioms enforce: a safe operating envelope for setpoints, SIS independence +; from the basic process control system, Purdue-level segmentation, alarm +; handling duties, and interlock/bypass authorisation rules. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Purdue Reference Model Levels --- +(def-concept PurdueLevel InformationContentEntity) +(def-concept Level0Process PurdueLevel) +(def-concept Level1BasicControl PurdueLevel) +(def-concept Level2Supervisory PurdueLevel) +(def-concept Level3SiteOperations PurdueLevel) +(def-concept Level35Dmz PurdueLevel) +(def-concept Level4Enterprise PurdueLevel) + +; --- Plant Structure --- +(def-concept PlantArea Site) +(def-concept ProcessUnit Site) +(def-concept ControlZone Site) +(def-concept SafetyZone ControlZone) + +; --- Field Devices --- +(def-concept FieldDevice Object) +(def-concept Sensor FieldDevice) +(def-concept PressureTransmitter Sensor) +(def-concept TemperatureTransmitter Sensor) +(def-concept LevelTransmitter Sensor) +(def-concept FlowTransmitter Sensor) +(def-concept GasDetector Sensor) +(def-concept Actuator FieldDevice) +(def-concept ControlValve Actuator) +(def-concept ShutdownValve Actuator) +(def-concept MotorStarter Actuator) +(def-concept VariableFrequencyDrive Actuator) +(def-concept EmergencyStopButton FieldDevice) + +; --- Controllers and Networks --- +(def-concept Controller Object) +(def-concept Plc Controller) +(def-concept Rtu Controller) +(def-concept Dcs Controller) +(def-concept SafetyController Controller) +(def-concept IoModule Object) +(def-concept IndustrialNetwork Object) +(def-concept FieldbusSegment IndustrialNetwork) +(def-concept ControlNetwork IndustrialNetwork) +(def-concept FirewallConduit IndustrialNetwork) + +; --- Supervisory Software and Workstations --- +(def-concept Workstation Object) +(def-concept ScadaServer Workstation) +(def-concept HmiStation Workstation) +(def-concept EngineeringWorkstation Workstation) +(def-concept Historian Workstation) +(def-concept ControlProgram InformationContentEntity) +(def-concept LadderLogicProgram ControlProgram) +(def-concept SafetyProgram ControlProgram) + +; --- Control and Safety Functions --- +(def-concept ControlLoop Function) +(def-concept PidLoop ControlLoop) +(def-concept SafetyInstrumentedFunction Function) +(def-concept Interlock SafetyInstrumentedFunction) +(def-concept PermissiveInterlock Interlock) +(def-concept ProtectiveInterlock Interlock) +(def-concept EmergencyShutdown SafetyInstrumentedFunction) +(def-concept SafetyInstrumentedSystem InformationContentEntity) + +; --- Setpoints, Limits and Alarms --- +(def-concept Setpoint Quality) +(def-concept ProcessVariable Quality) +(def-concept AlarmLimit Quality) +(def-concept Alarm InformationContentEntity) +(def-concept AdvisoryAlarm Alarm) +(def-concept StandardAlarm Alarm) +(def-concept CriticalAlarm Alarm) +(def-concept Bypass InformationContentEntity) + +; --- Processes and Roles --- +(def-concept ScanCycle Process) +(def-concept ProcessTrip Process) +(def-concept ProofTest Process) +(def-concept FirmwareChange Process) +(def-concept OperatorRole Role) +(def-concept ShiftSupervisorRole Role) +(def-concept ControlsEngineerRole Role) +(def-concept SafetyAuthorityRole Role) + +; --- Relations --- +(def-relation controls Controller FieldDevice :cardinality 0..*) +(def-relation reads_from Controller Sensor :cardinality 0..*) +(def-relation supervises ScadaServer Controller :cardinality 0..*) +(def-relation displays_on HmiStation ScadaServer) +(def-relation resides_at_level Controller PurdueLevel :cardinality 1..1) +(def-relation connected_to Controller IndustrialNetwork :cardinality 1..*) +(def-relation protects ShutdownValve ProcessUnit) +(def-relation initiates Interlock ProcessTrip) +(def-relation raises Sensor Alarm :cardinality 0..*) +(def-relation acknowledged_by Alarm OperatorRole) +(def-relation bypasses Bypass Interlock) +(def-relation authorised_by Bypass SafetyAuthorityRole :cardinality 1..1) +(def-relation executes Plc ControlProgram :cardinality 1..*) +(def-relation located_in FieldDevice ProcessUnit) + +; --- Properties --- +(def-property tag_name FieldDevice String :cardinality 1..1) +(def-property scan_time_ms Plc Integer) +(def-property setpoint_value Setpoint Integer) +(def-property setpoint_low_limit Setpoint Integer) +(def-property setpoint_high_limit Setpoint Integer) +(def-property process_value ProcessVariable Integer) +(def-property high_high_limit AlarmLimit Integer) +(def-property alarm_priority Alarm Integer) +(def-property requires_acknowledgement Alarm Boolean) +(def-property sil_level SafetyInstrumentedFunction Integer) +(def-property proof_test_interval_months SafetyInstrumentedFunction Integer) +(def-property is_tripped ProcessTrip Boolean) +(def-property is_bypassed Interlock Boolean) +(def-property bypass_duration_hours Bypass Integer) +(def-property is_remote_access_enabled Controller Boolean) +(def-property is_internet_facing Controller Boolean) +(def-property key_switch_in_run Plc Boolean) +(def-property firmware_signed FirmwareChange Boolean) + +; --- Axioms --- + +; 1. Safety integrity levels range from SIL 1 to SIL 4 +(forall (f) + (implies (SafetyInstrumentedFunction f) + (and (gte sil_level 1) (lte sil_level 4)))) + +; 2. Operating envelope: setpoint is within the scaled engineering range 0..10000 +(forall (s) + (implies (Setpoint s) + (and (gte setpoint_value 0) (lte setpoint_value 10000)))) + +; 3. Scan cycle bound: PLC scan time must be positive and under 500 ms +(forall (p) + (implies (Plc p) + (and (gt scan_time_ms 0) (lt scan_time_ms 500)))) + +; 4. SIS independence: a safety controller is never a basic-process PLC +(forall (c) + (implies (SafetyController c) (not (Plc c)))) + +; 5. A critical alarm always demands operator acknowledgement +(forall (a) + (implies (CriticalAlarm a) (eq requires_acknowledgement True))) + +; 6. Alarm priority is ranked 1 (most urgent) to 3 +(forall (a) + (implies (Alarm a) + (and (gte alarm_priority 1) (lte alarm_priority 3)))) + +; 7. Segmentation: no controller is ever directly internet facing +(forall (c) + (implies (Controller c) (eq is_internet_facing False))) + +; 8. Every bypass of an interlock needs an authorising safety authority +(forall (b) + (implies (Bypass b) + (exists (r) (and (SafetyAuthorityRole r) (authorised_by b r))))) + +; 9. A bypass is time boxed to at most 8 hours +(forall (b) + (implies (Bypass b) + (and (gt bypass_duration_hours 0) (lte bypass_duration_hours 8)))) + +; 10. A tripped process must have an interlock that initiated the trip +(forall (t) + (implies (and (ProcessTrip t) (eq is_tripped True)) + (exists (i) (and (Interlock i) (initiates i t))))) + +; 11. Firmware changes on controllers must be signed +(forall (f) + (implies (FirmwareChange f) (eq firmware_signed True))) + +; 12. Alarms, interlocks and trips are distinct kinds of thing +(forall (x) + (implies (Alarm x) (not (Interlock x)))) diff --git a/examples/domain_ics.mmd b/examples/domain_ics.mmd new file mode 100644 index 0000000..0628368 --- /dev/null +++ b/examples/domain_ics.mmd @@ -0,0 +1,194 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class PurdueLevel["PurdueLevel"] + class Level0Process["Level0Process"] + class Level1BasicControl["Level1BasicControl"] + class Level2Supervisory["Level2Supervisory"] + class Level3SiteOperations["Level3SiteOperations"] + class Level35Dmz["Level35Dmz"] + class Level4Enterprise["Level4Enterprise"] + class PlantArea["PlantArea"] + class ProcessUnit["ProcessUnit"] + class ControlZone["ControlZone"] + class SafetyZone["SafetyZone"] + class FieldDevice["FieldDevice"] + class Sensor["Sensor"] + class PressureTransmitter["PressureTransmitter"] + class TemperatureTransmitter["TemperatureTransmitter"] + class LevelTransmitter["LevelTransmitter"] + class FlowTransmitter["FlowTransmitter"] + class GasDetector["GasDetector"] + class Actuator["Actuator"] + class ControlValve["ControlValve"] + class ShutdownValve["ShutdownValve"] + class MotorStarter["MotorStarter"] + class VariableFrequencyDrive["VariableFrequencyDrive"] + class EmergencyStopButton["EmergencyStopButton"] + class Controller["Controller"] + class Plc["Plc"] + class Rtu["Rtu"] + class Dcs["Dcs"] + class SafetyController["SafetyController"] + class IoModule["IoModule"] + class IndustrialNetwork["IndustrialNetwork"] + class FieldbusSegment["FieldbusSegment"] + class ControlNetwork["ControlNetwork"] + class FirewallConduit["FirewallConduit"] + class Workstation["Workstation"] + class ScadaServer["ScadaServer"] + class HmiStation["HmiStation"] + class EngineeringWorkstation["EngineeringWorkstation"] + class Historian["Historian"] + class ControlProgram["ControlProgram"] + class LadderLogicProgram["LadderLogicProgram"] + class SafetyProgram["SafetyProgram"] + class ControlLoop["ControlLoop"] + class PidLoop["PidLoop"] + class SafetyInstrumentedFunction["SafetyInstrumentedFunction"] + class Interlock["Interlock"] + class PermissiveInterlock["PermissiveInterlock"] + class ProtectiveInterlock["ProtectiveInterlock"] + class EmergencyShutdown["EmergencyShutdown"] + class SafetyInstrumentedSystem["SafetyInstrumentedSystem"] + class Setpoint["Setpoint"] + class ProcessVariable["ProcessVariable"] + class AlarmLimit["AlarmLimit"] + class Alarm["Alarm"] + class AdvisoryAlarm["AdvisoryAlarm"] + class StandardAlarm["StandardAlarm"] + class CriticalAlarm["CriticalAlarm"] + class Bypass["Bypass"] + class ScanCycle["ScanCycle"] + class ProcessTrip["ProcessTrip"] + class ProofTest["ProofTest"] + class FirmwareChange["FirmwareChange"] + class OperatorRole["OperatorRole"] + class ShiftSupervisorRole["ShiftSupervisorRole"] + class ControlsEngineerRole["ControlsEngineerRole"] + class SafetyAuthorityRole["SafetyAuthorityRole"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + InformationContentEntity <|-- PurdueLevel + PurdueLevel <|-- Level0Process + PurdueLevel <|-- Level1BasicControl + PurdueLevel <|-- Level2Supervisory + PurdueLevel <|-- Level3SiteOperations + PurdueLevel <|-- Level35Dmz + PurdueLevel <|-- Level4Enterprise + Site <|-- PlantArea + Site <|-- ProcessUnit + Site <|-- ControlZone + ControlZone <|-- SafetyZone + Object <|-- FieldDevice + FieldDevice <|-- Sensor + Sensor <|-- PressureTransmitter + Sensor <|-- TemperatureTransmitter + Sensor <|-- LevelTransmitter + Sensor <|-- FlowTransmitter + Sensor <|-- GasDetector + FieldDevice <|-- Actuator + Actuator <|-- ControlValve + Actuator <|-- ShutdownValve + Actuator <|-- MotorStarter + Actuator <|-- VariableFrequencyDrive + FieldDevice <|-- EmergencyStopButton + Object <|-- Controller + Controller <|-- Plc + Controller <|-- Rtu + Controller <|-- Dcs + Controller <|-- SafetyController + Object <|-- IoModule + Object <|-- IndustrialNetwork + IndustrialNetwork <|-- FieldbusSegment + IndustrialNetwork <|-- ControlNetwork + IndustrialNetwork <|-- FirewallConduit + Object <|-- Workstation + Workstation <|-- ScadaServer + Workstation <|-- HmiStation + Workstation <|-- EngineeringWorkstation + Workstation <|-- Historian + InformationContentEntity <|-- ControlProgram + ControlProgram <|-- LadderLogicProgram + ControlProgram <|-- SafetyProgram + Function <|-- ControlLoop + ControlLoop <|-- PidLoop + Function <|-- SafetyInstrumentedFunction + SafetyInstrumentedFunction <|-- Interlock + Interlock <|-- PermissiveInterlock + Interlock <|-- ProtectiveInterlock + SafetyInstrumentedFunction <|-- EmergencyShutdown + InformationContentEntity <|-- SafetyInstrumentedSystem + Quality <|-- Setpoint + Quality <|-- ProcessVariable + Quality <|-- AlarmLimit + InformationContentEntity <|-- Alarm + Alarm <|-- AdvisoryAlarm + Alarm <|-- StandardAlarm + Alarm <|-- CriticalAlarm + InformationContentEntity <|-- Bypass + Process <|-- ScanCycle + Process <|-- ProcessTrip + Process <|-- ProofTest + Process <|-- FirmwareChange + Role <|-- OperatorRole + Role <|-- ShiftSupervisorRole + Role <|-- ControlsEngineerRole + Role <|-- SafetyAuthorityRole + FieldDevice : +String tag_name + Plc : +Integer scan_time_ms + Setpoint : +Integer setpoint_value + Setpoint : +Integer setpoint_low_limit + Setpoint : +Integer setpoint_high_limit + ProcessVariable : +Integer process_value + AlarmLimit : +Integer high_high_limit + Alarm : +Integer alarm_priority + Alarm : +Boolean requires_acknowledgement + SafetyInstrumentedFunction : +Integer sil_level + SafetyInstrumentedFunction : +Integer proof_test_interval_months + ProcessTrip : +Boolean is_tripped + Interlock : +Boolean is_bypassed + Bypass : +Integer bypass_duration_hours + Controller : +Boolean is_remote_access_enabled + Controller : +Boolean is_internet_facing + Plc : +Boolean key_switch_in_run + FirmwareChange : +Boolean firmware_signed + Controller --> FieldDevice : controls + Controller --> Sensor : reads_from + ScadaServer --> Controller : supervises + HmiStation --> ScadaServer : displays_on + Controller --> PurdueLevel : resides_at_level + Controller --> IndustrialNetwork : connected_to + ShutdownValve --> ProcessUnit : protects + Interlock --> ProcessTrip : initiates + Sensor --> Alarm : raises + Alarm --> OperatorRole : acknowledged_by + Bypass --> Interlock : bypasses + Bypass --> SafetyAuthorityRole : authorised_by + Plc --> ControlProgram : executes + FieldDevice --> ProcessUnit : located_in + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall c (SafetyController(c) implies not Plc(c)) +%% forall b (Bypass(b) implies exists r (SafetyAuthorityRole(r) and authorised_by(b, r))) +%% forall t (ProcessTrip(t) and is_tripped = True implies exists i (Interlock(i) and initiates(i, t))) +%% forall x (Alarm(x) implies not Interlock(x)) diff --git a/examples/domain_iiot.cypher b/examples/domain_iiot.cypher new file mode 100644 index 0000000..b9b0c50 --- /dev/null +++ b/examples/domain_iiot.cypher @@ -0,0 +1,328 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Asset'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RotatingAsset'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Motor'}) +MERGE (p:OntologyClass {name: 'RotatingAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pump'}) +MERGE (p:OntologyClass {name: 'RotatingAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Compressor'}) +MERGE (p:OntologyClass {name: 'RotatingAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Fan'}) +MERGE (p:OntologyClass {name: 'RotatingAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Gearbox'}) +MERGE (p:OntologyClass {name: 'RotatingAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StaticAsset'}) +MERGE (p:OntologyClass {name: 'Asset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HeatExchanger'}) +MERGE (p:OntologyClass {name: 'StaticAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tank'}) +MERGE (p:OntologyClass {name: 'StaticAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pipeline'}) +MERGE (p:OntologyClass {name: 'StaticAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Component'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Bearing'}) +MERGE (p:OntologyClass {name: 'Component'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Seal'}) +MERGE (p:OntologyClass {name: 'Component'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Impeller'}) +MERGE (p:OntologyClass {name: 'Component'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sensor'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VibrationSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TemperatureSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PressureSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CurrentSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AcousticSensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OilQualitySensor'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EdgeGateway'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProtocolBridge'}) +MERGE (p:OntologyClass {name: 'EdgeGateway'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EdgeAnalyticsNode'}) +MERGE (p:OntologyClass {name: 'EdgeGateway'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PlcController'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MessageBroker'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MqttBroker'}) +MERGE (p:OntologyClass {name: 'MessageBroker'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OpcUaServer'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CloudPlatform'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TimeSeriesStore'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NetworkLink'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CellularLink'}) +MERGE (p:OntologyClass {name: 'NetworkLink'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EthernetLink'}) +MERGE (p:OntologyClass {name: 'NetworkLink'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WirelessMeshLink'}) +MERGE (p:OntologyClass {name: 'NetworkLink'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TelemetryMessage'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MqttMessage'}) +MERGE (p:OntologyClass {name: 'TelemetryMessage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OpcUaDataChange'}) +MERGE (p:OntologyClass {name: 'TelemetryMessage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Topic'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'NodeId'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PayloadSchema'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Measurement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Waveform'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ScalarReading'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HealthIndicator'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FeatureVector'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AnomalyModel'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RemainingUsefulLifeEstimate'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Alert'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConditionAlert'}) +MERGE (p:OntologyClass {name: 'Alert'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConnectivityAlert'}) +MERGE (p:OntologyClass {name: 'Alert'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WorkOrder'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PredictiveWorkOrder'}) +MERGE (p:OntologyClass {name: 'WorkOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CorrectiveWorkOrder'}) +MERGE (p:OntologyClass {name: 'WorkOrder'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Certificate'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Telemetry'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sampling'}) +MERGE (p:OntologyClass {name: 'Telemetry'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Publication'}) +MERGE (p:OntologyClass {name: 'Telemetry'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StoreAndForward'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InferenceRun'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Degradation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaintenanceActivity'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InspectionActivity'}) +MERGE (p:OntologyClass {name: 'MaintenanceActivity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RepairActivity'}) +MERGE (p:OntologyClass {name: 'MaintenanceActivity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReliabilityEngineerRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaintenanceTechnicianRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataEngineerRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Sensor'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'monitors'}]->(t); +MERGE (s:OntologyClass {name: 'Sensor'}) +MERGE (t:OntologyClass {name: 'Component'}) +MERGE (s)-[:RELATION {name: 'attached_to'}]->(t); +MERGE (s:OntologyClass {name: 'Component'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'part_of'}]->(t); +MERGE (s:OntologyClass {name: 'EdgeGateway'}) +MERGE (t:OntologyClass {name: 'Sensor'}) +MERGE (s)-[:RELATION {name: 'collects_from'}]->(t); +MERGE (s:OntologyClass {name: 'EdgeGateway'}) +MERGE (t:OntologyClass {name: 'MessageBroker'}) +MERGE (s)-[:RELATION {name: 'publishes_to'}]->(t); +MERGE (s:OntologyClass {name: 'OpcUaServer'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'exposes'}]->(t); +MERGE (s:OntologyClass {name: 'MessageBroker'}) +MERGE (t:OntologyClass {name: 'CloudPlatform'}) +MERGE (s)-[:RELATION {name: 'reports_to'}]->(t); +MERGE (s:OntologyClass {name: 'TelemetryMessage'}) +MERGE (t:OntologyClass {name: 'Sensor'}) +MERGE (s)-[:RELATION {name: 'emitted_by'}]->(t); +MERGE (s:OntologyClass {name: 'TelemetryMessage'}) +MERGE (t:OntologyClass {name: 'Topic'}) +MERGE (s)-[:RELATION {name: 'published_on'}]->(t); +MERGE (s:OntologyClass {name: 'TelemetryMessage'}) +MERGE (t:OntologyClass {name: 'PayloadSchema'}) +MERGE (s)-[:RELATION {name: 'conforms_to'}]->(t); +MERGE (s:OntologyClass {name: 'FeatureVector'}) +MERGE (t:OntologyClass {name: 'Measurement'}) +MERGE (s)-[:RELATION {name: 'derived_from'}]->(t); +MERGE (s:OntologyClass {name: 'HealthIndicator'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'scores'}]->(t); +MERGE (s:OntologyClass {name: 'RemainingUsefulLifeEstimate'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'predicts'}]->(t); +MERGE (s:OntologyClass {name: 'Alert'}) +MERGE (t:OntologyClass {name: 'WorkOrder'}) +MERGE (s)-[:RELATION {name: 'triggers'}]->(t); +MERGE (s:OntologyClass {name: 'Alert'}) +MERGE (t:OntologyClass {name: 'Asset'}) +MERGE (s)-[:RELATION {name: 'raised_for'}]->(t); +MERGE (s:OntologyClass {name: 'WorkOrder'}) +MERGE (t:OntologyClass {name: 'MaintenanceTechnicianRole'}) +MERGE (s)-[:RELATION {name: 'assigned_to'}]->(t); +MERGE (s:OntologyClass {name: 'EdgeGateway'}) +MERGE (t:OntologyClass {name: 'Certificate'}) +MERGE (s)-[:RELATION {name: 'authenticated_with'}]->(t); +MERGE (s:OntologyClass {name: 'EdgeGateway'}) +MERGE (t:OntologyClass {name: 'NetworkLink'}) +MERGE (s)-[:RELATION {name: 'uplink'}]->(t); +// Axiom Validations +// Axiom validation: Sensor sampling_rate_hz gt 0 +MATCH (n:`Sensor`) WHERE NOT (n.`sampling_rate_hz` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: EdgeGateway buffered_msgs gte 0 +MATCH (n:`EdgeGateway`) WHERE NOT (n.`buffered_msgs` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: EdgeGateway buffered_msgs lte 1000000 +MATCH (n:`EdgeGateway`) WHERE NOT (n.`buffered_msgs` <= 1000000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: TelemetryMessage is_encrypted_in_transit eq True +MATCH (n:`TelemetryMessage`) WHERE NOT (n.`is_encrypted_in_transit` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: MqttMessage qos_level gte 0 +MATCH (n:`MqttMessage`) WHERE NOT (n.`qos_level` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: MqttMessage qos_level lte 2 +MATCH (n:`MqttMessage`) WHERE NOT (n.`qos_level` <= 2) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Measurement quality_code gte 0 +MATCH (n:`Measurement`) WHERE NOT (n.`quality_code` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Measurement quality_code lte 3 +MATCH (n:`Measurement`) WHERE NOT (n.`quality_code` <= 3) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: HealthIndicator health_score gte 0 +MATCH (n:`HealthIndicator`) WHERE NOT (n.`health_score` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: HealthIndicator health_score lte 100 +MATCH (n:`HealthIndicator`) WHERE NOT (n.`health_score` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: RemainingUsefulLifeEstimate rul_hours gte 0 +MATCH (n:`RemainingUsefulLifeEstimate`) WHERE NOT (n.`rul_hours` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: RemainingUsefulLifeEstimate confidence_pct gte 0 +MATCH (n:`RemainingUsefulLifeEstimate`) WHERE NOT (n.`confidence_pct` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: RemainingUsefulLifeEstimate confidence_pct lte 100 +MATCH (n:`RemainingUsefulLifeEstimate`) WHERE NOT (n.`confidence_pct` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Alert alert_severity gte 1 +MATCH (n:`Alert`) WHERE NOT (n.`alert_severity` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Alert alert_severity lte 5 +MATCH (n:`Alert`) WHERE NOT (n.`alert_severity` <= 5) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall a (ConditionAlert(a) implies exists x (Asset(x) and raised_for(a, x))) +// forall w (PredictiveWorkOrder(w) implies exists a (Alert(a) and triggers(a, w))) +// forall g (EdgeGateway(g) implies exists c (Certificate(c) and authenticated_with(g, c))) +// forall g (EdgeGateway(g) implies not Sensor(g)) diff --git a/examples/domain_iiot.d2 b/examples/domain_iiot.d2 new file mode 100644 index 0000000..c253ebe --- /dev/null +++ b/examples/domain_iiot.d2 @@ -0,0 +1,204 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Asset": { shape: class } +"RotatingAsset": { shape: class } +"Motor": { shape: class } +"Pump": { shape: class } +"Compressor": { shape: class } +"Fan": { shape: class } +"Gearbox": { shape: class } +"StaticAsset": { shape: class } +"HeatExchanger": { shape: class } +"Tank": { shape: class } +"Pipeline": { shape: class } +"Component": { shape: class } +"Bearing": { shape: class } +"Seal": { shape: class } +"Impeller": { shape: class } +"Sensor": { shape: class } +"VibrationSensor": { shape: class } +"TemperatureSensor": { shape: class } +"PressureSensor": { shape: class } +"CurrentSensor": { shape: class } +"AcousticSensor": { shape: class } +"OilQualitySensor": { shape: class } +"EdgeGateway": { shape: class } +"ProtocolBridge": { shape: class } +"EdgeAnalyticsNode": { shape: class } +"PlcController": { shape: class } +"MessageBroker": { shape: class } +"MqttBroker": { shape: class } +"OpcUaServer": { shape: class } +"CloudPlatform": { shape: class } +"TimeSeriesStore": { shape: class } +"NetworkLink": { shape: class } +"CellularLink": { shape: class } +"EthernetLink": { shape: class } +"WirelessMeshLink": { shape: class } +"TelemetryMessage": { shape: class } +"MqttMessage": { shape: class } +"OpcUaDataChange": { shape: class } +"Topic": { shape: class } +"NodeId": { shape: class } +"PayloadSchema": { shape: class } +"Measurement": { shape: class } +"Waveform": { shape: class } +"ScalarReading": { shape: class } +"HealthIndicator": { shape: class } +"FeatureVector": { shape: class } +"AnomalyModel": { shape: class } +"RemainingUsefulLifeEstimate": { shape: class } +"Alert": { shape: class } +"ConditionAlert": { shape: class } +"ConnectivityAlert": { shape: class } +"WorkOrder": { shape: class } +"PredictiveWorkOrder": { shape: class } +"CorrectiveWorkOrder": { shape: class } +"Certificate": { shape: class } +"Telemetry": { shape: class } +"Sampling": { shape: class } +"Publication": { shape: class } +"StoreAndForward": { shape: class } +"InferenceRun": { shape: class } +"Degradation": { shape: class } +"MaintenanceActivity": { shape: class } +"InspectionActivity": { shape: class } +"RepairActivity": { shape: class } +"ReliabilityEngineerRole": { shape: class } +"MaintenanceTechnicianRole": { shape: class } +"DataEngineerRole": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Asset" -> "Object" +"RotatingAsset" -> "Asset" +"Motor" -> "RotatingAsset" +"Pump" -> "RotatingAsset" +"Compressor" -> "RotatingAsset" +"Fan" -> "RotatingAsset" +"Gearbox" -> "RotatingAsset" +"StaticAsset" -> "Asset" +"HeatExchanger" -> "StaticAsset" +"Tank" -> "StaticAsset" +"Pipeline" -> "StaticAsset" +"Component" -> "Object" +"Bearing" -> "Component" +"Seal" -> "Component" +"Impeller" -> "Component" +"Sensor" -> "Object" +"VibrationSensor" -> "Sensor" +"TemperatureSensor" -> "Sensor" +"PressureSensor" -> "Sensor" +"CurrentSensor" -> "Sensor" +"AcousticSensor" -> "Sensor" +"OilQualitySensor" -> "Sensor" +"EdgeGateway" -> "Object" +"ProtocolBridge" -> "EdgeGateway" +"EdgeAnalyticsNode" -> "EdgeGateway" +"PlcController" -> "Object" +"MessageBroker" -> "Object" +"MqttBroker" -> "MessageBroker" +"OpcUaServer" -> "Object" +"CloudPlatform" -> "Object" +"TimeSeriesStore" -> "Object" +"NetworkLink" -> "Object" +"CellularLink" -> "NetworkLink" +"EthernetLink" -> "NetworkLink" +"WirelessMeshLink" -> "NetworkLink" +"TelemetryMessage" -> "InformationContentEntity" +"MqttMessage" -> "TelemetryMessage" +"OpcUaDataChange" -> "TelemetryMessage" +"Topic" -> "InformationContentEntity" +"NodeId" -> "InformationContentEntity" +"PayloadSchema" -> "InformationContentEntity" +"Measurement" -> "InformationContentEntity" +"Waveform" -> "Measurement" +"ScalarReading" -> "Measurement" +"HealthIndicator" -> "InformationContentEntity" +"FeatureVector" -> "InformationContentEntity" +"AnomalyModel" -> "InformationContentEntity" +"RemainingUsefulLifeEstimate" -> "InformationContentEntity" +"Alert" -> "InformationContentEntity" +"ConditionAlert" -> "Alert" +"ConnectivityAlert" -> "Alert" +"WorkOrder" -> "InformationContentEntity" +"PredictiveWorkOrder" -> "WorkOrder" +"CorrectiveWorkOrder" -> "WorkOrder" +"Certificate" -> "InformationContentEntity" +"Telemetry" -> "Process" +"Sampling" -> "Telemetry" +"Publication" -> "Telemetry" +"StoreAndForward" -> "Process" +"InferenceRun" -> "Process" +"Degradation" -> "Process" +"MaintenanceActivity" -> "Process" +"InspectionActivity" -> "MaintenanceActivity" +"RepairActivity" -> "MaintenanceActivity" +"ReliabilityEngineerRole" -> "Role" +"MaintenanceTechnicianRole" -> "Role" +"DataEngineerRole" -> "Role" +"Asset"."asset_tag": String +"Asset"."criticality_rank": Integer +"Sensor"."sampling_rate_hz": Integer +"ScalarReading"."reading_value": Integer +"Measurement"."quality_code": Integer +"MqttMessage"."qos_level": Integer +"MqttMessage"."is_retained": Boolean +"TelemetryMessage"."is_encrypted_in_transit": Boolean +"Topic"."topic_depth": Integer +"EdgeGateway"."buffer_capacity_msgs": Integer +"EdgeGateway"."buffered_msgs": Integer +"EdgeGateway"."is_online": Boolean +"EdgeGateway"."firmware_version": String +"VibrationSensor"."vibration_rms_mm_s": Integer +"Bearing"."bearing_temp_c": Integer +"HealthIndicator"."health_score": Integer +"RemainingUsefulLifeEstimate"."rul_hours": Integer +"RemainingUsefulLifeEstimate"."confidence_pct": Integer +"Alert"."alert_severity": Integer +"Alert"."is_acknowledged": Boolean +"Alert"."is_false_positive": Boolean +"Certificate"."is_expired": Boolean +"TelemetryMessage"."clock_skew_ms": Integer +"Sensor" -> "Asset": monitors +"Sensor" -> "Component": attached_to +"Component" -> "Asset": part_of +"EdgeGateway" -> "Sensor": collects_from +"EdgeGateway" -> "MessageBroker": publishes_to +"OpcUaServer" -> "Asset": exposes +"MessageBroker" -> "CloudPlatform": reports_to +"TelemetryMessage" -> "Sensor": emitted_by +"TelemetryMessage" -> "Topic": published_on +"TelemetryMessage" -> "PayloadSchema": conforms_to +"FeatureVector" -> "Measurement": derived_from +"HealthIndicator" -> "Asset": scores +"RemainingUsefulLifeEstimate" -> "Asset": predicts +"Alert" -> "WorkOrder": triggers +"Alert" -> "Asset": raised_for +"WorkOrder" -> "MaintenanceTechnicianRole": assigned_to +"EdgeGateway" -> "Certificate": authenticated_with +"EdgeGateway" -> "NetworkLink": uplink +# WARNING: The following axioms could not be mapped to field constraints: +# forall a (ConditionAlert(a) implies exists x (Asset(x) and raised_for(a, x))) +# forall w (PredictiveWorkOrder(w) implies exists a (Alert(a) and triggers(a, w))) +# forall g (EdgeGateway(g) implies exists c (Certificate(c) and authenticated_with(g, c))) +# forall g (EdgeGateway(g) implies not Sensor(g)) diff --git a/examples/domain_iiot.d2.svg b/examples/domain_iiot.d2.svg new file mode 100644 index 0000000..1d9ac52 --- /dev/null +++ b/examples/domain_iiot.d2.svg @@ -0,0 +1,119 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectSiteOccurrentProcessRoleFunctionQualityInformationContentEntityAsset+asset_tagString+criticality_rankIntegerRotatingAssetMotorPumpCompressorFanGearboxStaticAssetHeatExchangerTankPipelineComponentBearing+bearing_temp_cIntegerSealImpellerSensor+sampling_rate_hzIntegerVibrationSensor+vibration_rms_mm_sIntegerTemperatureSensorPressureSensorCurrentSensorAcousticSensorOilQualitySensorEdgeGateway+buffer_capacity_msgsInteger+buffered_msgsInteger+is_onlineBoolean+firmware_versionStringProtocolBridgeEdgeAnalyticsNodePlcControllerMessageBrokerMqttBrokerOpcUaServerCloudPlatformTimeSeriesStoreNetworkLinkCellularLinkEthernetLinkWirelessMeshLinkTelemetryMessage+is_encrypted_in_transitBoolean+clock_skew_msIntegerMqttMessage+qos_levelInteger+is_retainedBooleanOpcUaDataChangeTopic+topic_depthIntegerNodeIdPayloadSchemaMeasurement+quality_codeIntegerWaveformScalarReading+reading_valueIntegerHealthIndicator+health_scoreIntegerFeatureVectorAnomalyModelRemainingUsefulLifeEstimate+rul_hoursInteger+confidence_pctIntegerAlert+alert_severityInteger+is_acknowledgedBoolean+is_false_positiveBooleanConditionAlertConnectivityAlertWorkOrderPredictiveWorkOrderCorrectiveWorkOrderCertificate+is_expiredBooleanTelemetrySamplingPublicationStoreAndForwardInferenceRunDegradationMaintenanceActivityInspectionActivityRepairActivityReliabilityEngineerRoleMaintenanceTechnicianRoleDataEngineerRole monitorsattached_topart_ofcollects_frompublishes_toexposesreports_toemitted_bypublished_onconforms_toderived_fromscorespredictstriggersraised_forassigned_toauthenticated_withuplink + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_iiot.logic b/examples/domain_iiot.logic new file mode 100644 index 0000000..7760545 --- /dev/null +++ b/examples/domain_iiot.logic @@ -0,0 +1,202 @@ +; --- Industrial IoT (IIoT) --- +; Models edge gateways, MQTT / OPC UA telemetry, asset condition monitoring and +; predictive maintenance. Vendor-neutral: protocols and roles only. +; Axioms enforce: telemetry quality and bounds, secure transport, alarm and +; work-order duties, remaining-useful-life sanity, and gateway buffering. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Physical Assets --- +(def-concept Asset Object) +(def-concept RotatingAsset Asset) +(def-concept Motor RotatingAsset) +(def-concept Pump RotatingAsset) +(def-concept Compressor RotatingAsset) +(def-concept Fan RotatingAsset) +(def-concept Gearbox RotatingAsset) +(def-concept StaticAsset Asset) +(def-concept HeatExchanger StaticAsset) +(def-concept Tank StaticAsset) +(def-concept Pipeline StaticAsset) +(def-concept Component Object) +(def-concept Bearing Component) +(def-concept Seal Component) +(def-concept Impeller Component) + +; --- Sensing --- +(def-concept Sensor Object) +(def-concept VibrationSensor Sensor) +(def-concept TemperatureSensor Sensor) +(def-concept PressureSensor Sensor) +(def-concept CurrentSensor Sensor) +(def-concept AcousticSensor Sensor) +(def-concept OilQualitySensor Sensor) + +; --- Edge and Network Infrastructure --- +(def-concept EdgeGateway Object) +(def-concept ProtocolBridge EdgeGateway) +(def-concept EdgeAnalyticsNode EdgeGateway) +(def-concept PlcController Object) +(def-concept MessageBroker Object) +(def-concept MqttBroker MessageBroker) +(def-concept OpcUaServer Object) +(def-concept CloudPlatform Object) +(def-concept TimeSeriesStore Object) +(def-concept NetworkLink Object) +(def-concept CellularLink NetworkLink) +(def-concept EthernetLink NetworkLink) +(def-concept WirelessMeshLink NetworkLink) + +; --- Telemetry and Information --- +(def-concept TelemetryMessage InformationContentEntity) +(def-concept MqttMessage TelemetryMessage) +(def-concept OpcUaDataChange TelemetryMessage) +(def-concept Topic InformationContentEntity) +(def-concept NodeId InformationContentEntity) +(def-concept PayloadSchema InformationContentEntity) +(def-concept Measurement InformationContentEntity) +(def-concept Waveform Measurement) +(def-concept ScalarReading Measurement) +(def-concept HealthIndicator InformationContentEntity) +(def-concept FeatureVector InformationContentEntity) +(def-concept AnomalyModel InformationContentEntity) +(def-concept RemainingUsefulLifeEstimate InformationContentEntity) +(def-concept Alert InformationContentEntity) +(def-concept ConditionAlert Alert) +(def-concept ConnectivityAlert Alert) +(def-concept WorkOrder InformationContentEntity) +(def-concept PredictiveWorkOrder WorkOrder) +(def-concept CorrectiveWorkOrder WorkOrder) +(def-concept Certificate InformationContentEntity) + +; --- Processes --- +(def-concept Telemetry Process) +(def-concept Sampling Telemetry) +(def-concept Publication Telemetry) +(def-concept StoreAndForward Process) +(def-concept InferenceRun Process) +(def-concept Degradation Process) +(def-concept MaintenanceActivity Process) +(def-concept InspectionActivity MaintenanceActivity) +(def-concept RepairActivity MaintenanceActivity) + +; --- Roles --- +(def-concept ReliabilityEngineerRole Role) +(def-concept MaintenanceTechnicianRole Role) +(def-concept DataEngineerRole Role) + +; --- Relations --- +(def-relation monitors Sensor Asset :cardinality 1..*) +(def-relation attached_to Sensor Component) +(def-relation part_of Component Asset) +(def-relation collects_from EdgeGateway Sensor :cardinality 0..*) +(def-relation publishes_to EdgeGateway MessageBroker :cardinality 0..*) +(def-relation exposes OpcUaServer Asset :cardinality 0..*) +(def-relation reports_to MessageBroker CloudPlatform) +(def-relation emitted_by TelemetryMessage Sensor) +(def-relation published_on TelemetryMessage Topic) +(def-relation conforms_to TelemetryMessage PayloadSchema) +(def-relation derived_from FeatureVector Measurement :cardinality 1..*) +(def-relation scores HealthIndicator Asset) +(def-relation predicts RemainingUsefulLifeEstimate Asset) +(def-relation triggers Alert WorkOrder :cardinality 0..*) +(def-relation raised_for Alert Asset) +(def-relation assigned_to WorkOrder MaintenanceTechnicianRole) +(def-relation authenticated_with EdgeGateway Certificate :cardinality 1..*) +(def-relation uplink EdgeGateway NetworkLink :cardinality 1..*) + +; --- Properties --- +(def-property asset_tag Asset String :cardinality 1..1) +(def-property criticality_rank Asset Integer) +(def-property sampling_rate_hz Sensor Integer) +(def-property reading_value ScalarReading Integer) +(def-property quality_code Measurement Integer) +(def-property qos_level MqttMessage Integer) +(def-property is_retained MqttMessage Boolean) +(def-property is_encrypted_in_transit TelemetryMessage Boolean) +(def-property topic_depth Topic Integer) +(def-property buffer_capacity_msgs EdgeGateway Integer) +(def-property buffered_msgs EdgeGateway Integer) +(def-property is_online EdgeGateway Boolean) +(def-property firmware_version EdgeGateway String) +(def-property vibration_rms_mm_s VibrationSensor Integer) +(def-property bearing_temp_c Bearing Integer) +(def-property health_score HealthIndicator Integer) +(def-property rul_hours RemainingUsefulLifeEstimate Integer) +(def-property confidence_pct RemainingUsefulLifeEstimate Integer) +(def-property alert_severity Alert Integer) +(def-property is_acknowledged Alert Boolean) +(def-property is_false_positive Alert Boolean) +(def-property is_expired Certificate Boolean) +(def-property clock_skew_ms TelemetryMessage Integer) + +; --- Axioms --- + +; 1. Health indicators are normalised percentages +(forall (h) + (implies (HealthIndicator h) + (and (gte health_score 0) (lte health_score 100)))) + +; 2. MQTT quality of service levels are 0, 1 or 2 only +(forall (m) + (implies (MqttMessage m) + (and (gte qos_level 0) (lte qos_level 2)))) + +; 3. All telemetry travels encrypted in transit +(forall (m) + (implies (TelemetryMessage m) (eq is_encrypted_in_transit True))) + +; 4. Gateways cannot buffer more messages than their store-and-forward capacity +(forall (g) + (implies (EdgeGateway g) + (and (gte buffered_msgs 0) (lte buffered_msgs 1000000)))) + +; 5. Remaining useful life is non-negative and confidence is a percentage +(forall (r) + (implies (RemainingUsefulLifeEstimate r) + (and (gte rul_hours 0) (gte confidence_pct 0) (lte confidence_pct 100)))) + +; 6. A condition alert must be raised against some asset +(forall (a) + (implies (ConditionAlert a) + (exists (x) (and (Asset x) (raised_for a x))))) + +; 7. A predictive work order must originate from an alert +(forall (w) + (implies (PredictiveWorkOrder w) + (exists (a) (and (Alert a) (triggers a w))))) + +; 8. Gateways must hold a credential so they can authenticate to the broker +(forall (g) + (implies (EdgeGateway g) + (exists (c) (and (Certificate c) (authenticated_with g c))))) + +; 9. Severity is ranked 1 (info) to 5 (critical) +(forall (a) + (implies (Alert a) + (and (gte alert_severity 1) (lte alert_severity 5)))) + +; 10. Gateways and sensors are physically distinct kinds of device +(forall (g) + (implies (EdgeGateway g) (not (Sensor g)))) + +; 11. A sensor must sample at a positive rate +(forall (s) + (implies (Sensor s) (gt sampling_rate_hz 0))) + +; 12. Measurement quality codes are 0 (bad) to 3 (good) +(forall (m) + (implies (Measurement m) + (and (gte quality_code 0) (lte quality_code 3)))) diff --git a/examples/domain_iiot.mmd b/examples/domain_iiot.mmd new file mode 100644 index 0000000..ebaa4ca --- /dev/null +++ b/examples/domain_iiot.mmd @@ -0,0 +1,205 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Asset["Asset"] + class RotatingAsset["RotatingAsset"] + class Motor["Motor"] + class Pump["Pump"] + class Compressor["Compressor"] + class Fan["Fan"] + class Gearbox["Gearbox"] + class StaticAsset["StaticAsset"] + class HeatExchanger["HeatExchanger"] + class Tank["Tank"] + class Pipeline["Pipeline"] + class Component["Component"] + class Bearing["Bearing"] + class Seal["Seal"] + class Impeller["Impeller"] + class Sensor["Sensor"] + class VibrationSensor["VibrationSensor"] + class TemperatureSensor["TemperatureSensor"] + class PressureSensor["PressureSensor"] + class CurrentSensor["CurrentSensor"] + class AcousticSensor["AcousticSensor"] + class OilQualitySensor["OilQualitySensor"] + class EdgeGateway["EdgeGateway"] + class ProtocolBridge["ProtocolBridge"] + class EdgeAnalyticsNode["EdgeAnalyticsNode"] + class PlcController["PlcController"] + class MessageBroker["MessageBroker"] + class MqttBroker["MqttBroker"] + class OpcUaServer["OpcUaServer"] + class CloudPlatform["CloudPlatform"] + class TimeSeriesStore["TimeSeriesStore"] + class NetworkLink["NetworkLink"] + class CellularLink["CellularLink"] + class EthernetLink["EthernetLink"] + class WirelessMeshLink["WirelessMeshLink"] + class TelemetryMessage["TelemetryMessage"] + class MqttMessage["MqttMessage"] + class OpcUaDataChange["OpcUaDataChange"] + class Topic["Topic"] + class NodeId["NodeId"] + class PayloadSchema["PayloadSchema"] + class Measurement["Measurement"] + class Waveform["Waveform"] + class ScalarReading["ScalarReading"] + class HealthIndicator["HealthIndicator"] + class FeatureVector["FeatureVector"] + class AnomalyModel["AnomalyModel"] + class RemainingUsefulLifeEstimate["RemainingUsefulLifeEstimate"] + class Alert["Alert"] + class ConditionAlert["ConditionAlert"] + class ConnectivityAlert["ConnectivityAlert"] + class WorkOrder["WorkOrder"] + class PredictiveWorkOrder["PredictiveWorkOrder"] + class CorrectiveWorkOrder["CorrectiveWorkOrder"] + class Certificate["Certificate"] + class Telemetry["Telemetry"] + class Sampling["Sampling"] + class Publication["Publication"] + class StoreAndForward["StoreAndForward"] + class InferenceRun["InferenceRun"] + class Degradation["Degradation"] + class MaintenanceActivity["MaintenanceActivity"] + class InspectionActivity["InspectionActivity"] + class RepairActivity["RepairActivity"] + class ReliabilityEngineerRole["ReliabilityEngineerRole"] + class MaintenanceTechnicianRole["MaintenanceTechnicianRole"] + class DataEngineerRole["DataEngineerRole"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Object <|-- Asset + Asset <|-- RotatingAsset + RotatingAsset <|-- Motor + RotatingAsset <|-- Pump + RotatingAsset <|-- Compressor + RotatingAsset <|-- Fan + RotatingAsset <|-- Gearbox + Asset <|-- StaticAsset + StaticAsset <|-- HeatExchanger + StaticAsset <|-- Tank + StaticAsset <|-- Pipeline + Object <|-- Component + Component <|-- Bearing + Component <|-- Seal + Component <|-- Impeller + Object <|-- Sensor + Sensor <|-- VibrationSensor + Sensor <|-- TemperatureSensor + Sensor <|-- PressureSensor + Sensor <|-- CurrentSensor + Sensor <|-- AcousticSensor + Sensor <|-- OilQualitySensor + Object <|-- EdgeGateway + EdgeGateway <|-- ProtocolBridge + EdgeGateway <|-- EdgeAnalyticsNode + Object <|-- PlcController + Object <|-- MessageBroker + MessageBroker <|-- MqttBroker + Object <|-- OpcUaServer + Object <|-- CloudPlatform + Object <|-- TimeSeriesStore + Object <|-- NetworkLink + NetworkLink <|-- CellularLink + NetworkLink <|-- EthernetLink + NetworkLink <|-- WirelessMeshLink + InformationContentEntity <|-- TelemetryMessage + TelemetryMessage <|-- MqttMessage + TelemetryMessage <|-- OpcUaDataChange + InformationContentEntity <|-- Topic + InformationContentEntity <|-- NodeId + InformationContentEntity <|-- PayloadSchema + InformationContentEntity <|-- Measurement + Measurement <|-- Waveform + Measurement <|-- ScalarReading + InformationContentEntity <|-- HealthIndicator + InformationContentEntity <|-- FeatureVector + InformationContentEntity <|-- AnomalyModel + InformationContentEntity <|-- RemainingUsefulLifeEstimate + InformationContentEntity <|-- Alert + Alert <|-- ConditionAlert + Alert <|-- ConnectivityAlert + InformationContentEntity <|-- WorkOrder + WorkOrder <|-- PredictiveWorkOrder + WorkOrder <|-- CorrectiveWorkOrder + InformationContentEntity <|-- Certificate + Process <|-- Telemetry + Telemetry <|-- Sampling + Telemetry <|-- Publication + Process <|-- StoreAndForward + Process <|-- InferenceRun + Process <|-- Degradation + Process <|-- MaintenanceActivity + MaintenanceActivity <|-- InspectionActivity + MaintenanceActivity <|-- RepairActivity + Role <|-- ReliabilityEngineerRole + Role <|-- MaintenanceTechnicianRole + Role <|-- DataEngineerRole + Asset : +String asset_tag + Asset : +Integer criticality_rank + Sensor : +Integer sampling_rate_hz + ScalarReading : +Integer reading_value + Measurement : +Integer quality_code + MqttMessage : +Integer qos_level + MqttMessage : +Boolean is_retained + TelemetryMessage : +Boolean is_encrypted_in_transit + Topic : +Integer topic_depth + EdgeGateway : +Integer buffer_capacity_msgs + EdgeGateway : +Integer buffered_msgs + EdgeGateway : +Boolean is_online + EdgeGateway : +String firmware_version + VibrationSensor : +Integer vibration_rms_mm_s + Bearing : +Integer bearing_temp_c + HealthIndicator : +Integer health_score + RemainingUsefulLifeEstimate : +Integer rul_hours + RemainingUsefulLifeEstimate : +Integer confidence_pct + Alert : +Integer alert_severity + Alert : +Boolean is_acknowledged + Alert : +Boolean is_false_positive + Certificate : +Boolean is_expired + TelemetryMessage : +Integer clock_skew_ms + Sensor --> Asset : monitors + Sensor --> Component : attached_to + Component --> Asset : part_of + EdgeGateway --> Sensor : collects_from + EdgeGateway --> MessageBroker : publishes_to + OpcUaServer --> Asset : exposes + MessageBroker --> CloudPlatform : reports_to + TelemetryMessage --> Sensor : emitted_by + TelemetryMessage --> Topic : published_on + TelemetryMessage --> PayloadSchema : conforms_to + FeatureVector --> Measurement : derived_from + HealthIndicator --> Asset : scores + RemainingUsefulLifeEstimate --> Asset : predicts + Alert --> WorkOrder : triggers + Alert --> Asset : raised_for + WorkOrder --> MaintenanceTechnicianRole : assigned_to + EdgeGateway --> Certificate : authenticated_with + EdgeGateway --> NetworkLink : uplink + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall a (ConditionAlert(a) implies exists x (Asset(x) and raised_for(a, x))) +%% forall w (PredictiveWorkOrder(w) implies exists a (Alert(a) and triggers(a, w))) +%% forall g (EdgeGateway(g) implies exists c (Certificate(c) and authenticated_with(g, c))) +%% forall g (EdgeGateway(g) implies not Sensor(g)) diff --git a/examples/domain_iot_smart_home.cypher b/examples/domain_iot_smart_home.cypher new file mode 100644 index 0000000..23acd71 --- /dev/null +++ b/examples/domain_iot_smart_home.cypher @@ -0,0 +1,332 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Household'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Resident'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Guest'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Child'}) +MERGE (p:OntologyClass {name: 'Resident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Home'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Room'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Bedroom'}) +MERGE (p:OntologyClass {name: 'Room'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Kitchen'}) +MERGE (p:OntologyClass {name: 'Room'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LivingRoom'}) +MERGE (p:OntologyClass {name: 'Room'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Bathroom'}) +MERGE (p:OntologyClass {name: 'Room'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Garage'}) +MERGE (p:OntologyClass {name: 'Room'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SmartDevice'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Hub'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThreadBorderRouter'}) +MERGE (p:OntologyClass {name: 'Hub'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ZigbeeCoordinator'}) +MERGE (p:OntologyClass {name: 'Hub'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Light'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Thermostat'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SmartPlug'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DoorLock'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Camera'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DoorbellCamera'}) +MERGE (p:OntologyClass {name: 'Camera'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SmartSpeaker'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MotionSensor'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ContactSensor'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SmokeDetector'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LeakSensor'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Oven'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RobotVacuum'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GarageDoorOpener'}) +MERGE (p:OntologyClass {name: 'SmartDevice'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Radio'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WifiRadio'}) +MERGE (p:OntologyClass {name: 'Radio'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThreadRadio'}) +MERGE (p:OntologyClass {name: 'Radio'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ZigbeeRadio'}) +MERGE (p:OntologyClass {name: 'Radio'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BluetoothRadio'}) +MERGE (p:OntologyClass {name: 'Radio'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CloudService'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MobileApp'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Automation'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Trigger'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TimeTrigger'}) +MERGE (p:OntologyClass {name: 'Trigger'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PresenceTrigger'}) +MERGE (p:OntologyClass {name: 'Trigger'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SensorTrigger'}) +MERGE (p:OntologyClass {name: 'Trigger'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VoiceTrigger'}) +MERGE (p:OntologyClass {name: 'Trigger'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Condition'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Action'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Scene'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AutomationRun'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FirmwareImage'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SecurityPatch'}) +MERGE (p:OntologyClass {name: 'FirmwareImage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FeatureRelease'}) +MERGE (p:OntologyClass {name: 'FirmwareImage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FirmwareUpdate'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RollbackEvent'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PersonalData'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VideoRecording'}) +MERGE (p:OntologyClass {name: 'PersonalData'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AudioRecording'}) +MERGE (p:OntologyClass {name: 'PersonalData'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PresenceHistory'}) +MERGE (p:OntologyClass {name: 'PersonalData'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DeviceUsageLog'}) +MERGE (p:OntologyClass {name: 'PersonalData'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Consent'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConsentGrant'}) +MERGE (p:OntologyClass {name: 'Consent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConsentWithdrawal'}) +MERGE (p:OntologyClass {name: 'Consent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PrivacyPolicy'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataSharingAgreement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataSubjectRequest'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DeletionRequest'}) +MERGE (p:OntologyClass {name: 'DataSubjectRequest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ExportRequest'}) +MERGE (p:OntologyClass {name: 'DataSubjectRequest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OwnerRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AdminRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MemberRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GuestAccessRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'SmartDevice'}) +MERGE (t:OntologyClass {name: 'Hub'}) +MERGE (s)-[:RELATION {name: 'paired_with'}]->(t); +MERGE (s:OntologyClass {name: 'SmartDevice'}) +MERGE (t:OntologyClass {name: 'Room'}) +MERGE (s)-[:RELATION {name: 'located_in'}]->(t); +MERGE (s:OntologyClass {name: 'Room'}) +MERGE (t:OntologyClass {name: 'Home'}) +MERGE (s)-[:RELATION {name: 'part_of_home'}]->(t); +MERGE (s:OntologyClass {name: 'SmartDevice'}) +MERGE (t:OntologyClass {name: 'Radio'}) +MERGE (s)-[:RELATION {name: 'uses_radio'}]->(t); +MERGE (s:OntologyClass {name: 'Hub'}) +MERGE (t:OntologyClass {name: 'CloudService'}) +MERGE (s)-[:RELATION {name: 'syncs_with'}]->(t); +MERGE (s:OntologyClass {name: 'MobileApp'}) +MERGE (t:OntologyClass {name: 'Hub'}) +MERGE (s)-[:RELATION {name: 'controls_via'}]->(t); +MERGE (s:OntologyClass {name: 'Resident'}) +MERGE (t:OntologyClass {name: 'SmartDevice'}) +MERGE (s)-[:RELATION {name: 'owns'}]->(t); +MERGE (s:OntologyClass {name: 'Resident'}) +MERGE (t:OntologyClass {name: 'Household'}) +MERGE (s)-[:RELATION {name: 'member_of'}]->(t); +MERGE (s:OntologyClass {name: 'Trigger'}) +MERGE (t:OntologyClass {name: 'Automation'}) +MERGE (s)-[:RELATION {name: 'triggers_automation'}]->(t); +MERGE (s:OntologyClass {name: 'Automation'}) +MERGE (t:OntologyClass {name: 'Action'}) +MERGE (s)-[:RELATION {name: 'performs'}]->(t); +MERGE (s:OntologyClass {name: 'Action'}) +MERGE (t:OntologyClass {name: 'SmartDevice'}) +MERGE (s)-[:RELATION {name: 'targets'}]->(t); +MERGE (s:OntologyClass {name: 'FirmwareUpdate'}) +MERGE (t:OntologyClass {name: 'SmartDevice'}) +MERGE (s)-[:RELATION {name: 'applies_to'}]->(t); +MERGE (s:OntologyClass {name: 'FirmwareUpdate'}) +MERGE (t:OntologyClass {name: 'FirmwareImage'}) +MERGE (s)-[:RELATION {name: 'installs'}]->(t); +MERGE (s:OntologyClass {name: 'PersonalData'}) +MERGE (t:OntologyClass {name: 'SmartDevice'}) +MERGE (s)-[:RELATION {name: 'captured_by'}]->(t); +MERGE (s:OntologyClass {name: 'PersonalData'}) +MERGE (t:OntologyClass {name: 'Person'}) +MERGE (s)-[:RELATION {name: 'concerns'}]->(t); +MERGE (s:OntologyClass {name: 'Consent'}) +MERGE (t:OntologyClass {name: 'Person'}) +MERGE (s)-[:RELATION {name: 'granted_by'}]->(t); +MERGE (s:OntologyClass {name: 'Consent'}) +MERGE (t:OntologyClass {name: 'PersonalData'}) +MERGE (s)-[:RELATION {name: 'covers'}]->(t); +MERGE (s:OntologyClass {name: 'SmartDevice'}) +MERGE (t:OntologyClass {name: 'PrivacyPolicy'}) +MERGE (s)-[:RELATION {name: 'governed_by'}]->(t); +// Axiom Validations +// Axiom validation: SmartDevice battery_pct gte 0 +MATCH (n:`SmartDevice`) WHERE NOT (n.`battery_pct` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SmartDevice battery_pct lte 100 +MATCH (n:`SmartDevice`) WHERE NOT (n.`battery_pct` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SmartDevice default_password_changed eq True +MATCH (n:`SmartDevice`) WHERE NOT (n.`default_password_changed` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Thermostat target_temp_c gte 5 +MATCH (n:`Thermostat`) WHERE NOT (n.`target_temp_c` >= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Thermostat target_temp_c lte 35 +MATCH (n:`Thermostat`) WHERE NOT (n.`target_temp_c` <= 35) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Automation runs_unattended eq False +MATCH (n:`Automation`) WHERE NOT (n.`runs_unattended` = false) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: FirmwareImage is_signed eq True +MATCH (n:`FirmwareImage`) WHERE NOT (n.`is_signed` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: FirmwareUpdate rollout_pct gte 0 +MATCH (n:`FirmwareUpdate`) WHERE NOT (n.`rollout_pct` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: FirmwareUpdate rollout_pct lte 100 +MATCH (n:`FirmwareUpdate`) WHERE NOT (n.`rollout_pct` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: PersonalData retention_days gte 1 +MATCH (n:`PersonalData`) WHERE NOT (n.`retention_days` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: PersonalData retention_days lte 365 +MATCH (n:`PersonalData`) WHERE NOT (n.`retention_days` <= 365) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: VideoRecording is_end_to_end_encrypted eq True +MATCH (n:`VideoRecording`) WHERE NOT (n.`is_end_to_end_encrypted` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall p (PersonalData(p) and is_shared_with_third_party = True implies exists c (Consent(c) and covers(c, p))) +// forall v (VideoRecording(v) implies exists c (ConsentGrant(c) and covers(c, v))) +// forall s (SmartSpeaker(s) and is_listening = True implies has_hardware_mute = True) +// forall c (Camera(c) implies not SmartSpeaker(c)) +// forall c (ConsentGrant(c) implies not ConsentWithdrawal(c)) diff --git a/examples/domain_iot_smart_home.d2 b/examples/domain_iot_smart_home.d2 new file mode 100644 index 0000000..a10e0b2 --- /dev/null +++ b/examples/domain_iot_smart_home.d2 @@ -0,0 +1,210 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Site": { shape: class } +"Agent": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Person": { shape: class } +"Household": { shape: class } +"Resident": { shape: class } +"Guest": { shape: class } +"Child": { shape: class } +"Home": { shape: class } +"Room": { shape: class } +"Bedroom": { shape: class } +"Kitchen": { shape: class } +"LivingRoom": { shape: class } +"Bathroom": { shape: class } +"Garage": { shape: class } +"SmartDevice": { shape: class } +"Hub": { shape: class } +"ThreadBorderRouter": { shape: class } +"ZigbeeCoordinator": { shape: class } +"Light": { shape: class } +"Thermostat": { shape: class } +"SmartPlug": { shape: class } +"DoorLock": { shape: class } +"Camera": { shape: class } +"DoorbellCamera": { shape: class } +"SmartSpeaker": { shape: class } +"MotionSensor": { shape: class } +"ContactSensor": { shape: class } +"SmokeDetector": { shape: class } +"LeakSensor": { shape: class } +"Oven": { shape: class } +"RobotVacuum": { shape: class } +"GarageDoorOpener": { shape: class } +"Radio": { shape: class } +"WifiRadio": { shape: class } +"ThreadRadio": { shape: class } +"ZigbeeRadio": { shape: class } +"BluetoothRadio": { shape: class } +"CloudService": { shape: class } +"MobileApp": { shape: class } +"Automation": { shape: class } +"Trigger": { shape: class } +"TimeTrigger": { shape: class } +"PresenceTrigger": { shape: class } +"SensorTrigger": { shape: class } +"VoiceTrigger": { shape: class } +"Condition": { shape: class } +"Action": { shape: class } +"Scene": { shape: class } +"AutomationRun": { shape: class } +"FirmwareImage": { shape: class } +"SecurityPatch": { shape: class } +"FeatureRelease": { shape: class } +"FirmwareUpdate": { shape: class } +"RollbackEvent": { shape: class } +"PersonalData": { shape: class } +"VideoRecording": { shape: class } +"AudioRecording": { shape: class } +"PresenceHistory": { shape: class } +"DeviceUsageLog": { shape: class } +"Consent": { shape: class } +"ConsentGrant": { shape: class } +"ConsentWithdrawal": { shape: class } +"PrivacyPolicy": { shape: class } +"DataSharingAgreement": { shape: class } +"DataSubjectRequest": { shape: class } +"DeletionRequest": { shape: class } +"ExportRequest": { shape: class } +"OwnerRole": { shape: class } +"AdminRole": { shape: class } +"MemberRole": { shape: class } +"GuestAccessRole": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Site" -> "IndependentContinuant" +"Agent" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Person" -> "Agent" +"Household" -> "InformationContentEntity" +"Resident" -> "Person" +"Guest" -> "Person" +"Child" -> "Resident" +"Home" -> "Site" +"Room" -> "Site" +"Bedroom" -> "Room" +"Kitchen" -> "Room" +"LivingRoom" -> "Room" +"Bathroom" -> "Room" +"Garage" -> "Room" +"SmartDevice" -> "Object" +"Hub" -> "SmartDevice" +"ThreadBorderRouter" -> "Hub" +"ZigbeeCoordinator" -> "Hub" +"Light" -> "SmartDevice" +"Thermostat" -> "SmartDevice" +"SmartPlug" -> "SmartDevice" +"DoorLock" -> "SmartDevice" +"Camera" -> "SmartDevice" +"DoorbellCamera" -> "Camera" +"SmartSpeaker" -> "SmartDevice" +"MotionSensor" -> "SmartDevice" +"ContactSensor" -> "SmartDevice" +"SmokeDetector" -> "SmartDevice" +"LeakSensor" -> "SmartDevice" +"Oven" -> "SmartDevice" +"RobotVacuum" -> "SmartDevice" +"GarageDoorOpener" -> "SmartDevice" +"Radio" -> "Object" +"WifiRadio" -> "Radio" +"ThreadRadio" -> "Radio" +"ZigbeeRadio" -> "Radio" +"BluetoothRadio" -> "Radio" +"CloudService" -> "Object" +"MobileApp" -> "Object" +"Automation" -> "InformationContentEntity" +"Trigger" -> "InformationContentEntity" +"TimeTrigger" -> "Trigger" +"PresenceTrigger" -> "Trigger" +"SensorTrigger" -> "Trigger" +"VoiceTrigger" -> "Trigger" +"Condition" -> "InformationContentEntity" +"Action" -> "InformationContentEntity" +"Scene" -> "InformationContentEntity" +"AutomationRun" -> "Process" +"FirmwareImage" -> "InformationContentEntity" +"SecurityPatch" -> "FirmwareImage" +"FeatureRelease" -> "FirmwareImage" +"FirmwareUpdate" -> "Process" +"RollbackEvent" -> "Process" +"PersonalData" -> "InformationContentEntity" +"VideoRecording" -> "PersonalData" +"AudioRecording" -> "PersonalData" +"PresenceHistory" -> "PersonalData" +"DeviceUsageLog" -> "PersonalData" +"Consent" -> "InformationContentEntity" +"ConsentGrant" -> "Consent" +"ConsentWithdrawal" -> "Consent" +"PrivacyPolicy" -> "InformationContentEntity" +"DataSharingAgreement" -> "InformationContentEntity" +"DataSubjectRequest" -> "Process" +"DeletionRequest" -> "DataSubjectRequest" +"ExportRequest" -> "DataSubjectRequest" +"OwnerRole" -> "Role" +"AdminRole" -> "Role" +"MemberRole" -> "Role" +"GuestAccessRole" -> "Role" +"SmartDevice"."device_name": String +"SmartDevice"."firmware_version": String +"SmartDevice"."battery_pct": Integer +"SmartDevice"."is_online": Boolean +"Camera"."is_recording": Boolean +"SmartSpeaker"."is_listening": Boolean +"SmartSpeaker"."has_hardware_mute": Boolean +"Oven"."is_on": Boolean +"Thermostat"."target_temp_c": Integer +"DoorLock"."is_locked": Boolean +"GarageDoorOpener"."is_door_open": Boolean +"FirmwareImage"."is_signed": Boolean +"FirmwareUpdate"."rollout_pct": Integer +"FirmwareImage"."is_security_critical": Boolean +"Person"."age_years": Integer +"Home"."is_home_occupied": Boolean +"PersonalData"."retention_days": Integer +"Consent"."is_active": Boolean +"PersonalData"."is_shared_with_third_party": Boolean +"VideoRecording"."is_end_to_end_encrypted": Boolean +"SmartDevice"."default_password_changed": Boolean +"Automation"."runs_unattended": Boolean +"SmartDevice" -> "Hub": paired_with +"SmartDevice" -> "Room": located_in +"Room" -> "Home": part_of_home +"SmartDevice" -> "Radio": uses_radio +"Hub" -> "CloudService": syncs_with +"MobileApp" -> "Hub": controls_via +"Resident" -> "SmartDevice": owns +"Resident" -> "Household": member_of +"Trigger" -> "Automation": triggers_automation +"Automation" -> "Action": performs +"Action" -> "SmartDevice": targets +"FirmwareUpdate" -> "SmartDevice": applies_to +"FirmwareUpdate" -> "FirmwareImage": installs +"PersonalData" -> "SmartDevice": captured_by +"PersonalData" -> "Person": concerns +"Consent" -> "Person": granted_by +"Consent" -> "PersonalData": covers +"SmartDevice" -> "PrivacyPolicy": governed_by +# WARNING: The following axioms could not be mapped to field constraints: +# forall p (PersonalData(p) and is_shared_with_third_party = True implies exists c (Consent(c) and covers(c, p))) +# forall v (VideoRecording(v) implies exists c (ConsentGrant(c) and covers(c, v))) +# forall s (SmartSpeaker(s) and is_listening = True implies has_hardware_mute = True) +# forall c (Camera(c) implies not SmartSpeaker(c)) +# forall c (ConsentGrant(c) implies not ConsentWithdrawal(c)) diff --git a/examples/domain_iot_smart_home.d2.svg b/examples/domain_iot_smart_home.d2.svg new file mode 100644 index 0000000..44d8327 --- /dev/null +++ b/examples/domain_iot_smart_home.d2.svg @@ -0,0 +1,119 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectSiteAgentOccurrentProcessRoleFunctionQualityInformationContentEntityPerson+age_yearsIntegerHouseholdResidentGuestChildHome+is_home_occupiedBooleanRoomBedroomKitchenLivingRoomBathroomGarageSmartDevice+device_nameString+firmware_versionString+battery_pctInteger+is_onlineBoolean+default_password_changedBooleanHubThreadBorderRouterZigbeeCoordinatorLightThermostat+target_temp_cIntegerSmartPlugDoorLock+is_lockedBooleanCamera+is_recordingBooleanDoorbellCameraSmartSpeaker+is_listeningBoolean+has_hardware_muteBooleanMotionSensorContactSensorSmokeDetectorLeakSensorOven+is_onBooleanRobotVacuumGarageDoorOpener+is_door_openBooleanRadioWifiRadioThreadRadioZigbeeRadioBluetoothRadioCloudServiceMobileAppAutomation+runs_unattendedBooleanTriggerTimeTriggerPresenceTriggerSensorTriggerVoiceTriggerConditionActionSceneAutomationRunFirmwareImage+is_signedBoolean+is_security_criticalBooleanSecurityPatchFeatureReleaseFirmwareUpdate+rollout_pctIntegerRollbackEventPersonalData+retention_daysInteger+is_shared_with_third_partyBooleanVideoRecording+is_end_to_end_encryptedBooleanAudioRecordingPresenceHistoryDeviceUsageLogConsent+is_activeBooleanConsentGrantConsentWithdrawalPrivacyPolicyDataSharingAgreementDataSubjectRequestDeletionRequestExportRequestOwnerRoleAdminRoleMemberRoleGuestAccessRole paired_withlocated_inpart_of_homeuses_radiosyncs_withcontrols_viaownsmember_oftriggers_automationperformstargetsapplies_toinstallscaptured_byconcernsgranted_bycoversgoverned_by + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_iot_smart_home.logic b/examples/domain_iot_smart_home.logic new file mode 100644 index 0000000..aa445bc --- /dev/null +++ b/examples/domain_iot_smart_home.logic @@ -0,0 +1,208 @@ +; --- Consumer IoT / Smart Home --- +; Models devices, hubs, rooms, automations, firmware updates and the +; privacy / consent obligations around household data. +; Axioms enforce: camera and microphone consent, signed firmware, hub +; connectivity, automation safety (no unattended hazards) and data retention. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Site IndependentContinuant) +(def-concept Agent MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- People and Places --- +(def-concept Person Agent) +(def-concept Household InformationContentEntity) +(def-concept Resident Person) +(def-concept Guest Person) +(def-concept Child Resident) +(def-concept Home Site) +(def-concept Room Site) +(def-concept Bedroom Room) +(def-concept Kitchen Room) +(def-concept LivingRoom Room) +(def-concept Bathroom Room) +(def-concept Garage Room) + +; --- Devices --- +(def-concept SmartDevice Object) +(def-concept Hub SmartDevice) +(def-concept ThreadBorderRouter Hub) +(def-concept ZigbeeCoordinator Hub) +(def-concept Light SmartDevice) +(def-concept Thermostat SmartDevice) +(def-concept SmartPlug SmartDevice) +(def-concept DoorLock SmartDevice) +(def-concept Camera SmartDevice) +(def-concept DoorbellCamera Camera) +(def-concept SmartSpeaker SmartDevice) +(def-concept MotionSensor SmartDevice) +(def-concept ContactSensor SmartDevice) +(def-concept SmokeDetector SmartDevice) +(def-concept LeakSensor SmartDevice) +(def-concept Oven SmartDevice) +(def-concept RobotVacuum SmartDevice) +(def-concept GarageDoorOpener SmartDevice) + +; --- Connectivity --- +(def-concept Radio Object) +(def-concept WifiRadio Radio) +(def-concept ThreadRadio Radio) +(def-concept ZigbeeRadio Radio) +(def-concept BluetoothRadio Radio) +(def-concept CloudService Object) +(def-concept MobileApp Object) + +; --- Automation --- +(def-concept Automation InformationContentEntity) +(def-concept Trigger InformationContentEntity) +(def-concept TimeTrigger Trigger) +(def-concept PresenceTrigger Trigger) +(def-concept SensorTrigger Trigger) +(def-concept VoiceTrigger Trigger) +(def-concept Condition InformationContentEntity) +(def-concept Action InformationContentEntity) +(def-concept Scene InformationContentEntity) +(def-concept AutomationRun Process) + +; --- Firmware --- +(def-concept FirmwareImage InformationContentEntity) +(def-concept SecurityPatch FirmwareImage) +(def-concept FeatureRelease FirmwareImage) +(def-concept FirmwareUpdate Process) +(def-concept RollbackEvent Process) + +; --- Privacy and Consent --- +(def-concept PersonalData InformationContentEntity) +(def-concept VideoRecording PersonalData) +(def-concept AudioRecording PersonalData) +(def-concept PresenceHistory PersonalData) +(def-concept DeviceUsageLog PersonalData) +(def-concept Consent InformationContentEntity) +(def-concept ConsentGrant Consent) +(def-concept ConsentWithdrawal Consent) +(def-concept PrivacyPolicy InformationContentEntity) +(def-concept DataSharingAgreement InformationContentEntity) +(def-concept DataSubjectRequest Process) +(def-concept DeletionRequest DataSubjectRequest) +(def-concept ExportRequest DataSubjectRequest) + +; --- Roles --- +(def-concept OwnerRole Role) +(def-concept AdminRole Role) +(def-concept MemberRole Role) +(def-concept GuestAccessRole Role) + +; --- Relations --- +(def-relation paired_with SmartDevice Hub :cardinality 0..1) +(def-relation located_in SmartDevice Room :cardinality 1..1) +(def-relation part_of_home Room Home) +(def-relation uses_radio SmartDevice Radio :cardinality 1..*) +(def-relation syncs_with Hub CloudService) +(def-relation controls_via MobileApp Hub) +(def-relation owns Resident SmartDevice :cardinality 0..*) +(def-relation member_of Resident Household) +(def-relation triggers_automation Trigger Automation) +(def-relation performs Automation Action :cardinality 1..*) +(def-relation targets Action SmartDevice) +(def-relation applies_to FirmwareUpdate SmartDevice) +(def-relation installs FirmwareUpdate FirmwareImage) +(def-relation captured_by PersonalData SmartDevice) +(def-relation concerns PersonalData Person) +(def-relation granted_by Consent Person) +(def-relation covers Consent PersonalData :cardinality 1..*) +(def-relation governed_by SmartDevice PrivacyPolicy) + +; --- Properties --- +(def-property device_name SmartDevice String :cardinality 1..1) +(def-property firmware_version SmartDevice String) +(def-property battery_pct SmartDevice Integer) +(def-property is_online SmartDevice Boolean) +(def-property is_recording Camera Boolean) +(def-property is_listening SmartSpeaker Boolean) +(def-property has_hardware_mute SmartSpeaker Boolean) +(def-property is_on Oven Boolean) +(def-property target_temp_c Thermostat Integer) +(def-property is_locked DoorLock Boolean) +(def-property is_door_open GarageDoorOpener Boolean) +(def-property is_signed FirmwareImage Boolean) +(def-property rollout_pct FirmwareUpdate Integer) +(def-property is_security_critical FirmwareImage Boolean) +(def-property age_years Person Integer) +(def-property is_home_occupied Home Boolean) +(def-property retention_days PersonalData Integer) +(def-property is_active Consent Boolean) +(def-property is_shared_with_third_party PersonalData Boolean) +(def-property is_end_to_end_encrypted VideoRecording Boolean) +(def-property default_password_changed SmartDevice Boolean) +(def-property runs_unattended Automation Boolean) + +; --- Axioms --- + +; 1. Thermostat targets stay in a safe range (5..35 C) +(forall (t) + (implies (Thermostat t) + (and (gte target_temp_c 5) (lte target_temp_c 35)))) + +; 2. Battery percentage is a valid percentage +(forall (d) + (implies (SmartDevice d) + (and (gte battery_pct 0) (lte battery_pct 100)))) + +; 3. Firmware is only installed when the image is cryptographically signed +(forall (i) + (implies (FirmwareImage i) (eq is_signed True))) + +; 4. Personal data is retained for at most one year +(forall (p) + (implies (PersonalData p) + (and (gte retention_days 1) (lte retention_days 365)))) + +; 5. Video recordings are always end-to-end encrypted +(forall (v) + (implies (VideoRecording v) (eq is_end_to_end_encrypted True))) + +; 6. Personal data cannot be shared with third parties without consent +(forall (p) + (implies (and (PersonalData p) (eq is_shared_with_third_party True)) + (exists (c) (and (Consent c) (covers c p))))) + +; 7. Every recording is covered by a consent grant +(forall (v) + (implies (VideoRecording v) + (exists (c) (and (ConsentGrant c) (covers c v))))) + +; 8. A smart speaker that is listening must offer a hardware mute +(forall (s) + (implies (and (SmartSpeaker s) (eq is_listening True)) + (eq has_hardware_mute True))) + +; 9. Hazard rule: no automation (e.g. one driving an oven) runs unattended +(forall (a) + (implies (Automation a) (eq runs_unattended False))) + +; 10. Every device has changed its factory default password +(forall (d) + (implies (SmartDevice d) (eq default_password_changed True))) + +; 11. Cameras and microphones are different device classes +(forall (c) + (implies (Camera c) (not (SmartSpeaker c)))) + +; 12. A consent grant and a consent withdrawal are mutually exclusive +(forall (c) + (implies (ConsentGrant c) (not (ConsentWithdrawal c)))) + +; 13. Rollout progress is a percentage +(forall (u) + (implies (FirmwareUpdate u) + (and (gte rollout_pct 0) (lte rollout_pct 100)))) diff --git a/examples/domain_iot_smart_home.mmd b/examples/domain_iot_smart_home.mmd new file mode 100644 index 0000000..9b5132a --- /dev/null +++ b/examples/domain_iot_smart_home.mmd @@ -0,0 +1,211 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Site["Site"] + class Agent["Agent"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Person["Person"] + class Household["Household"] + class Resident["Resident"] + class Guest["Guest"] + class Child["Child"] + class Home["Home"] + class Room["Room"] + class Bedroom["Bedroom"] + class Kitchen["Kitchen"] + class LivingRoom["LivingRoom"] + class Bathroom["Bathroom"] + class Garage["Garage"] + class SmartDevice["SmartDevice"] + class Hub["Hub"] + class ThreadBorderRouter["ThreadBorderRouter"] + class ZigbeeCoordinator["ZigbeeCoordinator"] + class Light["Light"] + class Thermostat["Thermostat"] + class SmartPlug["SmartPlug"] + class DoorLock["DoorLock"] + class Camera["Camera"] + class DoorbellCamera["DoorbellCamera"] + class SmartSpeaker["SmartSpeaker"] + class MotionSensor["MotionSensor"] + class ContactSensor["ContactSensor"] + class SmokeDetector["SmokeDetector"] + class LeakSensor["LeakSensor"] + class Oven["Oven"] + class RobotVacuum["RobotVacuum"] + class GarageDoorOpener["GarageDoorOpener"] + class Radio["Radio"] + class WifiRadio["WifiRadio"] + class ThreadRadio["ThreadRadio"] + class ZigbeeRadio["ZigbeeRadio"] + class BluetoothRadio["BluetoothRadio"] + class CloudService["CloudService"] + class MobileApp["MobileApp"] + class Automation["Automation"] + class Trigger["Trigger"] + class TimeTrigger["TimeTrigger"] + class PresenceTrigger["PresenceTrigger"] + class SensorTrigger["SensorTrigger"] + class VoiceTrigger["VoiceTrigger"] + class Condition["Condition"] + class Action["Action"] + class Scene["Scene"] + class AutomationRun["AutomationRun"] + class FirmwareImage["FirmwareImage"] + class SecurityPatch["SecurityPatch"] + class FeatureRelease["FeatureRelease"] + class FirmwareUpdate["FirmwareUpdate"] + class RollbackEvent["RollbackEvent"] + class PersonalData["PersonalData"] + class VideoRecording["VideoRecording"] + class AudioRecording["AudioRecording"] + class PresenceHistory["PresenceHistory"] + class DeviceUsageLog["DeviceUsageLog"] + class Consent["Consent"] + class ConsentGrant["ConsentGrant"] + class ConsentWithdrawal["ConsentWithdrawal"] + class PrivacyPolicy["PrivacyPolicy"] + class DataSharingAgreement["DataSharingAgreement"] + class DataSubjectRequest["DataSubjectRequest"] + class DeletionRequest["DeletionRequest"] + class ExportRequest["ExportRequest"] + class OwnerRole["OwnerRole"] + class AdminRole["AdminRole"] + class MemberRole["MemberRole"] + class GuestAccessRole["GuestAccessRole"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + IndependentContinuant <|-- Site + MaterialEntity <|-- Agent + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Agent <|-- Person + InformationContentEntity <|-- Household + Person <|-- Resident + Person <|-- Guest + Resident <|-- Child + Site <|-- Home + Site <|-- Room + Room <|-- Bedroom + Room <|-- Kitchen + Room <|-- LivingRoom + Room <|-- Bathroom + Room <|-- Garage + Object <|-- SmartDevice + SmartDevice <|-- Hub + Hub <|-- ThreadBorderRouter + Hub <|-- ZigbeeCoordinator + SmartDevice <|-- Light + SmartDevice <|-- Thermostat + SmartDevice <|-- SmartPlug + SmartDevice <|-- DoorLock + SmartDevice <|-- Camera + Camera <|-- DoorbellCamera + SmartDevice <|-- SmartSpeaker + SmartDevice <|-- MotionSensor + SmartDevice <|-- ContactSensor + SmartDevice <|-- SmokeDetector + SmartDevice <|-- LeakSensor + SmartDevice <|-- Oven + SmartDevice <|-- RobotVacuum + SmartDevice <|-- GarageDoorOpener + Object <|-- Radio + Radio <|-- WifiRadio + Radio <|-- ThreadRadio + Radio <|-- ZigbeeRadio + Radio <|-- BluetoothRadio + Object <|-- CloudService + Object <|-- MobileApp + InformationContentEntity <|-- Automation + InformationContentEntity <|-- Trigger + Trigger <|-- TimeTrigger + Trigger <|-- PresenceTrigger + Trigger <|-- SensorTrigger + Trigger <|-- VoiceTrigger + InformationContentEntity <|-- Condition + InformationContentEntity <|-- Action + InformationContentEntity <|-- Scene + Process <|-- AutomationRun + InformationContentEntity <|-- FirmwareImage + FirmwareImage <|-- SecurityPatch + FirmwareImage <|-- FeatureRelease + Process <|-- FirmwareUpdate + Process <|-- RollbackEvent + InformationContentEntity <|-- PersonalData + PersonalData <|-- VideoRecording + PersonalData <|-- AudioRecording + PersonalData <|-- PresenceHistory + PersonalData <|-- DeviceUsageLog + InformationContentEntity <|-- Consent + Consent <|-- ConsentGrant + Consent <|-- ConsentWithdrawal + InformationContentEntity <|-- PrivacyPolicy + InformationContentEntity <|-- DataSharingAgreement + Process <|-- DataSubjectRequest + DataSubjectRequest <|-- DeletionRequest + DataSubjectRequest <|-- ExportRequest + Role <|-- OwnerRole + Role <|-- AdminRole + Role <|-- MemberRole + Role <|-- GuestAccessRole + SmartDevice : +String device_name + SmartDevice : +String firmware_version + SmartDevice : +Integer battery_pct + SmartDevice : +Boolean is_online + Camera : +Boolean is_recording + SmartSpeaker : +Boolean is_listening + SmartSpeaker : +Boolean has_hardware_mute + Oven : +Boolean is_on + Thermostat : +Integer target_temp_c + DoorLock : +Boolean is_locked + GarageDoorOpener : +Boolean is_door_open + FirmwareImage : +Boolean is_signed + FirmwareUpdate : +Integer rollout_pct + FirmwareImage : +Boolean is_security_critical + Person : +Integer age_years + Home : +Boolean is_home_occupied + PersonalData : +Integer retention_days + Consent : +Boolean is_active + PersonalData : +Boolean is_shared_with_third_party + VideoRecording : +Boolean is_end_to_end_encrypted + SmartDevice : +Boolean default_password_changed + Automation : +Boolean runs_unattended + SmartDevice --> Hub : paired_with + SmartDevice --> Room : located_in + Room --> Home : part_of_home + SmartDevice --> Radio : uses_radio + Hub --> CloudService : syncs_with + MobileApp --> Hub : controls_via + Resident --> SmartDevice : owns + Resident --> Household : member_of + Trigger --> Automation : triggers_automation + Automation --> Action : performs + Action --> SmartDevice : targets + FirmwareUpdate --> SmartDevice : applies_to + FirmwareUpdate --> FirmwareImage : installs + PersonalData --> SmartDevice : captured_by + PersonalData --> Person : concerns + Consent --> Person : granted_by + Consent --> PersonalData : covers + SmartDevice --> PrivacyPolicy : governed_by + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall p (PersonalData(p) and is_shared_with_third_party = True implies exists c (Consent(c) and covers(c, p))) +%% forall v (VideoRecording(v) implies exists c (ConsentGrant(c) and covers(c, v))) +%% forall s (SmartSpeaker(s) and is_listening = True implies has_hardware_mute = True) +%% forall c (Camera(c) implies not SmartSpeaker(c)) +%% forall c (ConsentGrant(c) implies not ConsentWithdrawal(c)) diff --git a/examples/domain_logistics.cypher b/examples/domain_logistics.cypher new file mode 100644 index 0000000..3bf8831 --- /dev/null +++ b/examples/domain_logistics.cypher @@ -0,0 +1,357 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Agent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Organization'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Shipper'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Consignee'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Carrier'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RoadCarrier'}) +MERGE (p:OntologyClass {name: 'Carrier'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AirCarrier'}) +MERGE (p:OntologyClass {name: 'Carrier'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OceanCarrier'}) +MERGE (p:OntologyClass {name: 'Carrier'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RailCarrier'}) +MERGE (p:OntologyClass {name: 'Carrier'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Supplier'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustomsBroker'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThirdPartyLogisticsProvider'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Facility'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Warehouse'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DistributionCenter'}) +MERGE (p:OntologyClass {name: 'Warehouse'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CrossDock'}) +MERGE (p:OntologyClass {name: 'Warehouse'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ColdStore'}) +MERGE (p:OntologyClass {name: 'Warehouse'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HazmatStore'}) +MERGE (p:OntologyClass {name: 'Warehouse'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Port'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Airport'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RailTerminal'}) +MERGE (p:OntologyClass {name: 'Facility'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StorageZone'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DockDoor'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StorageLocation'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TransportAsset'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Vehicle'}) +MERGE (p:OntologyClass {name: 'TransportAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Truck'}) +MERGE (p:OntologyClass {name: 'Vehicle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReeferTruck'}) +MERGE (p:OntologyClass {name: 'Truck'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Van'}) +MERGE (p:OntologyClass {name: 'Vehicle'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Aircraft'}) +MERGE (p:OntologyClass {name: 'TransportAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Vessel'}) +MERGE (p:OntologyClass {name: 'TransportAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Container'}) +MERGE (p:OntologyClass {name: 'TransportAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReeferContainer'}) +MERGE (p:OntologyClass {name: 'Container'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pallet'}) +MERGE (p:OntologyClass {name: 'TransportAsset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Agent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Driver'}) +MERGE (p:OntologyClass {name: 'Person'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Goods'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GeneralCargo'}) +MERGE (p:OntologyClass {name: 'Goods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PerishableGoods'}) +MERGE (p:OntologyClass {name: 'Goods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FrozenGoods'}) +MERGE (p:OntologyClass {name: 'PerishableGoods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChilledGoods'}) +MERGE (p:OntologyClass {name: 'PerishableGoods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pharmaceuticals'}) +MERGE (p:OntologyClass {name: 'Goods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DangerousGoods'}) +MERGE (p:OntologyClass {name: 'Goods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FlammableGoods'}) +MERGE (p:OntologyClass {name: 'DangerousGoods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CorrosiveGoods'}) +MERGE (p:OntologyClass {name: 'DangerousGoods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OversizedGoods'}) +MERGE (p:OntologyClass {name: 'Goods'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StockKeepingUnit'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InventoryRecord'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Lot'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Order'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PurchaseOrder'}) +MERGE (p:OntologyClass {name: 'Order'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SalesOrder'}) +MERGE (p:OntologyClass {name: 'Order'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TransferOrder'}) +MERGE (p:OntologyClass {name: 'Order'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Shipment'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InboundShipment'}) +MERGE (p:OntologyClass {name: 'Shipment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OutboundShipment'}) +MERGE (p:OntologyClass {name: 'Shipment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ColdChainShipment'}) +MERGE (p:OntologyClass {name: 'Shipment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InternationalShipment'}) +MERGE (p:OntologyClass {name: 'Shipment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Leg'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Pickup'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Delivery'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Receiving'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PutAway'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Picking'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Packing'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustomsClearance'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Exception'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DelayException'}) +MERGE (p:OntologyClass {name: 'Exception'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TemperatureExcursion'}) +MERGE (p:OntologyClass {name: 'Exception'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ShippingDocument'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BillOfLading'}) +MERGE (p:OntologyClass {name: 'ShippingDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CommercialInvoice'}) +MERGE (p:OntologyClass {name: 'ShippingDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PackingList'}) +MERGE (p:OntologyClass {name: 'ShippingDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustomsDeclaration'}) +MERGE (p:OntologyClass {name: 'ShippingDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProofOfDelivery'}) +MERGE (p:OntologyClass {name: 'ShippingDocument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TemperatureLog'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Shipper'}) +MERGE (s)-[:RELATION {name: 'shipped_by'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Consignee'}) +MERGE (s)-[:RELATION {name: 'consigned_to'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Carrier'}) +MERGE (s)-[:RELATION {name: 'carried_by'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Goods'}) +MERGE (s)-[:RELATION {name: 'transports'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Leg'}) +MERGE (s)-[:RELATION {name: 'has_leg'}]->(t); +MERGE (s:OntologyClass {name: 'Leg'}) +MERGE (t:OntologyClass {name: 'TransportAsset'}) +MERGE (s)-[:RELATION {name: 'leg_uses'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Facility'}) +MERGE (s)-[:RELATION {name: 'originates_at'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Facility'}) +MERGE (s)-[:RELATION {name: 'destined_for'}]->(t); +MERGE (s:OntologyClass {name: 'InventoryRecord'}) +MERGE (t:OntologyClass {name: 'StorageLocation'}) +MERGE (s)-[:RELATION {name: 'stored_in'}]->(t); +MERGE (s:OntologyClass {name: 'InventoryRecord'}) +MERGE (t:OntologyClass {name: 'StockKeepingUnit'}) +MERGE (s)-[:RELATION {name: 'tracks'}]->(t); +MERGE (s:OntologyClass {name: 'StorageLocation'}) +MERGE (t:OntologyClass {name: 'Warehouse'}) +MERGE (s)-[:RELATION {name: 'located_in'}]->(t); +MERGE (s:OntologyClass {name: 'StorageZone'}) +MERGE (t:OntologyClass {name: 'Warehouse'}) +MERGE (s)-[:RELATION {name: 'zone_of'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'Order'}) +MERGE (s)-[:RELATION {name: 'fulfils'}]->(t); +MERGE (s:OntologyClass {name: 'Shipment'}) +MERGE (t:OntologyClass {name: 'ShippingDocument'}) +MERGE (s)-[:RELATION {name: 'documented_by'}]->(t); +MERGE (s:OntologyClass {name: 'ColdChainShipment'}) +MERGE (t:OntologyClass {name: 'TemperatureLog'}) +MERGE (s)-[:RELATION {name: 'monitored_by'}]->(t); +MERGE (s:OntologyClass {name: 'Vehicle'}) +MERGE (t:OntologyClass {name: 'Carrier'}) +MERGE (s)-[:RELATION {name: 'operated_by'}]->(t); +MERGE (s:OntologyClass {name: 'Truck'}) +MERGE (t:OntologyClass {name: 'Driver'}) +MERGE (s)-[:RELATION {name: 'driven_by'}]->(t); +MERGE (s:OntologyClass {name: 'CustomsClearance'}) +MERGE (t:OntologyClass {name: 'CustomsBroker'}) +MERGE (s)-[:RELATION {name: 'cleared_by'}]->(t); +MERGE (s:OntologyClass {name: 'Goods'}) +MERGE (t:OntologyClass {name: 'Warehouse'}) +MERGE (s)-[:RELATION {name: 'stored_with'}]->(t); +MERGE (s:OntologyClass {name: 'DangerousGoods'}) +MERGE (t:OntologyClass {name: 'Goods'}) +MERGE (s)-[:RELATION {name: 'segregated_from'}]->(t); +// Axiom Validations +// Axiom validation: ColdStore cold_store_temp_c lte 8 +MATCH (n:`ColdStore`) WHERE NOT (n.`cold_store_temp_c` <= 8) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Vehicle loaded_weight_kg gte 0 +MATCH (n:`Vehicle`) WHERE NOT (n.`loaded_weight_kg` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Vehicle loaded_weight_kg lte 44000 +MATCH (n:`Vehicle`) WHERE NOT (n.`loaded_weight_kg` <= 44000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Driver driving_hours_today lte 9 +MATCH (n:`Driver`) WHERE NOT (n.`driving_hours_today` <= 9) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: FrozenGoods frozen_goods_temp_c lte -18 +MATCH (n:`FrozenGoods`) WHERE NOT (n.`frozen_goods_temp_c` <= -18) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: ChilledGoods chilled_goods_temp_c gte 2 +MATCH (n:`ChilledGoods`) WHERE NOT (n.`chilled_goods_temp_c` >= 2) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: ChilledGoods chilled_goods_temp_c lte 8 +MATCH (n:`ChilledGoods`) WHERE NOT (n.`chilled_goods_temp_c` <= 8) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Pharmaceuticals pharma_temp_c gte 2 +MATCH (n:`Pharmaceuticals`) WHERE NOT (n.`pharma_temp_c` >= 2) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Pharmaceuticals pharma_temp_c lte 8 +MATCH (n:`Pharmaceuticals`) WHERE NOT (n.`pharma_temp_c` <= 8) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: InventoryRecord on_hand_quantity gte 0 +MATCH (n:`InventoryRecord`) WHERE NOT (n.`on_hand_quantity` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: InventoryRecord reserved_quantity gte 0 +MATCH (n:`InventoryRecord`) WHERE NOT (n.`reserved_quantity` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: InternationalShipment has_customs_declaration eq True +MATCH (n:`InternationalShipment`) WHERE NOT (n.`has_customs_declaration` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall x (not Shipper(x) and Carrier(x)) +// forall x (not DangerousGoods(x) and GeneralCargo(x)) +// forall x (not InboundShipment(x) and OutboundShipment(x)) +// forall x (not FrozenGoods(x) and ChilledGoods(x)) +// forall x (not HazmatStore(x) and ColdStore(x)) +// forall s (Shipment(s) and is_delivered = True implies has_proof_of_delivery = True) diff --git a/examples/domain_logistics.d2 b/examples/domain_logistics.d2 new file mode 100644 index 0000000..e99b63d --- /dev/null +++ b/examples/domain_logistics.d2 @@ -0,0 +1,223 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Agent": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Organization": { shape: class } +"Shipper": { shape: class } +"Consignee": { shape: class } +"Carrier": { shape: class } +"RoadCarrier": { shape: class } +"AirCarrier": { shape: class } +"OceanCarrier": { shape: class } +"RailCarrier": { shape: class } +"Supplier": { shape: class } +"CustomsBroker": { shape: class } +"ThirdPartyLogisticsProvider": { shape: class } +"Facility": { shape: class } +"Warehouse": { shape: class } +"DistributionCenter": { shape: class } +"CrossDock": { shape: class } +"ColdStore": { shape: class } +"HazmatStore": { shape: class } +"Port": { shape: class } +"Airport": { shape: class } +"RailTerminal": { shape: class } +"StorageZone": { shape: class } +"DockDoor": { shape: class } +"StorageLocation": { shape: class } +"TransportAsset": { shape: class } +"Vehicle": { shape: class } +"Truck": { shape: class } +"ReeferTruck": { shape: class } +"Van": { shape: class } +"Aircraft": { shape: class } +"Vessel": { shape: class } +"Container": { shape: class } +"ReeferContainer": { shape: class } +"Pallet": { shape: class } +"Person": { shape: class } +"Driver": { shape: class } +"Goods": { shape: class } +"GeneralCargo": { shape: class } +"PerishableGoods": { shape: class } +"FrozenGoods": { shape: class } +"ChilledGoods": { shape: class } +"Pharmaceuticals": { shape: class } +"DangerousGoods": { shape: class } +"FlammableGoods": { shape: class } +"CorrosiveGoods": { shape: class } +"OversizedGoods": { shape: class } +"StockKeepingUnit": { shape: class } +"InventoryRecord": { shape: class } +"Lot": { shape: class } +"Order": { shape: class } +"PurchaseOrder": { shape: class } +"SalesOrder": { shape: class } +"TransferOrder": { shape: class } +"Shipment": { shape: class } +"InboundShipment": { shape: class } +"OutboundShipment": { shape: class } +"ColdChainShipment": { shape: class } +"InternationalShipment": { shape: class } +"Leg": { shape: class } +"Pickup": { shape: class } +"Delivery": { shape: class } +"Receiving": { shape: class } +"PutAway": { shape: class } +"Picking": { shape: class } +"Packing": { shape: class } +"CustomsClearance": { shape: class } +"Exception": { shape: class } +"DelayException": { shape: class } +"TemperatureExcursion": { shape: class } +"ShippingDocument": { shape: class } +"BillOfLading": { shape: class } +"CommercialInvoice": { shape: class } +"PackingList": { shape: class } +"CustomsDeclaration": { shape: class } +"ProofOfDelivery": { shape: class } +"TemperatureLog": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Agent" -> "Object" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Organization" -> "Agent" +"Shipper" -> "Organization" +"Consignee" -> "Organization" +"Carrier" -> "Organization" +"RoadCarrier" -> "Carrier" +"AirCarrier" -> "Carrier" +"OceanCarrier" -> "Carrier" +"RailCarrier" -> "Carrier" +"Supplier" -> "Organization" +"CustomsBroker" -> "Organization" +"ThirdPartyLogisticsProvider" -> "Organization" +"Facility" -> "Site" +"Warehouse" -> "Facility" +"DistributionCenter" -> "Warehouse" +"CrossDock" -> "Warehouse" +"ColdStore" -> "Warehouse" +"HazmatStore" -> "Warehouse" +"Port" -> "Facility" +"Airport" -> "Facility" +"RailTerminal" -> "Facility" +"StorageZone" -> "Site" +"DockDoor" -> "Site" +"StorageLocation" -> "Site" +"TransportAsset" -> "Object" +"Vehicle" -> "TransportAsset" +"Truck" -> "Vehicle" +"ReeferTruck" -> "Truck" +"Van" -> "Vehicle" +"Aircraft" -> "TransportAsset" +"Vessel" -> "TransportAsset" +"Container" -> "TransportAsset" +"ReeferContainer" -> "Container" +"Pallet" -> "TransportAsset" +"Person" -> "Agent" +"Driver" -> "Person" +"Goods" -> "MaterialEntity" +"GeneralCargo" -> "Goods" +"PerishableGoods" -> "Goods" +"FrozenGoods" -> "PerishableGoods" +"ChilledGoods" -> "PerishableGoods" +"Pharmaceuticals" -> "Goods" +"DangerousGoods" -> "Goods" +"FlammableGoods" -> "DangerousGoods" +"CorrosiveGoods" -> "DangerousGoods" +"OversizedGoods" -> "Goods" +"StockKeepingUnit" -> "InformationContentEntity" +"InventoryRecord" -> "InformationContentEntity" +"Lot" -> "InformationContentEntity" +"Order" -> "InformationContentEntity" +"PurchaseOrder" -> "Order" +"SalesOrder" -> "Order" +"TransferOrder" -> "Order" +"Shipment" -> "Process" +"InboundShipment" -> "Shipment" +"OutboundShipment" -> "Shipment" +"ColdChainShipment" -> "Shipment" +"InternationalShipment" -> "Shipment" +"Leg" -> "Process" +"Pickup" -> "Process" +"Delivery" -> "Process" +"Receiving" -> "Process" +"PutAway" -> "Process" +"Picking" -> "Process" +"Packing" -> "Process" +"CustomsClearance" -> "Process" +"Exception" -> "Process" +"DelayException" -> "Exception" +"TemperatureExcursion" -> "Exception" +"ShippingDocument" -> "InformationContentEntity" +"BillOfLading" -> "ShippingDocument" +"CommercialInvoice" -> "ShippingDocument" +"PackingList" -> "ShippingDocument" +"CustomsDeclaration" -> "ShippingDocument" +"ProofOfDelivery" -> "ShippingDocument" +"TemperatureLog" -> "InformationContentEntity" +"Shipment"."tracking_number": String +"Shipment"."gross_weight_kg": Integer +"Shipment"."transit_hours": Integer +"Shipment"."is_delivered": Boolean +"Shipment"."has_proof_of_delivery": Boolean +"Shipment"."has_customs_declaration": Boolean +"Vehicle"."payload_capacity_kg": Integer +"Vehicle"."loaded_weight_kg": Integer +"ReeferContainer"."reefer_set_point_c": Integer +"ColdStore"."cold_store_temp_c": Integer +"FrozenGoods"."frozen_goods_temp_c": Integer +"ChilledGoods"."chilled_goods_temp_c": Integer +"Pharmaceuticals"."pharma_temp_c": Integer +"InventoryRecord"."on_hand_quantity": Integer +"InventoryRecord"."reserved_quantity": Integer +"InventoryRecord"."reorder_point": Integer +"Lot"."shelf_life_days": Integer +"Warehouse"."storage_capacity_pallets": Integer +"Driver"."driving_hours_today": Integer +"DangerousGoods"."un_number": String +"Shipment" -> "Shipper": shipped_by +"Shipment" -> "Consignee": consigned_to +"Shipment" -> "Carrier": carried_by +"Shipment" -> "Goods": transports +"Shipment" -> "Leg": has_leg +"Leg" -> "TransportAsset": leg_uses +"Shipment" -> "Facility": originates_at +"Shipment" -> "Facility": destined_for +"InventoryRecord" -> "StorageLocation": stored_in +"InventoryRecord" -> "StockKeepingUnit": tracks +"StorageLocation" -> "Warehouse": located_in +"StorageZone" -> "Warehouse": zone_of +"Shipment" -> "Order": fulfils +"Shipment" -> "ShippingDocument": documented_by +"ColdChainShipment" -> "TemperatureLog": monitored_by +"Vehicle" -> "Carrier": operated_by +"Truck" -> "Driver": driven_by +"CustomsClearance" -> "CustomsBroker": cleared_by +"Goods" -> "Warehouse": stored_with +"DangerousGoods" -> "Goods": segregated_from +# WARNING: The following axioms could not be mapped to field constraints: +# forall x (not Shipper(x) and Carrier(x)) +# forall x (not DangerousGoods(x) and GeneralCargo(x)) +# forall x (not InboundShipment(x) and OutboundShipment(x)) +# forall x (not FrozenGoods(x) and ChilledGoods(x)) +# forall x (not HazmatStore(x) and ColdStore(x)) +# forall s (Shipment(s) and is_delivered = True implies has_proof_of_delivery = True) diff --git a/examples/domain_logistics.d2.svg b/examples/domain_logistics.d2.svg new file mode 100644 index 0000000..3487b1b --- /dev/null +++ b/examples/domain_logistics.d2.svg @@ -0,0 +1,121 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectAgentSiteOccurrentProcessRoleFunctionQualityInformationContentEntityOrganizationShipperConsigneeCarrierRoadCarrierAirCarrierOceanCarrierRailCarrierSupplierCustomsBrokerThirdPartyLogisticsProviderFacilityWarehouse+storage_capacity_palletsIntegerDistributionCenterCrossDockColdStore+cold_store_temp_cIntegerHazmatStorePortAirportRailTerminalStorageZoneDockDoorStorageLocationTransportAssetVehicle+payload_capacity_kgInteger+loaded_weight_kgIntegerTruckReeferTruckVanAircraftVesselContainerReeferContainer+reefer_set_point_cIntegerPalletPersonDriver+driving_hours_todayIntegerGoodsGeneralCargoPerishableGoodsFrozenGoods+frozen_goods_temp_cIntegerChilledGoods+chilled_goods_temp_cIntegerPharmaceuticals+pharma_temp_cIntegerDangerousGoods+un_numberStringFlammableGoodsCorrosiveGoodsOversizedGoodsStockKeepingUnitInventoryRecord+on_hand_quantityInteger+reserved_quantityInteger+reorder_pointIntegerLot+shelf_life_daysIntegerOrderPurchaseOrderSalesOrderTransferOrderShipment+tracking_numberString+gross_weight_kgInteger+transit_hoursInteger+is_deliveredBoolean+has_proof_of_deliveryBoolean+has_customs_declarationBooleanInboundShipmentOutboundShipmentColdChainShipmentInternationalShipmentLegPickupDeliveryReceivingPutAwayPickingPackingCustomsClearanceExceptionDelayExceptionTemperatureExcursionShippingDocumentBillOfLadingCommercialInvoicePackingListCustomsDeclarationProofOfDeliveryTemperatureLog shipped_byconsigned_tocarried_bytransportshas_legleg_usesoriginates_atdestined_forstored_intrackslocated_inzone_offulfilsdocumented_bymonitored_byoperated_bydriven_bycleared_bystored_withsegregated_from + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_logistics.logic b/examples/domain_logistics.logic new file mode 100644 index 0000000..6e529f3 --- /dev/null +++ b/examples/domain_logistics.logic @@ -0,0 +1,184 @@ +; ===================================================================== +; Domain: Logistics and Supply Chain +; Models shipments, warehouses, carriers, inventory, transport assets and +; cold-chain monitoring on a condensed BFO upper level. +; Axioms enforce: cold-chain temperature limits, hazmat segregation, +; vehicle weight limits, shipment documentation and inventory integrity +; (stock quantities never negative). +; ===================================================================== + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Agent Object) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Organisations --- +(def-concept Organization Agent) +(def-concept Shipper Organization) +(def-concept Consignee Organization) +(def-concept Carrier Organization) +(def-concept RoadCarrier Carrier) +(def-concept AirCarrier Carrier) +(def-concept OceanCarrier Carrier) +(def-concept RailCarrier Carrier) +(def-concept Supplier Organization) +(def-concept CustomsBroker Organization) +(def-concept ThirdPartyLogisticsProvider Organization) + +; --- Facilities --- +(def-concept Facility Site) +(def-concept Warehouse Facility) +(def-concept DistributionCenter Warehouse) +(def-concept CrossDock Warehouse) +(def-concept ColdStore Warehouse) +(def-concept HazmatStore Warehouse) +(def-concept Port Facility) +(def-concept Airport Facility) +(def-concept RailTerminal Facility) +(def-concept StorageZone Site) +(def-concept DockDoor Site) +(def-concept StorageLocation Site) + +; --- Transport Assets --- +(def-concept TransportAsset Object) +(def-concept Vehicle TransportAsset) +(def-concept Truck Vehicle) +(def-concept ReeferTruck Truck) +(def-concept Van Vehicle) +(def-concept Aircraft TransportAsset) +(def-concept Vessel TransportAsset) +(def-concept Container TransportAsset) +(def-concept ReeferContainer Container) +(def-concept Pallet TransportAsset) +(def-concept Person Agent) +(def-concept Driver Person) + +; --- Goods --- +(def-concept Goods MaterialEntity) +(def-concept GeneralCargo Goods) +(def-concept PerishableGoods Goods) +(def-concept FrozenGoods PerishableGoods) +(def-concept ChilledGoods PerishableGoods) +(def-concept Pharmaceuticals Goods) +(def-concept DangerousGoods Goods) +(def-concept FlammableGoods DangerousGoods) +(def-concept CorrosiveGoods DangerousGoods) +(def-concept OversizedGoods Goods) +(def-concept StockKeepingUnit InformationContentEntity) +(def-concept InventoryRecord InformationContentEntity) +(def-concept Lot InformationContentEntity) + +; --- Shipments and Orders --- +(def-concept Order InformationContentEntity) +(def-concept PurchaseOrder Order) +(def-concept SalesOrder Order) +(def-concept TransferOrder Order) +(def-concept Shipment Process) +(def-concept InboundShipment Shipment) +(def-concept OutboundShipment Shipment) +(def-concept ColdChainShipment Shipment) +(def-concept InternationalShipment Shipment) +(def-concept Leg Process) +(def-concept Pickup Process) +(def-concept Delivery Process) +(def-concept Receiving Process) +(def-concept PutAway Process) +(def-concept Picking Process) +(def-concept Packing Process) +(def-concept CustomsClearance Process) +(def-concept Exception Process) +(def-concept DelayException Exception) +(def-concept TemperatureExcursion Exception) + +; --- Documents --- +(def-concept ShippingDocument InformationContentEntity) +(def-concept BillOfLading ShippingDocument) +(def-concept CommercialInvoice ShippingDocument) +(def-concept PackingList ShippingDocument) +(def-concept CustomsDeclaration ShippingDocument) +(def-concept ProofOfDelivery ShippingDocument) +(def-concept TemperatureLog InformationContentEntity) + +; --- Properties --- +(def-property tracking_number Shipment String :cardinality 1..1) +(def-property gross_weight_kg Shipment Integer) +(def-property transit_hours Shipment Integer) +(def-property is_delivered Shipment Boolean) +(def-property has_proof_of_delivery Shipment Boolean) +(def-property has_customs_declaration Shipment Boolean) +(def-property payload_capacity_kg Vehicle Integer) +(def-property loaded_weight_kg Vehicle Integer) +(def-property reefer_set_point_c ReeferContainer Integer) +(def-property cold_store_temp_c ColdStore Integer) +(def-property frozen_goods_temp_c FrozenGoods Integer) +(def-property chilled_goods_temp_c ChilledGoods Integer) +(def-property pharma_temp_c Pharmaceuticals Integer) +(def-property on_hand_quantity InventoryRecord Integer) +(def-property reserved_quantity InventoryRecord Integer) +(def-property reorder_point InventoryRecord Integer) +(def-property shelf_life_days Lot Integer) +(def-property storage_capacity_pallets Warehouse Integer) +(def-property driving_hours_today Driver Integer) +(def-property un_number DangerousGoods String) + +; --- Relations --- +(def-relation shipped_by Shipment Shipper) +(def-relation consigned_to Shipment Consignee) +(def-relation carried_by Shipment Carrier :cardinality 1..*) +(def-relation transports Shipment Goods :cardinality 1..*) +(def-relation has_leg Shipment Leg :cardinality 1..*) +(def-relation leg_uses Leg TransportAsset) +(def-relation originates_at Shipment Facility) +(def-relation destined_for Shipment Facility) +(def-relation stored_in InventoryRecord StorageLocation) +(def-relation tracks InventoryRecord StockKeepingUnit) +(def-relation located_in StorageLocation Warehouse) +(def-relation zone_of StorageZone Warehouse) +(def-relation fulfils Shipment Order) +(def-relation documented_by Shipment ShippingDocument) +(def-relation monitored_by ColdChainShipment TemperatureLog) +(def-relation operated_by Vehicle Carrier) +(def-relation driven_by Truck Driver) +(def-relation cleared_by CustomsClearance CustomsBroker) +(def-relation stored_with Goods Warehouse) +(def-relation segregated_from DangerousGoods Goods) + +; --- Axioms --- +; 1. Integrity: shippers and carriers are distinct organisation roles +(forall (x) (not (and (Shipper x) (Carrier x)))) +; 2. Integrity: dangerous goods are never general cargo +(forall (x) (not (and (DangerousGoods x) (GeneralCargo x)))) +; 3. Integrity: inbound and outbound shipments are distinct +(forall (x) (not (and (InboundShipment x) (OutboundShipment x)))) +; 4. Integrity: frozen and chilled goods use different temperature regimes +(forall (x) (not (and (FrozenGoods x) (ChilledGoods x)))) +; 5. Integrity: dangerous goods are only kept in hazmat stores, never cold stores +(forall (x) (not (and (HazmatStore x) (ColdStore x)))) +; 6. Cold chain: frozen goods are kept at minus 18 C or below +(forall (g) (implies (FrozenGoods g) (lte frozen_goods_temp_c -18))) +; 7. Cold chain: chilled goods are kept between 2 C and 8 C +(forall (g) (implies (ChilledGoods g) (and (gte chilled_goods_temp_c 2) (lte chilled_goods_temp_c 8)))) +; 8. Cold chain: pharmaceuticals are kept between 2 C and 8 C +(forall (g) (implies (Pharmaceuticals g) (and (gte pharma_temp_c 2) (lte pharma_temp_c 8)))) +; 9. Cold chain: cold stores operate at 8 C or below +(forall (w) (implies (ColdStore w) (lte cold_store_temp_c 8))) +; 10. Safety: no road vehicle may be loaded above the 44000 kg legal gross limit +(forall (v) (implies (Vehicle v) (and (gte loaded_weight_kg 0) (lte loaded_weight_kg 44000)))) +; 11. Safety: driver hours are capped at 9 per day +(forall (d) (implies (Driver d) (lte driving_hours_today 9))) +; 12. Integrity: on-hand and reserved inventory quantities are never negative +(forall (r) (implies (InventoryRecord r) (and (gte on_hand_quantity 0) (gte reserved_quantity 0)))) +; 13. Documentation: delivered shipments need proof of delivery +(forall (s) (implies (and (Shipment s) (eq is_delivered True)) (eq has_proof_of_delivery True))) +; 14. Documentation: international shipments need a customs declaration +(forall (s) (implies (InternationalShipment s) (eq has_customs_declaration True))) diff --git a/examples/domain_logistics.mmd b/examples/domain_logistics.mmd new file mode 100644 index 0000000..6937249 --- /dev/null +++ b/examples/domain_logistics.mmd @@ -0,0 +1,224 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Agent["Agent"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Organization["Organization"] + class Shipper["Shipper"] + class Consignee["Consignee"] + class Carrier["Carrier"] + class RoadCarrier["RoadCarrier"] + class AirCarrier["AirCarrier"] + class OceanCarrier["OceanCarrier"] + class RailCarrier["RailCarrier"] + class Supplier["Supplier"] + class CustomsBroker["CustomsBroker"] + class ThirdPartyLogisticsProvider["ThirdPartyLogisticsProvider"] + class Facility["Facility"] + class Warehouse["Warehouse"] + class DistributionCenter["DistributionCenter"] + class CrossDock["CrossDock"] + class ColdStore["ColdStore"] + class HazmatStore["HazmatStore"] + class Port["Port"] + class Airport["Airport"] + class RailTerminal["RailTerminal"] + class StorageZone["StorageZone"] + class DockDoor["DockDoor"] + class StorageLocation["StorageLocation"] + class TransportAsset["TransportAsset"] + class Vehicle["Vehicle"] + class Truck["Truck"] + class ReeferTruck["ReeferTruck"] + class Van["Van"] + class Aircraft["Aircraft"] + class Vessel["Vessel"] + class Container["Container"] + class ReeferContainer["ReeferContainer"] + class Pallet["Pallet"] + class Person["Person"] + class Driver["Driver"] + class Goods["Goods"] + class GeneralCargo["GeneralCargo"] + class PerishableGoods["PerishableGoods"] + class FrozenGoods["FrozenGoods"] + class ChilledGoods["ChilledGoods"] + class Pharmaceuticals["Pharmaceuticals"] + class DangerousGoods["DangerousGoods"] + class FlammableGoods["FlammableGoods"] + class CorrosiveGoods["CorrosiveGoods"] + class OversizedGoods["OversizedGoods"] + class StockKeepingUnit["StockKeepingUnit"] + class InventoryRecord["InventoryRecord"] + class Lot["Lot"] + class Order["Order"] + class PurchaseOrder["PurchaseOrder"] + class SalesOrder["SalesOrder"] + class TransferOrder["TransferOrder"] + class Shipment["Shipment"] + class InboundShipment["InboundShipment"] + class OutboundShipment["OutboundShipment"] + class ColdChainShipment["ColdChainShipment"] + class InternationalShipment["InternationalShipment"] + class Leg["Leg"] + class Pickup["Pickup"] + class Delivery["Delivery"] + class Receiving["Receiving"] + class PutAway["PutAway"] + class Picking["Picking"] + class Packing["Packing"] + class CustomsClearance["CustomsClearance"] + class Exception["Exception"] + class DelayException["DelayException"] + class TemperatureExcursion["TemperatureExcursion"] + class ShippingDocument["ShippingDocument"] + class BillOfLading["BillOfLading"] + class CommercialInvoice["CommercialInvoice"] + class PackingList["PackingList"] + class CustomsDeclaration["CustomsDeclaration"] + class ProofOfDelivery["ProofOfDelivery"] + class TemperatureLog["TemperatureLog"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Object <|-- Agent + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Agent <|-- Organization + Organization <|-- Shipper + Organization <|-- Consignee + Organization <|-- Carrier + Carrier <|-- RoadCarrier + Carrier <|-- AirCarrier + Carrier <|-- OceanCarrier + Carrier <|-- RailCarrier + Organization <|-- Supplier + Organization <|-- CustomsBroker + Organization <|-- ThirdPartyLogisticsProvider + Site <|-- Facility + Facility <|-- Warehouse + Warehouse <|-- DistributionCenter + Warehouse <|-- CrossDock + Warehouse <|-- ColdStore + Warehouse <|-- HazmatStore + Facility <|-- Port + Facility <|-- Airport + Facility <|-- RailTerminal + Site <|-- StorageZone + Site <|-- DockDoor + Site <|-- StorageLocation + Object <|-- TransportAsset + TransportAsset <|-- Vehicle + Vehicle <|-- Truck + Truck <|-- ReeferTruck + Vehicle <|-- Van + TransportAsset <|-- Aircraft + TransportAsset <|-- Vessel + TransportAsset <|-- Container + Container <|-- ReeferContainer + TransportAsset <|-- Pallet + Agent <|-- Person + Person <|-- Driver + MaterialEntity <|-- Goods + Goods <|-- GeneralCargo + Goods <|-- PerishableGoods + PerishableGoods <|-- FrozenGoods + PerishableGoods <|-- ChilledGoods + Goods <|-- Pharmaceuticals + Goods <|-- DangerousGoods + DangerousGoods <|-- FlammableGoods + DangerousGoods <|-- CorrosiveGoods + Goods <|-- OversizedGoods + InformationContentEntity <|-- StockKeepingUnit + InformationContentEntity <|-- InventoryRecord + InformationContentEntity <|-- Lot + InformationContentEntity <|-- Order + Order <|-- PurchaseOrder + Order <|-- SalesOrder + Order <|-- TransferOrder + Process <|-- Shipment + Shipment <|-- InboundShipment + Shipment <|-- OutboundShipment + Shipment <|-- ColdChainShipment + Shipment <|-- InternationalShipment + Process <|-- Leg + Process <|-- Pickup + Process <|-- Delivery + Process <|-- Receiving + Process <|-- PutAway + Process <|-- Picking + Process <|-- Packing + Process <|-- CustomsClearance + Process <|-- Exception + Exception <|-- DelayException + Exception <|-- TemperatureExcursion + InformationContentEntity <|-- ShippingDocument + ShippingDocument <|-- BillOfLading + ShippingDocument <|-- CommercialInvoice + ShippingDocument <|-- PackingList + ShippingDocument <|-- CustomsDeclaration + ShippingDocument <|-- ProofOfDelivery + InformationContentEntity <|-- TemperatureLog + Shipment : +String tracking_number + Shipment : +Integer gross_weight_kg + Shipment : +Integer transit_hours + Shipment : +Boolean is_delivered + Shipment : +Boolean has_proof_of_delivery + Shipment : +Boolean has_customs_declaration + Vehicle : +Integer payload_capacity_kg + Vehicle : +Integer loaded_weight_kg + ReeferContainer : +Integer reefer_set_point_c + ColdStore : +Integer cold_store_temp_c + FrozenGoods : +Integer frozen_goods_temp_c + ChilledGoods : +Integer chilled_goods_temp_c + Pharmaceuticals : +Integer pharma_temp_c + InventoryRecord : +Integer on_hand_quantity + InventoryRecord : +Integer reserved_quantity + InventoryRecord : +Integer reorder_point + Lot : +Integer shelf_life_days + Warehouse : +Integer storage_capacity_pallets + Driver : +Integer driving_hours_today + DangerousGoods : +String un_number + Shipment --> Shipper : shipped_by + Shipment --> Consignee : consigned_to + Shipment --> Carrier : carried_by + Shipment --> Goods : transports + Shipment --> Leg : has_leg + Leg --> TransportAsset : leg_uses + Shipment --> Facility : originates_at + Shipment --> Facility : destined_for + InventoryRecord --> StorageLocation : stored_in + InventoryRecord --> StockKeepingUnit : tracks + StorageLocation --> Warehouse : located_in + StorageZone --> Warehouse : zone_of + Shipment --> Order : fulfils + Shipment --> ShippingDocument : documented_by + ColdChainShipment --> TemperatureLog : monitored_by + Vehicle --> Carrier : operated_by + Truck --> Driver : driven_by + CustomsClearance --> CustomsBroker : cleared_by + Goods --> Warehouse : stored_with + DangerousGoods --> Goods : segregated_from + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall x (not Shipper(x) and Carrier(x)) +%% forall x (not DangerousGoods(x) and GeneralCargo(x)) +%% forall x (not InboundShipment(x) and OutboundShipment(x)) +%% forall x (not FrozenGoods(x) and ChilledGoods(x)) +%% forall x (not HazmatStore(x) and ColdStore(x)) +%% forall s (Shipment(s) and is_delivered = True implies has_proof_of_delivery = True) diff --git a/examples/domain_research_projects.cypher b/examples/domain_research_projects.cypher new file mode 100644 index 0000000..9c9dc1c --- /dev/null +++ b/examples/domain_research_projects.cypher @@ -0,0 +1,331 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Organization'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'University'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ResearchInstitute'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FundingAgency'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PublicFunder'}) +MERGE (p:OntologyClass {name: 'FundingAgency'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PrivateFoundation'}) +MERGE (p:OntologyClass {name: 'FundingAgency'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Publisher'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EthicsCommittee'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Department'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ResearchGroup'}) +MERGE (p:OntologyClass {name: 'Organization'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Investigator'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PrincipalInvestigator'}) +MERGE (p:OntologyClass {name: 'Investigator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CoInvestigator'}) +MERGE (p:OntologyClass {name: 'Investigator'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PostdoctoralResearcher'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DoctoralStudent'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ResearchParticipant'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Reviewer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Author'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FundingInstrument'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Grant'}) +MERGE (p:OntologyClass {name: 'FundingInstrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProjectGrant'}) +MERGE (p:OntologyClass {name: 'Grant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FellowshipGrant'}) +MERGE (p:OntologyClass {name: 'Grant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProposalDocument'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Budget'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BudgetLine'}) +MERGE (p:OntologyClass {name: 'Budget'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataManagementPlan'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProgressReport'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FinalReport'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConflictOfInterestDeclaration'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ResearchProject'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Study'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ObservationalStudy'}) +MERGE (p:OntologyClass {name: 'Study'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ClinicalTrial'}) +MERGE (p:OntologyClass {name: 'Study'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SurveyStudy'}) +MERGE (p:OntologyClass {name: 'Study'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ComputationalStudy'}) +MERGE (p:OntologyClass {name: 'Study'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HumanSubjectsStudy'}) +MERGE (p:OntologyClass {name: 'Study'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Experiment'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Enrolment'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PeerReview'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EthicsReview'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EthicsApproval'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformedConsent'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StudyProtocol'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PreRegistration'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AdverseEventReport'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Dataset'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RawDataset'}) +MERGE (p:OntologyClass {name: 'Dataset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessedDataset'}) +MERGE (p:OntologyClass {name: 'Dataset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SensitiveDataset'}) +MERGE (p:OntologyClass {name: 'Dataset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OpenDataset'}) +MERGE (p:OntologyClass {name: 'Dataset'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Metadata'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Codebook'}) +MERGE (p:OntologyClass {name: 'Metadata'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Software'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Publication'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'JournalArticle'}) +MERGE (p:OntologyClass {name: 'Publication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConferencePaper'}) +MERGE (p:OntologyClass {name: 'Publication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Preprint'}) +MERGE (p:OntologyClass {name: 'Publication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Thesis'}) +MERGE (p:OntologyClass {name: 'Publication'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Citation'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Journal'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Repository'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Grant'}) +MERGE (t:OntologyClass {name: 'FundingAgency'}) +MERGE (s)-[:RELATION {name: 'awarded_by'}]->(t); +MERGE (s:OntologyClass {name: 'Grant'}) +MERGE (t:OntologyClass {name: 'Organization'}) +MERGE (s)-[:RELATION {name: 'held_by'}]->(t); +MERGE (s:OntologyClass {name: 'Grant'}) +MERGE (t:OntologyClass {name: 'PrincipalInvestigator'}) +MERGE (s)-[:RELATION {name: 'led_by'}]->(t); +MERGE (s:OntologyClass {name: 'ResearchProject'}) +MERGE (t:OntologyClass {name: 'Grant'}) +MERGE (s)-[:RELATION {name: 'funds'}]->(t); +MERGE (s:OntologyClass {name: 'Grant'}) +MERGE (t:OntologyClass {name: 'Budget'}) +MERGE (s)-[:RELATION {name: 'has_budget'}]->(t); +MERGE (s:OntologyClass {name: 'Budget'}) +MERGE (t:OntologyClass {name: 'BudgetLine'}) +MERGE (s)-[:RELATION {name: 'includes_line'}]->(t); +MERGE (s:OntologyClass {name: 'ProposalDocument'}) +MERGE (t:OntologyClass {name: 'ResearchProject'}) +MERGE (s)-[:RELATION {name: 'proposes'}]->(t); +MERGE (s:OntologyClass {name: 'Person'}) +MERGE (t:OntologyClass {name: 'Organization'}) +MERGE (s)-[:RELATION {name: 'employed_by'}]->(t); +MERGE (s:OntologyClass {name: 'Person'}) +MERGE (t:OntologyClass {name: 'ResearchGroup'}) +MERGE (s)-[:RELATION {name: 'member_of'}]->(t); +MERGE (s:OntologyClass {name: 'Investigator'}) +MERGE (t:OntologyClass {name: 'Study'}) +MERGE (s)-[:RELATION {name: 'conducts'}]->(t); +MERGE (s:OntologyClass {name: 'Study'}) +MERGE (t:OntologyClass {name: 'ResearchProject'}) +MERGE (s)-[:RELATION {name: 'part_of_project'}]->(t); +MERGE (s:OntologyClass {name: 'Study'}) +MERGE (t:OntologyClass {name: 'StudyProtocol'}) +MERGE (s)-[:RELATION {name: 'governed_by'}]->(t); +MERGE (s:OntologyClass {name: 'Study'}) +MERGE (t:OntologyClass {name: 'EthicsApproval'}) +MERGE (s)-[:RELATION {name: 'approved_by_ethics'}]->(t); +MERGE (s:OntologyClass {name: 'EthicsApproval'}) +MERGE (t:OntologyClass {name: 'EthicsCommittee'}) +MERGE (s)-[:RELATION {name: 'issued_by'}]->(t); +MERGE (s:OntologyClass {name: 'Enrolment'}) +MERGE (t:OntologyClass {name: 'ResearchParticipant'}) +MERGE (s)-[:RELATION {name: 'enrols'}]->(t); +MERGE (s:OntologyClass {name: 'Enrolment'}) +MERGE (t:OntologyClass {name: 'Study'}) +MERGE (s)-[:RELATION {name: 'enrolment_in'}]->(t); +MERGE (s:OntologyClass {name: 'Enrolment'}) +MERGE (t:OntologyClass {name: 'InformedConsent'}) +MERGE (s)-[:RELATION {name: 'has_consent'}]->(t); +MERGE (s:OntologyClass {name: 'Study'}) +MERGE (t:OntologyClass {name: 'Dataset'}) +MERGE (s)-[:RELATION {name: 'generates'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessedDataset'}) +MERGE (t:OntologyClass {name: 'RawDataset'}) +MERGE (s)-[:RELATION {name: 'derived_from_dataset'}]->(t); +MERGE (s:OntologyClass {name: 'Dataset'}) +MERGE (t:OntologyClass {name: 'Metadata'}) +MERGE (s)-[:RELATION {name: 'described_by'}]->(t); +MERGE (s:OntologyClass {name: 'Dataset'}) +MERGE (t:OntologyClass {name: 'Repository'}) +MERGE (s)-[:RELATION {name: 'deposited_in'}]->(t); +MERGE (s:OntologyClass {name: 'ResearchProject'}) +MERGE (t:OntologyClass {name: 'DataManagementPlan'}) +MERGE (s)-[:RELATION {name: 'governed_by_plan'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Study'}) +MERGE (s)-[:RELATION {name: 'reports_on'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Dataset'}) +MERGE (s)-[:RELATION {name: 'uses_dataset'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Author'}) +MERGE (s)-[:RELATION {name: 'authored_by'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Journal'}) +MERGE (s)-[:RELATION {name: 'published_in'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Publication'}) +MERGE (s)-[:RELATION {name: 'cites'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Grant'}) +MERGE (s)-[:RELATION {name: 'acknowledges'}]->(t); +MERGE (s:OntologyClass {name: 'Publication'}) +MERGE (t:OntologyClass {name: 'Reviewer'}) +MERGE (s)-[:RELATION {name: 'reviewed_by'}]->(t); +MERGE (s:OntologyClass {name: 'ConflictOfInterestDeclaration'}) +MERGE (t:OntologyClass {name: 'Author'}) +MERGE (s)-[:RELATION {name: 'declares'}]->(t); +// Axiom Validations +// Axiom validation: Budget budget_total gte 0 +MATCH (n:`Budget`) WHERE NOT (n.`budget_total` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Budget budget_total lte 10000000 +MATCH (n:`Budget`) WHERE NOT (n.`budget_total` <= 10000000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Study sample_size gt 0 +MATCH (n:`Study`) WHERE NOT (n.`sample_size` > 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Study enrolled_count gte 0 +MATCH (n:`Study`) WHERE NOT (n.`enrolled_count` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: ClinicalTrial is_preregistered eq True +MATCH (n:`ClinicalTrial`) WHERE NOT (n.`is_preregistered` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Enrolment consent_obtained eq True +MATCH (n:`Enrolment`) WHERE NOT (n.`consent_obtained` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall s (HumanSubjectsStudy(s) and study_started = True implies exists a (approved_by_ethics(s, a))) +// forall e (Enrolment(e) implies exists c (has_consent(e, c))) +// forall g (Grant(g) and grant_active = True implies exists b (has_budget(g, b))) +// forall d (Dataset(d) and data_is_personal = True and data_is_public = True implies data_is_anonymised = True) +// forall d (Dataset(d) and data_is_public = True implies has_metadata = True) +// forall p (Publication(p) and is_peer_reviewed = True implies exists r (reviewed_by(p, r))) +// forall p (Publication(p) and is_peer_reviewed = True implies has_coi_declared = True) +// forall x (not Study(x) and Publication(x)) +// forall x (not Organization(x) and Person(x)) +// forall x (not RawDataset(x) and ProcessedDataset(x)) diff --git a/examples/domain_research_projects.d2 b/examples/domain_research_projects.d2 new file mode 100644 index 0000000..9274890 --- /dev/null +++ b/examples/domain_research_projects.d2 @@ -0,0 +1,205 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"InformationContentEntity": { shape: class } +"Person": { shape: class } +"Organization": { shape: class } +"University": { shape: class } +"ResearchInstitute": { shape: class } +"FundingAgency": { shape: class } +"PublicFunder": { shape: class } +"PrivateFoundation": { shape: class } +"Publisher": { shape: class } +"EthicsCommittee": { shape: class } +"Department": { shape: class } +"ResearchGroup": { shape: class } +"Investigator": { shape: class } +"PrincipalInvestigator": { shape: class } +"CoInvestigator": { shape: class } +"PostdoctoralResearcher": { shape: class } +"DoctoralStudent": { shape: class } +"ResearchParticipant": { shape: class } +"Reviewer": { shape: class } +"Author": { shape: class } +"FundingInstrument": { shape: class } +"Grant": { shape: class } +"ProjectGrant": { shape: class } +"FellowshipGrant": { shape: class } +"ProposalDocument": { shape: class } +"Budget": { shape: class } +"BudgetLine": { shape: class } +"DataManagementPlan": { shape: class } +"ProgressReport": { shape: class } +"FinalReport": { shape: class } +"ConflictOfInterestDeclaration": { shape: class } +"ResearchProject": { shape: class } +"Study": { shape: class } +"ObservationalStudy": { shape: class } +"ClinicalTrial": { shape: class } +"SurveyStudy": { shape: class } +"ComputationalStudy": { shape: class } +"HumanSubjectsStudy": { shape: class } +"Experiment": { shape: class } +"Enrolment": { shape: class } +"PeerReview": { shape: class } +"EthicsReview": { shape: class } +"EthicsApproval": { shape: class } +"InformedConsent": { shape: class } +"StudyProtocol": { shape: class } +"PreRegistration": { shape: class } +"AdverseEventReport": { shape: class } +"Dataset": { shape: class } +"RawDataset": { shape: class } +"ProcessedDataset": { shape: class } +"SensitiveDataset": { shape: class } +"OpenDataset": { shape: class } +"Metadata": { shape: class } +"Codebook": { shape: class } +"Software": { shape: class } +"Publication": { shape: class } +"JournalArticle": { shape: class } +"ConferencePaper": { shape: class } +"Preprint": { shape: class } +"Thesis": { shape: class } +"Citation": { shape: class } +"Journal": { shape: class } +"Repository": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Person" -> "Object" +"Organization" -> "Object" +"University" -> "Organization" +"ResearchInstitute" -> "Organization" +"FundingAgency" -> "Organization" +"PublicFunder" -> "FundingAgency" +"PrivateFoundation" -> "FundingAgency" +"Publisher" -> "Organization" +"EthicsCommittee" -> "Organization" +"Department" -> "Organization" +"ResearchGroup" -> "Organization" +"Investigator" -> "Role" +"PrincipalInvestigator" -> "Investigator" +"CoInvestigator" -> "Investigator" +"PostdoctoralResearcher" -> "Role" +"DoctoralStudent" -> "Role" +"ResearchParticipant" -> "Role" +"Reviewer" -> "Role" +"Author" -> "Role" +"FundingInstrument" -> "InformationContentEntity" +"Grant" -> "FundingInstrument" +"ProjectGrant" -> "Grant" +"FellowshipGrant" -> "Grant" +"ProposalDocument" -> "InformationContentEntity" +"Budget" -> "InformationContentEntity" +"BudgetLine" -> "Budget" +"DataManagementPlan" -> "InformationContentEntity" +"ProgressReport" -> "InformationContentEntity" +"FinalReport" -> "InformationContentEntity" +"ConflictOfInterestDeclaration" -> "InformationContentEntity" +"ResearchProject" -> "Process" +"Study" -> "Process" +"ObservationalStudy" -> "Study" +"ClinicalTrial" -> "Study" +"SurveyStudy" -> "Study" +"ComputationalStudy" -> "Study" +"HumanSubjectsStudy" -> "Study" +"Experiment" -> "Process" +"Enrolment" -> "Process" +"PeerReview" -> "Process" +"EthicsReview" -> "Process" +"EthicsApproval" -> "InformationContentEntity" +"InformedConsent" -> "InformationContentEntity" +"StudyProtocol" -> "InformationContentEntity" +"PreRegistration" -> "InformationContentEntity" +"AdverseEventReport" -> "InformationContentEntity" +"Dataset" -> "InformationContentEntity" +"RawDataset" -> "Dataset" +"ProcessedDataset" -> "Dataset" +"SensitiveDataset" -> "Dataset" +"OpenDataset" -> "Dataset" +"Metadata" -> "InformationContentEntity" +"Codebook" -> "Metadata" +"Software" -> "InformationContentEntity" +"Publication" -> "InformationContentEntity" +"JournalArticle" -> "Publication" +"ConferencePaper" -> "Publication" +"Preprint" -> "Publication" +"Thesis" -> "Publication" +"Citation" -> "InformationContentEntity" +"Journal" -> "Object" +"Repository" -> "Object" +"Grant"."grant_number": String +"Grant"."award_amount": Integer +"Budget"."budget_total": Integer +"Grant"."grant_active": Boolean +"ResearchProject"."duration_months": Integer +"Study"."sample_size": Integer +"Study"."enrolled_count": Integer +"Study"."study_started": Boolean +"Study"."is_preregistered": Boolean +"EthicsApproval"."approval_valid": Boolean +"Enrolment"."consent_obtained": Boolean +"Dataset"."data_is_personal": Boolean +"Dataset"."data_is_anonymised": Boolean +"Dataset"."data_is_public": Boolean +"Dataset"."has_metadata": Boolean +"Publication"."doi": String +"Publication"."is_peer_reviewed": Boolean +"Publication"."author_count": Integer +"Publication"."has_coi_declared": Boolean +"Person"."h_index": Integer +"Grant" -> "FundingAgency": awarded_by +"Grant" -> "Organization": held_by +"Grant" -> "PrincipalInvestigator": led_by +"ResearchProject" -> "Grant": funds +"Grant" -> "Budget": has_budget +"Budget" -> "BudgetLine": includes_line +"ProposalDocument" -> "ResearchProject": proposes +"Person" -> "Organization": employed_by +"Person" -> "ResearchGroup": member_of +"Investigator" -> "Study": conducts +"Study" -> "ResearchProject": part_of_project +"Study" -> "StudyProtocol": governed_by +"Study" -> "EthicsApproval": approved_by_ethics +"EthicsApproval" -> "EthicsCommittee": issued_by +"Enrolment" -> "ResearchParticipant": enrols +"Enrolment" -> "Study": enrolment_in +"Enrolment" -> "InformedConsent": has_consent +"Study" -> "Dataset": generates +"ProcessedDataset" -> "RawDataset": derived_from_dataset +"Dataset" -> "Metadata": described_by +"Dataset" -> "Repository": deposited_in +"ResearchProject" -> "DataManagementPlan": governed_by_plan +"Publication" -> "Study": reports_on +"Publication" -> "Dataset": uses_dataset +"Publication" -> "Author": authored_by +"Publication" -> "Journal": published_in +"Publication" -> "Publication": cites +"Publication" -> "Grant": acknowledges +"Publication" -> "Reviewer": reviewed_by +"ConflictOfInterestDeclaration" -> "Author": declares +# WARNING: The following axioms could not be mapped to field constraints: +# forall s (HumanSubjectsStudy(s) and study_started = True implies exists a (approved_by_ethics(s, a))) +# forall e (Enrolment(e) implies exists c (has_consent(e, c))) +# forall g (Grant(g) and grant_active = True implies exists b (has_budget(g, b))) +# forall d (Dataset(d) and data_is_personal = True and data_is_public = True implies data_is_anonymised = True) +# forall d (Dataset(d) and data_is_public = True implies has_metadata = True) +# forall p (Publication(p) and is_peer_reviewed = True implies exists r (reviewed_by(p, r))) +# forall p (Publication(p) and is_peer_reviewed = True implies has_coi_declared = True) +# forall x (not Study(x) and Publication(x)) +# forall x (not Organization(x) and Person(x)) +# forall x (not RawDataset(x) and ProcessedDataset(x)) diff --git a/examples/domain_research_projects.d2.svg b/examples/domain_research_projects.d2.svg new file mode 100644 index 0000000..77f9b85 --- /dev/null +++ b/examples/domain_research_projects.d2.svg @@ -0,0 +1,131 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectOccurrentProcessRoleFunctionInformationContentEntityPerson+h_indexIntegerOrganizationUniversityResearchInstituteFundingAgencyPublicFunderPrivateFoundationPublisherEthicsCommitteeDepartmentResearchGroupInvestigatorPrincipalInvestigatorCoInvestigatorPostdoctoralResearcherDoctoralStudentResearchParticipantReviewerAuthorFundingInstrumentGrant+grant_numberString+award_amountInteger+grant_activeBooleanProjectGrantFellowshipGrantProposalDocumentBudget+budget_totalIntegerBudgetLineDataManagementPlanProgressReportFinalReportConflictOfInterestDeclarationResearchProject+duration_monthsIntegerStudy+sample_sizeInteger+enrolled_countInteger+study_startedBoolean+is_preregisteredBooleanObservationalStudyClinicalTrialSurveyStudyComputationalStudyHumanSubjectsStudyExperimentEnrolment+consent_obtainedBooleanPeerReviewEthicsReviewEthicsApproval+approval_validBooleanInformedConsentStudyProtocolPreRegistrationAdverseEventReportDataset+data_is_personalBoolean+data_is_anonymisedBoolean+data_is_publicBoolean+has_metadataBooleanRawDatasetProcessedDatasetSensitiveDatasetOpenDatasetMetadataCodebookSoftwarePublication+doiString+is_peer_reviewedBoolean+author_countInteger+has_coi_declaredBooleanJournalArticleConferencePaperPreprintThesisCitationJournalRepository awarded_byheld_byled_byfundshas_budgetincludes_lineproposesemployed_bymember_ofconductspart_of_projectgoverned_byapproved_by_ethicsissued_byenrolsenrolment_inhas_consentgeneratesderived_from_datasetdescribed_bydeposited_ingoverned_by_planreports_onuses_datasetauthored_bypublished_incitesacknowledgesreviewed_bydeclares + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_research_projects.logic b/examples/domain_research_projects.logic new file mode 100644 index 0000000..39f0ff5 --- /dev/null +++ b/examples/domain_research_projects.logic @@ -0,0 +1,203 @@ +; Domain: Research projects (grants, investigators, studies, data, publications). +; Models funding, investigators, institutions, studies, datasets, publications +; and ethics approval, with a condensed BFO upper level. +; Axioms enforce: human-subject studies need ethics approval before enrolment, +; funded grants have a principal investigator, budgets stay within award limits, +; published data is documented, conflicts of interest are declared, and disjoint kinds. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept InformationContentEntity Continuant) + +; --- People and organisations --- +(def-concept Person Object) +(def-concept Organization Object) +(def-concept University Organization) +(def-concept ResearchInstitute Organization) +(def-concept FundingAgency Organization) +(def-concept PublicFunder FundingAgency) +(def-concept PrivateFoundation FundingAgency) +(def-concept Publisher Organization) +(def-concept EthicsCommittee Organization) +(def-concept Department Organization) +(def-concept ResearchGroup Organization) +(def-concept Investigator Role) +(def-concept PrincipalInvestigator Investigator) +(def-concept CoInvestigator Investigator) +(def-concept PostdoctoralResearcher Role) +(def-concept DoctoralStudent Role) +(def-concept ResearchParticipant Role) +(def-concept Reviewer Role) +(def-concept Author Role) + +; --- Funding --- +(def-concept FundingInstrument InformationContentEntity) +(def-concept Grant FundingInstrument) +(def-concept ProjectGrant Grant) +(def-concept FellowshipGrant Grant) +(def-concept ProposalDocument InformationContentEntity) +(def-concept Budget InformationContentEntity) +(def-concept BudgetLine Budget) +(def-concept DataManagementPlan InformationContentEntity) +(def-concept ProgressReport InformationContentEntity) +(def-concept FinalReport InformationContentEntity) +(def-concept ConflictOfInterestDeclaration InformationContentEntity) + +; --- Studies and ethics --- +(def-concept ResearchProject Process) +(def-concept Study Process) +(def-concept ObservationalStudy Study) +(def-concept ClinicalTrial Study) +(def-concept SurveyStudy Study) +(def-concept ComputationalStudy Study) +(def-concept HumanSubjectsStudy Study) +(def-concept Experiment Process) +(def-concept Enrolment Process) +(def-concept PeerReview Process) +(def-concept EthicsReview Process) +(def-concept EthicsApproval InformationContentEntity) +(def-concept InformedConsent InformationContentEntity) +(def-concept StudyProtocol InformationContentEntity) +(def-concept PreRegistration InformationContentEntity) +(def-concept AdverseEventReport InformationContentEntity) + +; --- Data and outputs --- +(def-concept Dataset InformationContentEntity) +(def-concept RawDataset Dataset) +(def-concept ProcessedDataset Dataset) +(def-concept SensitiveDataset Dataset) +(def-concept OpenDataset Dataset) +(def-concept Metadata InformationContentEntity) +(def-concept Codebook Metadata) +(def-concept Software InformationContentEntity) +(def-concept Publication InformationContentEntity) +(def-concept JournalArticle Publication) +(def-concept ConferencePaper Publication) +(def-concept Preprint Publication) +(def-concept Thesis Publication) +(def-concept Citation InformationContentEntity) +(def-concept Journal Object) +(def-concept Repository Object) + +; --- Properties --- +(def-property grant_number Grant String :cardinality 1..1) +(def-property award_amount Grant Integer) +(def-property budget_total Budget Integer) +(def-property grant_active Grant Boolean) +(def-property duration_months ResearchProject Integer) +(def-property sample_size Study Integer) +(def-property enrolled_count Study Integer) +(def-property study_started Study Boolean) +(def-property is_preregistered Study Boolean) +(def-property approval_valid EthicsApproval Boolean) +(def-property consent_obtained Enrolment Boolean) +(def-property data_is_personal Dataset Boolean) +(def-property data_is_anonymised Dataset Boolean) +(def-property data_is_public Dataset Boolean) +(def-property has_metadata Dataset Boolean) +(def-property doi Publication String) +(def-property is_peer_reviewed Publication Boolean) +(def-property author_count Publication Integer) +(def-property has_coi_declared Publication Boolean) +(def-property h_index Person Integer) + +; --- Relations --- +(def-relation awarded_by Grant FundingAgency) +(def-relation held_by Grant Organization) +(def-relation led_by Grant PrincipalInvestigator :cardinality 1..1) +(def-relation funds ResearchProject Grant :cardinality 0..*) +(def-relation has_budget Grant Budget) +(def-relation includes_line Budget BudgetLine :cardinality 0..*) +(def-relation proposes ProposalDocument ResearchProject) +(def-relation employed_by Person Organization) +(def-relation member_of Person ResearchGroup) +(def-relation conducts Investigator Study) +(def-relation part_of_project Study ResearchProject) +(def-relation governed_by Study StudyProtocol) +(def-relation approved_by_ethics Study EthicsApproval) +(def-relation issued_by EthicsApproval EthicsCommittee) +(def-relation enrols Enrolment ResearchParticipant) +(def-relation enrolment_in Enrolment Study) +(def-relation has_consent Enrolment InformedConsent) +(def-relation generates Study Dataset :cardinality 0..*) +(def-relation derived_from_dataset ProcessedDataset RawDataset) +(def-relation described_by Dataset Metadata) +(def-relation deposited_in Dataset Repository) +(def-relation governed_by_plan ResearchProject DataManagementPlan) +(def-relation reports_on Publication Study) +(def-relation uses_dataset Publication Dataset :cardinality 0..*) +(def-relation authored_by Publication Author :cardinality 1..*) +(def-relation published_in Publication Journal) +(def-relation cites Publication Publication :cardinality 0..*) +(def-relation acknowledges Publication Grant) +(def-relation reviewed_by Publication Reviewer) +(def-relation declares ConflictOfInterestDeclaration Author) + +; --- Axioms --- +; 1. Ethics: a human-subjects study that has started needs an ethics approval. +(forall (s) + (implies (and (HumanSubjectsStudy s) (eq study_started True)) + (exists (a) (approved_by_ethics s a)))) + +; 2. Consent: every enrolment must hold an informed consent record. +(forall (e) + (implies (Enrolment e) + (exists (c) (has_consent e c)))) + +; 3. Consent flag: enrolment requires consent to have been obtained. +(forall (e) + (implies (Enrolment e) + (eq consent_obtained True))) + +; 4. Governance: an active grant must have a budget (the PI link is 1..1 on led_by). +(forall (g) + (implies (and (Grant g) (eq grant_active True)) + (exists (b) (has_budget g b)))) + +; 5. Budget limit: a budget never exceeds a positive bound of 10 million. +(forall (b) + (implies (Budget b) + (and (gte budget_total 0) (lte budget_total 10000000)))) + +; 6. Study design: sample size is positive and enrolment never starts negative. +(forall (s) + (implies (Study s) + (and (gt sample_size 0) (gte enrolled_count 0)))) + +; 7. Privacy: personal data is public only after anonymisation. +(forall (d) + (implies (and (Dataset d) (eq data_is_personal True) (eq data_is_public True)) + (eq data_is_anonymised True))) + +; 8. FAIR data: a public dataset must have metadata. +(forall (d) + (implies (and (Dataset d) (eq data_is_public True)) + (eq has_metadata True))) + +; 9. Integrity: a peer-reviewed publication has at least one reviewer. +(forall (p) + (implies (and (Publication p) (eq is_peer_reviewed True)) + (exists (r) (reviewed_by p r)))) + +; 10. Transparency: a publication must declare conflicts of interest. +(forall (p) + (implies (and (Publication p) (eq is_peer_reviewed True)) + (eq has_coi_declared True))) + +; 11. Clinical trials must be pre-registered. +(forall (t) + (implies (ClinicalTrial t) + (eq is_preregistered True))) + +; 12. Disjointness: a study is not a publication; organisations are not people. +(forall (x) (not (and (Study x) (Publication x)))) +(forall (x) (not (and (Organization x) (Person x)))) +(forall (x) (not (and (RawDataset x) (ProcessedDataset x)))) diff --git a/examples/domain_research_projects.mmd b/examples/domain_research_projects.mmd new file mode 100644 index 0000000..ed7d6dc --- /dev/null +++ b/examples/domain_research_projects.mmd @@ -0,0 +1,206 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class InformationContentEntity["InformationContentEntity"] + class Person["Person"] + class Organization["Organization"] + class University["University"] + class ResearchInstitute["ResearchInstitute"] + class FundingAgency["FundingAgency"] + class PublicFunder["PublicFunder"] + class PrivateFoundation["PrivateFoundation"] + class Publisher["Publisher"] + class EthicsCommittee["EthicsCommittee"] + class Department["Department"] + class ResearchGroup["ResearchGroup"] + class Investigator["Investigator"] + class PrincipalInvestigator["PrincipalInvestigator"] + class CoInvestigator["CoInvestigator"] + class PostdoctoralResearcher["PostdoctoralResearcher"] + class DoctoralStudent["DoctoralStudent"] + class ResearchParticipant["ResearchParticipant"] + class Reviewer["Reviewer"] + class Author["Author"] + class FundingInstrument["FundingInstrument"] + class Grant["Grant"] + class ProjectGrant["ProjectGrant"] + class FellowshipGrant["FellowshipGrant"] + class ProposalDocument["ProposalDocument"] + class Budget["Budget"] + class BudgetLine["BudgetLine"] + class DataManagementPlan["DataManagementPlan"] + class ProgressReport["ProgressReport"] + class FinalReport["FinalReport"] + class ConflictOfInterestDeclaration["ConflictOfInterestDeclaration"] + class ResearchProject["ResearchProject"] + class Study["Study"] + class ObservationalStudy["ObservationalStudy"] + class ClinicalTrial["ClinicalTrial"] + class SurveyStudy["SurveyStudy"] + class ComputationalStudy["ComputationalStudy"] + class HumanSubjectsStudy["HumanSubjectsStudy"] + class Experiment["Experiment"] + class Enrolment["Enrolment"] + class PeerReview["PeerReview"] + class EthicsReview["EthicsReview"] + class EthicsApproval["EthicsApproval"] + class InformedConsent["InformedConsent"] + class StudyProtocol["StudyProtocol"] + class PreRegistration["PreRegistration"] + class AdverseEventReport["AdverseEventReport"] + class Dataset["Dataset"] + class RawDataset["RawDataset"] + class ProcessedDataset["ProcessedDataset"] + class SensitiveDataset["SensitiveDataset"] + class OpenDataset["OpenDataset"] + class Metadata["Metadata"] + class Codebook["Codebook"] + class Software["Software"] + class Publication["Publication"] + class JournalArticle["JournalArticle"] + class ConferencePaper["ConferencePaper"] + class Preprint["Preprint"] + class Thesis["Thesis"] + class Citation["Citation"] + class Journal["Journal"] + class Repository["Repository"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- InformationContentEntity + Object <|-- Person + Object <|-- Organization + Organization <|-- University + Organization <|-- ResearchInstitute + Organization <|-- FundingAgency + FundingAgency <|-- PublicFunder + FundingAgency <|-- PrivateFoundation + Organization <|-- Publisher + Organization <|-- EthicsCommittee + Organization <|-- Department + Organization <|-- ResearchGroup + Role <|-- Investigator + Investigator <|-- PrincipalInvestigator + Investigator <|-- CoInvestigator + Role <|-- PostdoctoralResearcher + Role <|-- DoctoralStudent + Role <|-- ResearchParticipant + Role <|-- Reviewer + Role <|-- Author + InformationContentEntity <|-- FundingInstrument + FundingInstrument <|-- Grant + Grant <|-- ProjectGrant + Grant <|-- FellowshipGrant + InformationContentEntity <|-- ProposalDocument + InformationContentEntity <|-- Budget + Budget <|-- BudgetLine + InformationContentEntity <|-- DataManagementPlan + InformationContentEntity <|-- ProgressReport + InformationContentEntity <|-- FinalReport + InformationContentEntity <|-- ConflictOfInterestDeclaration + Process <|-- ResearchProject + Process <|-- Study + Study <|-- ObservationalStudy + Study <|-- ClinicalTrial + Study <|-- SurveyStudy + Study <|-- ComputationalStudy + Study <|-- HumanSubjectsStudy + Process <|-- Experiment + Process <|-- Enrolment + Process <|-- PeerReview + Process <|-- EthicsReview + InformationContentEntity <|-- EthicsApproval + InformationContentEntity <|-- InformedConsent + InformationContentEntity <|-- StudyProtocol + InformationContentEntity <|-- PreRegistration + InformationContentEntity <|-- AdverseEventReport + InformationContentEntity <|-- Dataset + Dataset <|-- RawDataset + Dataset <|-- ProcessedDataset + Dataset <|-- SensitiveDataset + Dataset <|-- OpenDataset + InformationContentEntity <|-- Metadata + Metadata <|-- Codebook + InformationContentEntity <|-- Software + InformationContentEntity <|-- Publication + Publication <|-- JournalArticle + Publication <|-- ConferencePaper + Publication <|-- Preprint + Publication <|-- Thesis + InformationContentEntity <|-- Citation + Object <|-- Journal + Object <|-- Repository + Grant : +String grant_number + Grant : +Integer award_amount + Budget : +Integer budget_total + Grant : +Boolean grant_active + ResearchProject : +Integer duration_months + Study : +Integer sample_size + Study : +Integer enrolled_count + Study : +Boolean study_started + Study : +Boolean is_preregistered + EthicsApproval : +Boolean approval_valid + Enrolment : +Boolean consent_obtained + Dataset : +Boolean data_is_personal + Dataset : +Boolean data_is_anonymised + Dataset : +Boolean data_is_public + Dataset : +Boolean has_metadata + Publication : +String doi + Publication : +Boolean is_peer_reviewed + Publication : +Integer author_count + Publication : +Boolean has_coi_declared + Person : +Integer h_index + Grant --> FundingAgency : awarded_by + Grant --> Organization : held_by + Grant --> PrincipalInvestigator : led_by + ResearchProject --> Grant : funds + Grant --> Budget : has_budget + Budget --> BudgetLine : includes_line + ProposalDocument --> ResearchProject : proposes + Person --> Organization : employed_by + Person --> ResearchGroup : member_of + Investigator --> Study : conducts + Study --> ResearchProject : part_of_project + Study --> StudyProtocol : governed_by + Study --> EthicsApproval : approved_by_ethics + EthicsApproval --> EthicsCommittee : issued_by + Enrolment --> ResearchParticipant : enrols + Enrolment --> Study : enrolment_in + Enrolment --> InformedConsent : has_consent + Study --> Dataset : generates + ProcessedDataset --> RawDataset : derived_from_dataset + Dataset --> Metadata : described_by + Dataset --> Repository : deposited_in + ResearchProject --> DataManagementPlan : governed_by_plan + Publication --> Study : reports_on + Publication --> Dataset : uses_dataset + Publication --> Author : authored_by + Publication --> Journal : published_in + Publication --> Publication : cites + Publication --> Grant : acknowledges + Publication --> Reviewer : reviewed_by + ConflictOfInterestDeclaration --> Author : declares + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall s (HumanSubjectsStudy(s) and study_started = True implies exists a (approved_by_ethics(s, a))) +%% forall e (Enrolment(e) implies exists c (has_consent(e, c))) +%% forall g (Grant(g) and grant_active = True implies exists b (has_budget(g, b))) +%% forall d (Dataset(d) and data_is_personal = True and data_is_public = True implies data_is_anonymised = True) +%% forall d (Dataset(d) and data_is_public = True implies has_metadata = True) +%% forall p (Publication(p) and is_peer_reviewed = True implies exists r (reviewed_by(p, r))) +%% forall p (Publication(p) and is_peer_reviewed = True implies has_coi_declared = True) +%% forall x (not Study(x) and Publication(x)) +%% forall x (not Organization(x) and Person(x)) +%% forall x (not RawDataset(x) and ProcessedDataset(x)) diff --git a/examples/domain_science_lab.cypher b/examples/domain_science_lab.cypher new file mode 100644 index 0000000..37961a0 --- /dev/null +++ b/examples/domain_science_lab.cypher @@ -0,0 +1,311 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sample'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BiologicalSample'}) +MERGE (p:OntologyClass {name: 'Sample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BloodSample'}) +MERGE (p:OntologyClass {name: 'BiologicalSample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TissueSample'}) +MERGE (p:OntologyClass {name: 'BiologicalSample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CellCulture'}) +MERGE (p:OntologyClass {name: 'BiologicalSample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EnvironmentalSample'}) +MERGE (p:OntologyClass {name: 'Sample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WaterSample'}) +MERGE (p:OntologyClass {name: 'EnvironmentalSample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SoilSample'}) +MERGE (p:OntologyClass {name: 'EnvironmentalSample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChemicalSample'}) +MERGE (p:OntologyClass {name: 'Sample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Aliquot'}) +MERGE (p:OntologyClass {name: 'Sample'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReferenceMaterial'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CertifiedReferenceMaterial'}) +MERGE (p:OntologyClass {name: 'ReferenceMaterial'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Reagent'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Solvent'}) +MERGE (p:OntologyClass {name: 'Reagent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Buffer'}) +MERGE (p:OntologyClass {name: 'Reagent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Container'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SampleVial'}) +MERGE (p:OntologyClass {name: 'Container'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StorageUnit'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Freezer'}) +MERGE (p:OntologyClass {name: 'StorageUnit'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ColdRoom'}) +MERGE (p:OntologyClass {name: 'StorageUnit'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Incubator'}) +MERGE (p:OntologyClass {name: 'StorageUnit'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Instrument'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Spectrometer'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MassSpectrometer'}) +MERGE (p:OntologyClass {name: 'Spectrometer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Chromatograph'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Microscope'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Centrifuge'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AnalyticalBalance'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PCRThermocycler'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Sensor'}) +MERGE (p:OntologyClass {name: 'Instrument'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TemperatureProbe'}) +MERGE (p:OntologyClass {name: 'Sensor'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Laboratory'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CleanRoom'}) +MERGE (p:OntologyClass {name: 'Laboratory'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BiosafetyLab'}) +MERGE (p:OntologyClass {name: 'Laboratory'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LabTechnician'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PrincipalScientist'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'QualityManager'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustodyHolder'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Analyst'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Protocol'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StandardOperatingProcedure'}) +MERGE (p:OntologyClass {name: 'Protocol'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AnalyticalMethod'}) +MERGE (p:OntologyClass {name: 'Protocol'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CalibrationCertificate'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Measurement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RawMeasurement'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DerivedMeasurement'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DatasetRecord'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LabNotebookEntry'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustodyRecord'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyDataSheet'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Deviation'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LabProcess'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Experiment'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlExperiment'}) +MERGE (p:OntologyClass {name: 'Experiment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Replicate'}) +MERGE (p:OntologyClass {name: 'Experiment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SamplePreparation'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Extraction'}) +MERGE (p:OntologyClass {name: 'SamplePreparation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Dilution'}) +MERGE (p:OntologyClass {name: 'SamplePreparation'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Calibration'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MeasurementProcess'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CustodyTransfer'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Disposal'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'QualityAudit'}) +MERGE (p:OntologyClass {name: 'LabProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Aliquot'}) +MERGE (t:OntologyClass {name: 'Sample'}) +MERGE (s)-[:RELATION {name: 'derived_from'}]->(t); +MERGE (s:OntologyClass {name: 'Sample'}) +MERGE (t:OntologyClass {name: 'StorageUnit'}) +MERGE (s)-[:RELATION {name: 'stored_in'}]->(t); +MERGE (s:OntologyClass {name: 'Sample'}) +MERGE (t:OntologyClass {name: 'Container'}) +MERGE (s)-[:RELATION {name: 'held_in'}]->(t); +MERGE (s:OntologyClass {name: 'Measurement'}) +MERGE (t:OntologyClass {name: 'Instrument'}) +MERGE (s)-[:RELATION {name: 'measured_by'}]->(t); +MERGE (s:OntologyClass {name: 'Measurement'}) +MERGE (t:OntologyClass {name: 'Sample'}) +MERGE (s)-[:RELATION {name: 'measures'}]->(t); +MERGE (s:OntologyClass {name: 'MeasurementProcess'}) +MERGE (t:OntologyClass {name: 'Laboratory'}) +MERGE (s)-[:RELATION {name: 'performed_in'}]->(t); +MERGE (s:OntologyClass {name: 'Experiment'}) +MERGE (t:OntologyClass {name: 'Protocol'}) +MERGE (s)-[:RELATION {name: 'follows_protocol'}]->(t); +MERGE (s:OntologyClass {name: 'Experiment'}) +MERGE (t:OntologyClass {name: 'Sample'}) +MERGE (s)-[:RELATION {name: 'uses_sample'}]->(t); +MERGE (s:OntologyClass {name: 'Experiment'}) +MERGE (t:OntologyClass {name: 'Instrument'}) +MERGE (s)-[:RELATION {name: 'uses_instrument'}]->(t); +MERGE (s:OntologyClass {name: 'Experiment'}) +MERGE (t:OntologyClass {name: 'Measurement'}) +MERGE (s)-[:RELATION {name: 'produces_measurement'}]->(t); +MERGE (s:OntologyClass {name: 'Instrument'}) +MERGE (t:OntologyClass {name: 'CalibrationCertificate'}) +MERGE (s)-[:RELATION {name: 'calibrated_by'}]->(t); +MERGE (s:OntologyClass {name: 'Calibration'}) +MERGE (t:OntologyClass {name: 'Instrument'}) +MERGE (s)-[:RELATION {name: 'calibration_of'}]->(t); +MERGE (s:OntologyClass {name: 'Calibration'}) +MERGE (t:OntologyClass {name: 'ReferenceMaterial'}) +MERGE (s)-[:RELATION {name: 'uses_reference'}]->(t); +MERGE (s:OntologyClass {name: 'CustodyRecord'}) +MERGE (t:OntologyClass {name: 'Sample'}) +MERGE (s)-[:RELATION {name: 'custody_of'}]->(t); +MERGE (s:OntologyClass {name: 'CustodyTransfer'}) +MERGE (t:OntologyClass {name: 'Person'}) +MERGE (s)-[:RELATION {name: 'released_by'}]->(t); +MERGE (s:OntologyClass {name: 'CustodyTransfer'}) +MERGE (t:OntologyClass {name: 'Person'}) +MERGE (s)-[:RELATION {name: 'received_by'}]->(t); +MERGE (s:OntologyClass {name: 'CustodyTransfer'}) +MERGE (t:OntologyClass {name: 'Sample'}) +MERGE (s)-[:RELATION {name: 'transfers'}]->(t); +MERGE (s:OntologyClass {name: 'CustodyTransfer'}) +MERGE (t:OntologyClass {name: 'CustodyRecord'}) +MERGE (s)-[:RELATION {name: 'recorded_in'}]->(t); +MERGE (s:OntologyClass {name: 'LabProcess'}) +MERGE (t:OntologyClass {name: 'Person'}) +MERGE (s)-[:RELATION {name: 'performed_by'}]->(t); +MERGE (s:OntologyClass {name: 'Experiment'}) +MERGE (t:OntologyClass {name: 'LabNotebookEntry'}) +MERGE (s)-[:RELATION {name: 'documented_in'}]->(t); +MERGE (s:OntologyClass {name: 'Deviation'}) +MERGE (t:OntologyClass {name: 'Protocol'}) +MERGE (s)-[:RELATION {name: 'deviates_from'}]->(t); +MERGE (s:OntologyClass {name: 'Sample'}) +MERGE (t:OntologyClass {name: 'SafetyDataSheet'}) +MERGE (s)-[:RELATION {name: 'handled_under'}]->(t); +// Axiom Validations +// Axiom validation: BiologicalSample storage_temp_c gte -196 +MATCH (n:`BiologicalSample`) WHERE NOT (n.`storage_temp_c` >= -196) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: BiologicalSample storage_temp_c lte 40 +MATCH (n:`BiologicalSample`) WHERE NOT (n.`storage_temp_c` <= 40) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Measurement uncertainty_percent gte 0 +MATCH (n:`Measurement`) WHERE NOT (n.`uncertainty_percent` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Measurement uncertainty_percent lte 100 +MATCH (n:`Measurement`) WHERE NOT (n.`uncertainty_percent` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: CustodyRecord custody_gap eq False +MATCH (n:`CustodyRecord`) WHERE NOT (n.`custody_gap` = false) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall m (forall i (Measurement(m) and measured_by(m, i) implies calibration_valid = True)) +// forall i (Instrument(i) and gt(days_since_calibration, 365) implies calibration_valid = False) +// forall e (forall p (Experiment(e) and follows_protocol(e, p) implies protocol_approved = True)) +// forall t (CustodyTransfer(t) implies exists r (recorded_in(t, r))) +// forall s (Sample(s) and is_biohazard = True implies exists d (handled_under(s, d))) +// forall e (Experiment(e) and experiment_complete = True implies gte(replicate_count, 3)) +// forall e (forall s (Experiment(e) and uses_sample(e, s) implies is_expired = False)) +// forall s (Sample(s) and is_disposed = True implies volume_ml = 0) +// forall x (not Sample(x) and Instrument(x)) +// forall x (not Measurement(x) and Protocol(x)) diff --git a/examples/domain_science_lab.d2 b/examples/domain_science_lab.d2 new file mode 100644 index 0000000..4fa2b0e --- /dev/null +++ b/examples/domain_science_lab.d2 @@ -0,0 +1,199 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"InformationContentEntity": { shape: class } +"Sample": { shape: class } +"BiologicalSample": { shape: class } +"BloodSample": { shape: class } +"TissueSample": { shape: class } +"CellCulture": { shape: class } +"EnvironmentalSample": { shape: class } +"WaterSample": { shape: class } +"SoilSample": { shape: class } +"ChemicalSample": { shape: class } +"Aliquot": { shape: class } +"ReferenceMaterial": { shape: class } +"CertifiedReferenceMaterial": { shape: class } +"Reagent": { shape: class } +"Solvent": { shape: class } +"Buffer": { shape: class } +"Container": { shape: class } +"SampleVial": { shape: class } +"StorageUnit": { shape: class } +"Freezer": { shape: class } +"ColdRoom": { shape: class } +"Incubator": { shape: class } +"Instrument": { shape: class } +"Spectrometer": { shape: class } +"MassSpectrometer": { shape: class } +"Chromatograph": { shape: class } +"Microscope": { shape: class } +"Centrifuge": { shape: class } +"AnalyticalBalance": { shape: class } +"PCRThermocycler": { shape: class } +"Sensor": { shape: class } +"TemperatureProbe": { shape: class } +"Laboratory": { shape: class } +"CleanRoom": { shape: class } +"BiosafetyLab": { shape: class } +"Person": { shape: class } +"LabTechnician": { shape: class } +"PrincipalScientist": { shape: class } +"QualityManager": { shape: class } +"CustodyHolder": { shape: class } +"Analyst": { shape: class } +"Protocol": { shape: class } +"StandardOperatingProcedure": { shape: class } +"AnalyticalMethod": { shape: class } +"CalibrationCertificate": { shape: class } +"Measurement": { shape: class } +"RawMeasurement": { shape: class } +"DerivedMeasurement": { shape: class } +"DatasetRecord": { shape: class } +"LabNotebookEntry": { shape: class } +"CustodyRecord": { shape: class } +"SafetyDataSheet": { shape: class } +"Deviation": { shape: class } +"LabProcess": { shape: class } +"Experiment": { shape: class } +"ControlExperiment": { shape: class } +"Replicate": { shape: class } +"SamplePreparation": { shape: class } +"Extraction": { shape: class } +"Dilution": { shape: class } +"Calibration": { shape: class } +"MeasurementProcess": { shape: class } +"CustodyTransfer": { shape: class } +"Disposal": { shape: class } +"QualityAudit": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Sample" -> "MaterialEntity" +"BiologicalSample" -> "Sample" +"BloodSample" -> "BiologicalSample" +"TissueSample" -> "BiologicalSample" +"CellCulture" -> "BiologicalSample" +"EnvironmentalSample" -> "Sample" +"WaterSample" -> "EnvironmentalSample" +"SoilSample" -> "EnvironmentalSample" +"ChemicalSample" -> "Sample" +"Aliquot" -> "Sample" +"ReferenceMaterial" -> "MaterialEntity" +"CertifiedReferenceMaterial" -> "ReferenceMaterial" +"Reagent" -> "MaterialEntity" +"Solvent" -> "Reagent" +"Buffer" -> "Reagent" +"Container" -> "Object" +"SampleVial" -> "Container" +"StorageUnit" -> "Object" +"Freezer" -> "StorageUnit" +"ColdRoom" -> "StorageUnit" +"Incubator" -> "StorageUnit" +"Instrument" -> "Object" +"Spectrometer" -> "Instrument" +"MassSpectrometer" -> "Spectrometer" +"Chromatograph" -> "Instrument" +"Microscope" -> "Instrument" +"Centrifuge" -> "Instrument" +"AnalyticalBalance" -> "Instrument" +"PCRThermocycler" -> "Instrument" +"Sensor" -> "Instrument" +"TemperatureProbe" -> "Sensor" +"Laboratory" -> "Object" +"CleanRoom" -> "Laboratory" +"BiosafetyLab" -> "Laboratory" +"Person" -> "Object" +"LabTechnician" -> "Role" +"PrincipalScientist" -> "Role" +"QualityManager" -> "Role" +"CustodyHolder" -> "Role" +"Analyst" -> "Role" +"Protocol" -> "InformationContentEntity" +"StandardOperatingProcedure" -> "Protocol" +"AnalyticalMethod" -> "Protocol" +"CalibrationCertificate" -> "InformationContentEntity" +"Measurement" -> "InformationContentEntity" +"RawMeasurement" -> "Measurement" +"DerivedMeasurement" -> "Measurement" +"DatasetRecord" -> "InformationContentEntity" +"LabNotebookEntry" -> "InformationContentEntity" +"CustodyRecord" -> "InformationContentEntity" +"SafetyDataSheet" -> "InformationContentEntity" +"Deviation" -> "InformationContentEntity" +"LabProcess" -> "Process" +"Experiment" -> "LabProcess" +"ControlExperiment" -> "Experiment" +"Replicate" -> "Experiment" +"SamplePreparation" -> "LabProcess" +"Extraction" -> "SamplePreparation" +"Dilution" -> "SamplePreparation" +"Calibration" -> "LabProcess" +"MeasurementProcess" -> "LabProcess" +"CustodyTransfer" -> "LabProcess" +"Disposal" -> "LabProcess" +"QualityAudit" -> "LabProcess" +"Sample"."sample_id": String +"Sample"."volume_ml": Integer +"Sample"."is_biohazard": Boolean +"Sample"."storage_temp_c": Integer +"Sample"."is_expired": Boolean +"Sample"."collection_date": String +"Instrument"."instrument_serial": String +"Instrument"."calibration_valid": Boolean +"Instrument"."days_since_calibration": Integer +"Measurement"."measured_value": Integer +"Measurement"."uncertainty_percent": Integer +"Protocol"."protocol_approved": Boolean +"Protocol"."protocol_version": Integer +"Experiment"."replicate_count": Integer +"Experiment"."experiment_complete": Boolean +"CustodyRecord"."custody_gap": Boolean +"BiosafetyLab"."containment_level": Integer +"Sample"."is_disposed": Boolean +"Aliquot" -> "Sample": derived_from +"Sample" -> "StorageUnit": stored_in +"Sample" -> "Container": held_in +"Measurement" -> "Instrument": measured_by +"Measurement" -> "Sample": measures +"MeasurementProcess" -> "Laboratory": performed_in +"Experiment" -> "Protocol": follows_protocol +"Experiment" -> "Sample": uses_sample +"Experiment" -> "Instrument": uses_instrument +"Experiment" -> "Measurement": produces_measurement +"Instrument" -> "CalibrationCertificate": calibrated_by +"Calibration" -> "Instrument": calibration_of +"Calibration" -> "ReferenceMaterial": uses_reference +"CustodyRecord" -> "Sample": custody_of +"CustodyTransfer" -> "Person": released_by +"CustodyTransfer" -> "Person": received_by +"CustodyTransfer" -> "Sample": transfers +"CustodyTransfer" -> "CustodyRecord": recorded_in +"LabProcess" -> "Person": performed_by +"Experiment" -> "LabNotebookEntry": documented_in +"Deviation" -> "Protocol": deviates_from +"Sample" -> "SafetyDataSheet": handled_under +# WARNING: The following axioms could not be mapped to field constraints: +# forall m (forall i (Measurement(m) and measured_by(m, i) implies calibration_valid = True)) +# forall i (Instrument(i) and gt(days_since_calibration, 365) implies calibration_valid = False) +# forall e (forall p (Experiment(e) and follows_protocol(e, p) implies protocol_approved = True)) +# forall t (CustodyTransfer(t) implies exists r (recorded_in(t, r))) +# forall s (Sample(s) and is_biohazard = True implies exists d (handled_under(s, d))) +# forall e (Experiment(e) and experiment_complete = True implies gte(replicate_count, 3)) +# forall e (forall s (Experiment(e) and uses_sample(e, s) implies is_expired = False)) +# forall s (Sample(s) and is_disposed = True implies volume_ml = 0) +# forall x (not Sample(x) and Instrument(x)) +# forall x (not Measurement(x) and Protocol(x)) diff --git a/examples/domain_science_lab.d2.svg b/examples/domain_science_lab.d2.svg new file mode 100644 index 0000000..2f3c466 --- /dev/null +++ b/examples/domain_science_lab.d2.svg @@ -0,0 +1,123 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectOccurrentProcessRoleFunctionInformationContentEntitySample+sample_idString+volume_mlInteger+is_biohazardBoolean+storage_temp_cInteger+is_expiredBoolean+collection_dateString+is_disposedBooleanBiologicalSampleBloodSampleTissueSampleCellCultureEnvironmentalSampleWaterSampleSoilSampleChemicalSampleAliquotReferenceMaterialCertifiedReferenceMaterialReagentSolventBufferContainerSampleVialStorageUnitFreezerColdRoomIncubatorInstrument+instrument_serialString+calibration_validBoolean+days_since_calibrationIntegerSpectrometerMassSpectrometerChromatographMicroscopeCentrifugeAnalyticalBalancePCRThermocyclerSensorTemperatureProbeLaboratoryCleanRoomBiosafetyLab+containment_levelIntegerPersonLabTechnicianPrincipalScientistQualityManagerCustodyHolderAnalystProtocol+protocol_approvedBoolean+protocol_versionIntegerStandardOperatingProcedureAnalyticalMethodCalibrationCertificateMeasurement+measured_valueInteger+uncertainty_percentIntegerRawMeasurementDerivedMeasurementDatasetRecordLabNotebookEntryCustodyRecord+custody_gapBooleanSafetyDataSheetDeviationLabProcessExperiment+replicate_countInteger+experiment_completeBooleanControlExperimentReplicateSamplePreparationExtractionDilutionCalibrationMeasurementProcessCustodyTransferDisposalQualityAudit derived_fromstored_inheld_inmeasured_bymeasuresperformed_infollows_protocoluses_sampleuses_instrumentproduces_measurementcalibrated_bycalibration_ofuses_referencecustody_ofreleased_byreceived_bytransfersrecorded_inperformed_bydocumented_indeviates_fromhandled_under + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_science_lab.logic b/examples/domain_science_lab.logic new file mode 100644 index 0000000..8b91c9e --- /dev/null +++ b/examples/domain_science_lab.logic @@ -0,0 +1,196 @@ +; Domain: Laboratory science (samples, instruments, experiments, custody). +; Models samples, specimens, instruments, calibration, protocols, experiments, +; measurements and chain of custody, with a condensed BFO upper level. +; Axioms enforce: measurements use calibrated instruments, samples have an +; unbroken custody chain, protocols are approved before use, biohazard samples +; need containment, storage temperatures stay in range, and disjoint kinds. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Samples and materials --- +(def-concept Sample MaterialEntity) +(def-concept BiologicalSample Sample) +(def-concept BloodSample BiologicalSample) +(def-concept TissueSample BiologicalSample) +(def-concept CellCulture BiologicalSample) +(def-concept EnvironmentalSample Sample) +(def-concept WaterSample EnvironmentalSample) +(def-concept SoilSample EnvironmentalSample) +(def-concept ChemicalSample Sample) +(def-concept Aliquot Sample) +(def-concept ReferenceMaterial MaterialEntity) +(def-concept CertifiedReferenceMaterial ReferenceMaterial) +(def-concept Reagent MaterialEntity) +(def-concept Solvent Reagent) +(def-concept Buffer Reagent) +(def-concept Container Object) +(def-concept SampleVial Container) +(def-concept StorageUnit Object) +(def-concept Freezer StorageUnit) +(def-concept ColdRoom StorageUnit) +(def-concept Incubator StorageUnit) + +; --- Instruments --- +(def-concept Instrument Object) +(def-concept Spectrometer Instrument) +(def-concept MassSpectrometer Spectrometer) +(def-concept Chromatograph Instrument) +(def-concept Microscope Instrument) +(def-concept Centrifuge Instrument) +(def-concept AnalyticalBalance Instrument) +(def-concept PCRThermocycler Instrument) +(def-concept Sensor Instrument) +(def-concept TemperatureProbe Sensor) +(def-concept Laboratory Object) +(def-concept CleanRoom Laboratory) +(def-concept BiosafetyLab Laboratory) + +; --- People and roles --- +(def-concept Person Object) +(def-concept LabTechnician Role) +(def-concept PrincipalScientist Role) +(def-concept QualityManager Role) +(def-concept CustodyHolder Role) +(def-concept Analyst Role) + +; --- Information --- +(def-concept Protocol InformationContentEntity) +(def-concept StandardOperatingProcedure Protocol) +(def-concept AnalyticalMethod Protocol) +(def-concept CalibrationCertificate InformationContentEntity) +(def-concept Measurement InformationContentEntity) +(def-concept RawMeasurement Measurement) +(def-concept DerivedMeasurement Measurement) +(def-concept DatasetRecord InformationContentEntity) +(def-concept LabNotebookEntry InformationContentEntity) +(def-concept CustodyRecord InformationContentEntity) +(def-concept SafetyDataSheet InformationContentEntity) +(def-concept Deviation InformationContentEntity) + +; --- Processes --- +(def-concept LabProcess Process) +(def-concept Experiment LabProcess) +(def-concept ControlExperiment Experiment) +(def-concept Replicate Experiment) +(def-concept SamplePreparation LabProcess) +(def-concept Extraction SamplePreparation) +(def-concept Dilution SamplePreparation) +(def-concept Calibration LabProcess) +(def-concept MeasurementProcess LabProcess) +(def-concept CustodyTransfer LabProcess) +(def-concept Disposal LabProcess) +(def-concept QualityAudit LabProcess) + +; --- Properties --- +(def-property sample_id Sample String :cardinality 1..1) +(def-property volume_ml Sample Integer) +(def-property is_biohazard Sample Boolean) +(def-property storage_temp_c Sample Integer) +(def-property is_expired Sample Boolean) +(def-property collection_date Sample String) +(def-property instrument_serial Instrument String :cardinality 1..1) +(def-property calibration_valid Instrument Boolean) +(def-property days_since_calibration Instrument Integer) +(def-property measured_value Measurement Integer) +(def-property uncertainty_percent Measurement Integer) +(def-property protocol_approved Protocol Boolean) +(def-property protocol_version Protocol Integer) +(def-property replicate_count Experiment Integer) +(def-property experiment_complete Experiment Boolean) +(def-property custody_gap CustodyRecord Boolean) +(def-property containment_level BiosafetyLab Integer) +(def-property is_disposed Sample Boolean) + +; --- Relations --- +(def-relation derived_from Aliquot Sample) +(def-relation stored_in Sample StorageUnit) +(def-relation held_in Sample Container) +(def-relation measured_by Measurement Instrument) +(def-relation measures Measurement Sample) +(def-relation performed_in MeasurementProcess Laboratory) +(def-relation follows_protocol Experiment Protocol) +(def-relation uses_sample Experiment Sample :cardinality 1..*) +(def-relation uses_instrument Experiment Instrument :cardinality 0..*) +(def-relation produces_measurement Experiment Measurement :cardinality 0..*) +(def-relation calibrated_by Instrument CalibrationCertificate) +(def-relation calibration_of Calibration Instrument) +(def-relation uses_reference Calibration ReferenceMaterial) +(def-relation custody_of CustodyRecord Sample) +(def-relation released_by CustodyTransfer Person) +(def-relation received_by CustodyTransfer Person) +(def-relation transfers CustodyTransfer Sample) +(def-relation recorded_in CustodyTransfer CustodyRecord) +(def-relation performed_by LabProcess Person) +(def-relation documented_in Experiment LabNotebookEntry) +(def-relation deviates_from Deviation Protocol) +(def-relation handled_under Sample SafetyDataSheet) + +; --- Axioms --- +; 1. Metrology: a sample may only be measured by an instrument with valid calibration. +(forall (m i) + (implies (and (Measurement m) (measured_by m i)) + (eq calibration_valid True))) + +; 2. Calibration interval: an instrument beyond 365 days is not validly calibrated. +(forall (i) + (implies (and (Instrument i) (gt days_since_calibration 365)) + (eq calibration_valid False))) + +; 3. Protocol control: an experiment may only follow an approved protocol. +(forall (e p) + (implies (and (Experiment e) (follows_protocol e p)) + (eq protocol_approved True))) + +; 4. Chain of custody: every transfer is recorded in a custody record. +(forall (t) + (implies (CustodyTransfer t) + (exists (r) (recorded_in t r)))) + +; 5. Custody integrity: a custody record never has a gap. +(forall (r) + (implies (CustodyRecord r) + (eq custody_gap False))) + +; 6. Biosafety: biohazard samples are only handled with a safety data sheet. +(forall (s) + (implies (and (Sample s) (eq is_biohazard True)) + (exists (d) (handled_under s d)))) + +; 7. Cold storage: stored biological samples stay between minus 196 and 40 Celsius. +(forall (s) + (implies (BiologicalSample s) + (and (gte storage_temp_c -196) (lte storage_temp_c 40)))) + +; 8. Reproducibility: a completed experiment has at least three replicates. +(forall (e) + (implies (and (Experiment e) (eq experiment_complete True)) + (gte replicate_count 3))) + +; 9. Data quality: measurement uncertainty is a percentage from 0 to 100. +(forall (m) + (implies (Measurement m) + (and (gte uncertainty_percent 0) (lte uncertainty_percent 100)))) + +; 10. Expiry: an expired sample must not be used in an experiment. +(forall (e s) + (implies (and (Experiment e) (uses_sample e s)) + (eq is_expired False))) + +; 11. Disposal: a disposed sample has zero remaining volume. +(forall (s) + (implies (and (Sample s) (eq is_disposed True)) + (eq volume_ml 0))) + +; 12. Disjointness: samples and instruments, measurements and protocols differ. +(forall (x) (not (and (Sample x) (Instrument x)))) +(forall (x) (not (and (Measurement x) (Protocol x)))) diff --git a/examples/domain_science_lab.mmd b/examples/domain_science_lab.mmd new file mode 100644 index 0000000..ebd7fe7 --- /dev/null +++ b/examples/domain_science_lab.mmd @@ -0,0 +1,200 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class InformationContentEntity["InformationContentEntity"] + class Sample["Sample"] + class BiologicalSample["BiologicalSample"] + class BloodSample["BloodSample"] + class TissueSample["TissueSample"] + class CellCulture["CellCulture"] + class EnvironmentalSample["EnvironmentalSample"] + class WaterSample["WaterSample"] + class SoilSample["SoilSample"] + class ChemicalSample["ChemicalSample"] + class Aliquot["Aliquot"] + class ReferenceMaterial["ReferenceMaterial"] + class CertifiedReferenceMaterial["CertifiedReferenceMaterial"] + class Reagent["Reagent"] + class Solvent["Solvent"] + class Buffer["Buffer"] + class Container["Container"] + class SampleVial["SampleVial"] + class StorageUnit["StorageUnit"] + class Freezer["Freezer"] + class ColdRoom["ColdRoom"] + class Incubator["Incubator"] + class Instrument["Instrument"] + class Spectrometer["Spectrometer"] + class MassSpectrometer["MassSpectrometer"] + class Chromatograph["Chromatograph"] + class Microscope["Microscope"] + class Centrifuge["Centrifuge"] + class AnalyticalBalance["AnalyticalBalance"] + class PCRThermocycler["PCRThermocycler"] + class Sensor["Sensor"] + class TemperatureProbe["TemperatureProbe"] + class Laboratory["Laboratory"] + class CleanRoom["CleanRoom"] + class BiosafetyLab["BiosafetyLab"] + class Person["Person"] + class LabTechnician["LabTechnician"] + class PrincipalScientist["PrincipalScientist"] + class QualityManager["QualityManager"] + class CustodyHolder["CustodyHolder"] + class Analyst["Analyst"] + class Protocol["Protocol"] + class StandardOperatingProcedure["StandardOperatingProcedure"] + class AnalyticalMethod["AnalyticalMethod"] + class CalibrationCertificate["CalibrationCertificate"] + class Measurement["Measurement"] + class RawMeasurement["RawMeasurement"] + class DerivedMeasurement["DerivedMeasurement"] + class DatasetRecord["DatasetRecord"] + class LabNotebookEntry["LabNotebookEntry"] + class CustodyRecord["CustodyRecord"] + class SafetyDataSheet["SafetyDataSheet"] + class Deviation["Deviation"] + class LabProcess["LabProcess"] + class Experiment["Experiment"] + class ControlExperiment["ControlExperiment"] + class Replicate["Replicate"] + class SamplePreparation["SamplePreparation"] + class Extraction["Extraction"] + class Dilution["Dilution"] + class Calibration["Calibration"] + class MeasurementProcess["MeasurementProcess"] + class CustodyTransfer["CustodyTransfer"] + class Disposal["Disposal"] + class QualityAudit["QualityAudit"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- InformationContentEntity + MaterialEntity <|-- Sample + Sample <|-- BiologicalSample + BiologicalSample <|-- BloodSample + BiologicalSample <|-- TissueSample + BiologicalSample <|-- CellCulture + Sample <|-- EnvironmentalSample + EnvironmentalSample <|-- WaterSample + EnvironmentalSample <|-- SoilSample + Sample <|-- ChemicalSample + Sample <|-- Aliquot + MaterialEntity <|-- ReferenceMaterial + ReferenceMaterial <|-- CertifiedReferenceMaterial + MaterialEntity <|-- Reagent + Reagent <|-- Solvent + Reagent <|-- Buffer + Object <|-- Container + Container <|-- SampleVial + Object <|-- StorageUnit + StorageUnit <|-- Freezer + StorageUnit <|-- ColdRoom + StorageUnit <|-- Incubator + Object <|-- Instrument + Instrument <|-- Spectrometer + Spectrometer <|-- MassSpectrometer + Instrument <|-- Chromatograph + Instrument <|-- Microscope + Instrument <|-- Centrifuge + Instrument <|-- AnalyticalBalance + Instrument <|-- PCRThermocycler + Instrument <|-- Sensor + Sensor <|-- TemperatureProbe + Object <|-- Laboratory + Laboratory <|-- CleanRoom + Laboratory <|-- BiosafetyLab + Object <|-- Person + Role <|-- LabTechnician + Role <|-- PrincipalScientist + Role <|-- QualityManager + Role <|-- CustodyHolder + Role <|-- Analyst + InformationContentEntity <|-- Protocol + Protocol <|-- StandardOperatingProcedure + Protocol <|-- AnalyticalMethod + InformationContentEntity <|-- CalibrationCertificate + InformationContentEntity <|-- Measurement + Measurement <|-- RawMeasurement + Measurement <|-- DerivedMeasurement + InformationContentEntity <|-- DatasetRecord + InformationContentEntity <|-- LabNotebookEntry + InformationContentEntity <|-- CustodyRecord + InformationContentEntity <|-- SafetyDataSheet + InformationContentEntity <|-- Deviation + Process <|-- LabProcess + LabProcess <|-- Experiment + Experiment <|-- ControlExperiment + Experiment <|-- Replicate + LabProcess <|-- SamplePreparation + SamplePreparation <|-- Extraction + SamplePreparation <|-- Dilution + LabProcess <|-- Calibration + LabProcess <|-- MeasurementProcess + LabProcess <|-- CustodyTransfer + LabProcess <|-- Disposal + LabProcess <|-- QualityAudit + Sample : +String sample_id + Sample : +Integer volume_ml + Sample : +Boolean is_biohazard + Sample : +Integer storage_temp_c + Sample : +Boolean is_expired + Sample : +String collection_date + Instrument : +String instrument_serial + Instrument : +Boolean calibration_valid + Instrument : +Integer days_since_calibration + Measurement : +Integer measured_value + Measurement : +Integer uncertainty_percent + Protocol : +Boolean protocol_approved + Protocol : +Integer protocol_version + Experiment : +Integer replicate_count + Experiment : +Boolean experiment_complete + CustodyRecord : +Boolean custody_gap + BiosafetyLab : +Integer containment_level + Sample : +Boolean is_disposed + Aliquot --> Sample : derived_from + Sample --> StorageUnit : stored_in + Sample --> Container : held_in + Measurement --> Instrument : measured_by + Measurement --> Sample : measures + MeasurementProcess --> Laboratory : performed_in + Experiment --> Protocol : follows_protocol + Experiment --> Sample : uses_sample + Experiment --> Instrument : uses_instrument + Experiment --> Measurement : produces_measurement + Instrument --> CalibrationCertificate : calibrated_by + Calibration --> Instrument : calibration_of + Calibration --> ReferenceMaterial : uses_reference + CustodyRecord --> Sample : custody_of + CustodyTransfer --> Person : released_by + CustodyTransfer --> Person : received_by + CustodyTransfer --> Sample : transfers + CustodyTransfer --> CustodyRecord : recorded_in + LabProcess --> Person : performed_by + Experiment --> LabNotebookEntry : documented_in + Deviation --> Protocol : deviates_from + Sample --> SafetyDataSheet : handled_under + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall m (forall i (Measurement(m) and measured_by(m, i) implies calibration_valid = True)) +%% forall i (Instrument(i) and gt(days_since_calibration, 365) implies calibration_valid = False) +%% forall e (forall p (Experiment(e) and follows_protocol(e, p) implies protocol_approved = True)) +%% forall t (CustodyTransfer(t) implies exists r (recorded_in(t, r))) +%% forall s (Sample(s) and is_biohazard = True implies exists d (handled_under(s, d))) +%% forall e (Experiment(e) and experiment_complete = True implies gte(replicate_count, 3)) +%% forall e (forall s (Experiment(e) and uses_sample(e, s) implies is_expired = False)) +%% forall s (Sample(s) and is_disposed = True implies volume_ml = 0) +%% forall x (not Sample(x) and Instrument(x)) +%% forall x (not Measurement(x) and Protocol(x)) diff --git a/examples/domain_semiconductor_fab.cypher b/examples/domain_semiconductor_fab.cypher new file mode 100644 index 0000000..851a6c6 --- /dev/null +++ b/examples/domain_semiconductor_fab.cypher @@ -0,0 +1,396 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Site'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Quality'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Facility'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Cleanroom'}) +MERGE (p:OntologyClass {name: 'Site'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Bay'}) +MERGE (p:OntologyClass {name: 'Cleanroom'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LithographyBay'}) +MERGE (p:OntologyClass {name: 'Bay'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EtchBay'}) +MERGE (p:OntologyClass {name: 'Bay'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DiffusionBay'}) +MERGE (p:OntologyClass {name: 'Bay'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThinFilmBay'}) +MERGE (p:OntologyClass {name: 'Bay'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MetrologyBay'}) +MERGE (p:OntologyClass {name: 'Bay'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChemicalMechanicalPolishBay'}) +MERGE (p:OntologyClass {name: 'Bay'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ISOClass'}) +MERGE (p:OntologyClass {name: 'Quality'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ISOClass3'}) +MERGE (p:OntologyClass {name: 'ISOClass'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ISOClass5'}) +MERGE (p:OntologyClass {name: 'ISOClass'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ISOClass7'}) +MERGE (p:OntologyClass {name: 'ISOClass'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Wafer'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductWafer'}) +MERGE (p:OntologyClass {name: 'Wafer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MonitorWafer'}) +MERGE (p:OntologyClass {name: 'Wafer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DummyWafer'}) +MERGE (p:OntologyClass {name: 'Wafer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Lot'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductionLot'}) +MERGE (p:OntologyClass {name: 'Lot'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EngineeringLot'}) +MERGE (p:OntologyClass {name: 'Lot'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HotLot'}) +MERGE (p:OntologyClass {name: 'ProductionLot'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Foup'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Reticle'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Die'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'GoodDie'}) +MERGE (p:OntologyClass {name: 'Die'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ScrapDie'}) +MERGE (p:OntologyClass {name: 'Die'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessChemical'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Photoresist'}) +MERGE (p:OntologyClass {name: 'ProcessChemical'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessGas'}) +MERGE (p:OntologyClass {name: 'ProcessChemical'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Slurry'}) +MERGE (p:OntologyClass {name: 'ProcessChemical'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tool'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessTool'}) +MERGE (p:OntologyClass {name: 'Tool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Stepper'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Scanner'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CoaterDeveloper'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PlasmaEtcher'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DiffusionFurnace'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CvdChamber'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PvdChamber'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IonImplanter'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CmpPolisher'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WetBench'}) +MERGE (p:OntologyClass {name: 'ProcessTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MetrologyTool'}) +MERGE (p:OntologyClass {name: 'Tool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CriticalDimensionSem'}) +MERGE (p:OntologyClass {name: 'MetrologyTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OpticalOverlayTool'}) +MERGE (p:OntologyClass {name: 'MetrologyTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FilmThicknessGauge'}) +MERGE (p:OntologyClass {name: 'MetrologyTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InspectionTool'}) +MERGE (p:OntologyClass {name: 'Tool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BrightFieldInspector'}) +MERGE (p:OntologyClass {name: 'InspectionTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DarkFieldInspector'}) +MERGE (p:OntologyClass {name: 'InspectionTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DefectReviewSem'}) +MERGE (p:OntologyClass {name: 'InspectionTool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WaferProber'}) +MERGE (p:OntologyClass {name: 'Tool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AutomatedMaterialHandling'}) +MERGE (p:OntologyClass {name: 'Tool'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessStep'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Photolithography'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Etch'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Deposition'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Implantation'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Diffusion'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Planarization'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WetClean'}) +MERGE (p:OntologyClass {name: 'ProcessStep'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MetrologyStep'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InspectionStep'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ElectricalTest'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Rework'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessFlow'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Layer'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Recipe'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'QualifiedRecipe'}) +MERGE (p:OntologyClass {name: 'Recipe'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RecipeParameter'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ControlPlan'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Measurement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CriticalDimensionMeasurement'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OverlayMeasurement'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ThicknessMeasurement'}) +MERGE (p:OntologyClass {name: 'Measurement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Defect'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ParticleDefect'}) +MERGE (p:OntologyClass {name: 'Defect'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ScratchDefect'}) +MERGE (p:OntologyClass {name: 'Defect'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PatternDefect'}) +MERGE (p:OntologyClass {name: 'Defect'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'KillerDefect'}) +MERGE (p:OntologyClass {name: 'Defect'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WaferMap'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'YieldReport'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SpcChart'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OutOfControlEvent'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HoldOrder'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProcessEngineerRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EquipmentTechnicianRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'YieldEngineerRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OperatorRole'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Lot'}) +MERGE (t:OntologyClass {name: 'Wafer'}) +MERGE (s)-[:RELATION {name: 'contains_wafer'}]->(t); +MERGE (s:OntologyClass {name: 'Lot'}) +MERGE (t:OntologyClass {name: 'Foup'}) +MERGE (s)-[:RELATION {name: 'carried_in'}]->(t); +MERGE (s:OntologyClass {name: 'Tool'}) +MERGE (t:OntologyClass {name: 'Bay'}) +MERGE (s)-[:RELATION {name: 'located_in'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'Lot'}) +MERGE (s)-[:RELATION {name: 'processes_lot'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'Tool'}) +MERGE (s)-[:RELATION {name: 'performed_on'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'Recipe'}) +MERGE (s)-[:RELATION {name: 'uses_recipe'}]->(t); +MERGE (s:OntologyClass {name: 'Recipe'}) +MERGE (t:OntologyClass {name: 'RecipeParameter'}) +MERGE (s)-[:RELATION {name: 'has_parameter'}]->(t); +MERGE (s:OntologyClass {name: 'Photolithography'}) +MERGE (t:OntologyClass {name: 'Reticle'}) +MERGE (s)-[:RELATION {name: 'uses_reticle'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'Layer'}) +MERGE (s)-[:RELATION {name: 'forms_layer'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'ProcessStep'}) +MERGE (s)-[:RELATION {name: 'follows'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'ProcessFlow'}) +MERGE (s)-[:RELATION {name: 'part_of_flow'}]->(t); +MERGE (s:OntologyClass {name: 'MetrologyStep'}) +MERGE (t:OntologyClass {name: 'Lot'}) +MERGE (s)-[:RELATION {name: 'measures'}]->(t); +MERGE (s:OntologyClass {name: 'MetrologyStep'}) +MERGE (t:OntologyClass {name: 'MetrologyTool'}) +MERGE (s)-[:RELATION {name: 'measured_on'}]->(t); +MERGE (s:OntologyClass {name: 'MetrologyStep'}) +MERGE (t:OntologyClass {name: 'Measurement'}) +MERGE (s)-[:RELATION {name: 'produces'}]->(t); +MERGE (s:OntologyClass {name: 'InspectionStep'}) +MERGE (t:OntologyClass {name: 'Wafer'}) +MERGE (s)-[:RELATION {name: 'inspects'}]->(t); +MERGE (s:OntologyClass {name: 'InspectionStep'}) +MERGE (t:OntologyClass {name: 'Defect'}) +MERGE (s)-[:RELATION {name: 'detects'}]->(t); +MERGE (s:OntologyClass {name: 'Defect'}) +MERGE (t:OntologyClass {name: 'Wafer'}) +MERGE (s)-[:RELATION {name: 'found_on'}]->(t); +MERGE (s:OntologyClass {name: 'HoldOrder'}) +MERGE (t:OntologyClass {name: 'Lot'}) +MERGE (s)-[:RELATION {name: 'hold_for'}]->(t); +MERGE (s:OntologyClass {name: 'HoldOrder'}) +MERGE (t:OntologyClass {name: 'OutOfControlEvent'}) +MERGE (s)-[:RELATION {name: 'triggered_by'}]->(t); +MERGE (s:OntologyClass {name: 'YieldReport'}) +MERGE (t:OntologyClass {name: 'Lot'}) +MERGE (s)-[:RELATION {name: 'summarises'}]->(t); +MERGE (s:OntologyClass {name: 'WaferMap'}) +MERGE (t:OntologyClass {name: 'Wafer'}) +MERGE (s)-[:RELATION {name: 'maps'}]->(t); +MERGE (s:OntologyClass {name: 'ProcessStep'}) +MERGE (t:OntologyClass {name: 'ControlPlan'}) +MERGE (s)-[:RELATION {name: 'governed_by'}]->(t); +// Axiom Validations +// Axiom validation: LithographyBay iso_class_number lte 5 +MATCH (n:`LithographyBay`) WHERE NOT (n.`iso_class_number` <= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Wafer wafer_diameter_mm gte 100 +MATCH (n:`Wafer`) WHERE NOT (n.`wafer_diameter_mm` >= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Wafer wafer_diameter_mm lte 450 +MATCH (n:`Wafer`) WHERE NOT (n.`wafer_diameter_mm` <= 450) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Wafer die_yield_pct gte 0 +MATCH (n:`Wafer`) WHERE NOT (n.`die_yield_pct` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Wafer die_yield_pct lte 100 +MATCH (n:`Wafer`) WHERE NOT (n.`die_yield_pct` <= 100) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Lot wafer_count gte 1 +MATCH (n:`Lot`) WHERE NOT (n.`wafer_count` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Lot wafer_count lte 25 +MATCH (n:`Lot`) WHERE NOT (n.`wafer_count` <= 25) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Lot rework_count lte 2 +MATCH (n:`Lot`) WHERE NOT (n.`rework_count` <= 2) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: ProcessTool is_qualified eq True +MATCH (n:`ProcessTool`) WHERE NOT (n.`is_qualified` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: QualifiedRecipe is_released eq True +MATCH (n:`QualifiedRecipe`) WHERE NOT (n.`is_released` = true) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: KillerDefect is_killer eq True +MATCH (n:`KillerDefect`) WHERE NOT (n.`is_killer` = true) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall s (ProcessStep(s) implies exists r (Recipe(r) and uses_recipe(s, r))) +// forall p (Photolithography(p) implies exists r (Reticle(r) and uses_reticle(p, r))) +// forall h (HoldOrder(h) implies exists l (Lot(l) and hold_for(h, l))) +// forall w (ProductWafer(w) implies not DummyWafer(w)) +// forall t (ProcessTool(t) implies not MetrologyTool(t)) diff --git a/examples/domain_semiconductor_fab.d2 b/examples/domain_semiconductor_fab.d2 new file mode 100644 index 0000000..eced986 --- /dev/null +++ b/examples/domain_semiconductor_fab.d2 @@ -0,0 +1,254 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Site": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"Quality": { shape: class } +"InformationContentEntity": { shape: class } +"Facility": { shape: class } +"Cleanroom": { shape: class } +"Bay": { shape: class } +"LithographyBay": { shape: class } +"EtchBay": { shape: class } +"DiffusionBay": { shape: class } +"ThinFilmBay": { shape: class } +"MetrologyBay": { shape: class } +"ChemicalMechanicalPolishBay": { shape: class } +"ISOClass": { shape: class } +"ISOClass3": { shape: class } +"ISOClass5": { shape: class } +"ISOClass7": { shape: class } +"Wafer": { shape: class } +"ProductWafer": { shape: class } +"MonitorWafer": { shape: class } +"DummyWafer": { shape: class } +"Lot": { shape: class } +"ProductionLot": { shape: class } +"EngineeringLot": { shape: class } +"HotLot": { shape: class } +"Foup": { shape: class } +"Reticle": { shape: class } +"Die": { shape: class } +"GoodDie": { shape: class } +"ScrapDie": { shape: class } +"ProcessChemical": { shape: class } +"Photoresist": { shape: class } +"ProcessGas": { shape: class } +"Slurry": { shape: class } +"Tool": { shape: class } +"ProcessTool": { shape: class } +"Stepper": { shape: class } +"Scanner": { shape: class } +"CoaterDeveloper": { shape: class } +"PlasmaEtcher": { shape: class } +"DiffusionFurnace": { shape: class } +"CvdChamber": { shape: class } +"PvdChamber": { shape: class } +"IonImplanter": { shape: class } +"CmpPolisher": { shape: class } +"WetBench": { shape: class } +"MetrologyTool": { shape: class } +"CriticalDimensionSem": { shape: class } +"OpticalOverlayTool": { shape: class } +"FilmThicknessGauge": { shape: class } +"InspectionTool": { shape: class } +"BrightFieldInspector": { shape: class } +"DarkFieldInspector": { shape: class } +"DefectReviewSem": { shape: class } +"WaferProber": { shape: class } +"AutomatedMaterialHandling": { shape: class } +"ProcessStep": { shape: class } +"Photolithography": { shape: class } +"Etch": { shape: class } +"Deposition": { shape: class } +"Implantation": { shape: class } +"Diffusion": { shape: class } +"Planarization": { shape: class } +"WetClean": { shape: class } +"MetrologyStep": { shape: class } +"InspectionStep": { shape: class } +"ElectricalTest": { shape: class } +"Rework": { shape: class } +"ProcessFlow": { shape: class } +"Layer": { shape: class } +"Recipe": { shape: class } +"QualifiedRecipe": { shape: class } +"RecipeParameter": { shape: class } +"ControlPlan": { shape: class } +"Measurement": { shape: class } +"CriticalDimensionMeasurement": { shape: class } +"OverlayMeasurement": { shape: class } +"ThicknessMeasurement": { shape: class } +"Defect": { shape: class } +"ParticleDefect": { shape: class } +"ScratchDefect": { shape: class } +"PatternDefect": { shape: class } +"KillerDefect": { shape: class } +"WaferMap": { shape: class } +"YieldReport": { shape: class } +"SpcChart": { shape: class } +"OutOfControlEvent": { shape: class } +"HoldOrder": { shape: class } +"ProcessEngineerRole": { shape: class } +"EquipmentTechnicianRole": { shape: class } +"YieldEngineerRole": { shape: class } +"OperatorRole": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Site" -> "IndependentContinuant" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"Quality" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Facility" -> "Site" +"Cleanroom" -> "Site" +"Bay" -> "Cleanroom" +"LithographyBay" -> "Bay" +"EtchBay" -> "Bay" +"DiffusionBay" -> "Bay" +"ThinFilmBay" -> "Bay" +"MetrologyBay" -> "Bay" +"ChemicalMechanicalPolishBay" -> "Bay" +"ISOClass" -> "Quality" +"ISOClass3" -> "ISOClass" +"ISOClass5" -> "ISOClass" +"ISOClass7" -> "ISOClass" +"Wafer" -> "Object" +"ProductWafer" -> "Wafer" +"MonitorWafer" -> "Wafer" +"DummyWafer" -> "Wafer" +"Lot" -> "Object" +"ProductionLot" -> "Lot" +"EngineeringLot" -> "Lot" +"HotLot" -> "ProductionLot" +"Foup" -> "Object" +"Reticle" -> "Object" +"Die" -> "Object" +"GoodDie" -> "Die" +"ScrapDie" -> "Die" +"ProcessChemical" -> "Object" +"Photoresist" -> "ProcessChemical" +"ProcessGas" -> "ProcessChemical" +"Slurry" -> "ProcessChemical" +"Tool" -> "Object" +"ProcessTool" -> "Tool" +"Stepper" -> "ProcessTool" +"Scanner" -> "ProcessTool" +"CoaterDeveloper" -> "ProcessTool" +"PlasmaEtcher" -> "ProcessTool" +"DiffusionFurnace" -> "ProcessTool" +"CvdChamber" -> "ProcessTool" +"PvdChamber" -> "ProcessTool" +"IonImplanter" -> "ProcessTool" +"CmpPolisher" -> "ProcessTool" +"WetBench" -> "ProcessTool" +"MetrologyTool" -> "Tool" +"CriticalDimensionSem" -> "MetrologyTool" +"OpticalOverlayTool" -> "MetrologyTool" +"FilmThicknessGauge" -> "MetrologyTool" +"InspectionTool" -> "Tool" +"BrightFieldInspector" -> "InspectionTool" +"DarkFieldInspector" -> "InspectionTool" +"DefectReviewSem" -> "InspectionTool" +"WaferProber" -> "Tool" +"AutomatedMaterialHandling" -> "Tool" +"ProcessStep" -> "Process" +"Photolithography" -> "ProcessStep" +"Etch" -> "ProcessStep" +"Deposition" -> "ProcessStep" +"Implantation" -> "ProcessStep" +"Diffusion" -> "ProcessStep" +"Planarization" -> "ProcessStep" +"WetClean" -> "ProcessStep" +"MetrologyStep" -> "Process" +"InspectionStep" -> "Process" +"ElectricalTest" -> "Process" +"Rework" -> "Process" +"ProcessFlow" -> "InformationContentEntity" +"Layer" -> "InformationContentEntity" +"Recipe" -> "InformationContentEntity" +"QualifiedRecipe" -> "Recipe" +"RecipeParameter" -> "InformationContentEntity" +"ControlPlan" -> "InformationContentEntity" +"Measurement" -> "InformationContentEntity" +"CriticalDimensionMeasurement" -> "Measurement" +"OverlayMeasurement" -> "Measurement" +"ThicknessMeasurement" -> "Measurement" +"Defect" -> "InformationContentEntity" +"ParticleDefect" -> "Defect" +"ScratchDefect" -> "Defect" +"PatternDefect" -> "Defect" +"KillerDefect" -> "Defect" +"WaferMap" -> "InformationContentEntity" +"YieldReport" -> "InformationContentEntity" +"SpcChart" -> "InformationContentEntity" +"OutOfControlEvent" -> "InformationContentEntity" +"HoldOrder" -> "InformationContentEntity" +"ProcessEngineerRole" -> "Role" +"EquipmentTechnicianRole" -> "Role" +"YieldEngineerRole" -> "Role" +"OperatorRole" -> "Role" +"Lot"."lot_id": String +"Lot"."wafer_count": Integer +"Wafer"."wafer_diameter_mm": Integer +"Wafer"."wafer_thickness_um": Integer +"Lot"."lot_priority": Integer +"Lot"."is_on_hold": Boolean +"Tool"."tool_state": String +"Tool"."is_qualified": Boolean +"Tool"."is_in_maintenance": Boolean +"ProcessTool"."chamber_pressure_mtorr": Integer +"ProcessTool"."process_temp_c": Integer +"Cleanroom"."iso_class_number": Integer +"Cleanroom"."particle_count_per_m3": Integer +"Recipe"."is_released": Boolean +"Recipe"."is_golden": Boolean +"CriticalDimensionMeasurement"."cd_nm": Integer +"CriticalDimensionMeasurement"."cd_target_nm": Integer +"OverlayMeasurement"."overlay_nm": Integer +"ThicknessMeasurement"."film_thickness_nm": Integer +"Wafer"."defect_density_per_cm2": Integer +"Defect"."defect_size_nm": Integer +"Defect"."is_killer": Boolean +"Wafer"."die_yield_pct": Integer +"YieldReport"."line_yield_pct": Integer +"Lot"."rework_count": Integer +"Wafer"."is_cross_contaminated": Boolean +"Lot" -> "Wafer": contains_wafer +"Lot" -> "Foup": carried_in +"Tool" -> "Bay": located_in +"ProcessStep" -> "Lot": processes_lot +"ProcessStep" -> "Tool": performed_on +"ProcessStep" -> "Recipe": uses_recipe +"Recipe" -> "RecipeParameter": has_parameter +"Photolithography" -> "Reticle": uses_reticle +"ProcessStep" -> "Layer": forms_layer +"ProcessStep" -> "ProcessStep": follows +"ProcessStep" -> "ProcessFlow": part_of_flow +"MetrologyStep" -> "Lot": measures +"MetrologyStep" -> "MetrologyTool": measured_on +"MetrologyStep" -> "Measurement": produces +"InspectionStep" -> "Wafer": inspects +"InspectionStep" -> "Defect": detects +"Defect" -> "Wafer": found_on +"HoldOrder" -> "Lot": hold_for +"HoldOrder" -> "OutOfControlEvent": triggered_by +"YieldReport" -> "Lot": summarises +"WaferMap" -> "Wafer": maps +"ProcessStep" -> "ControlPlan": governed_by +# WARNING: The following axioms could not be mapped to field constraints: +# forall s (ProcessStep(s) implies exists r (Recipe(r) and uses_recipe(s, r))) +# forall p (Photolithography(p) implies exists r (Reticle(r) and uses_reticle(p, r))) +# forall h (HoldOrder(h) implies exists l (Lot(l) and hold_for(h, l))) +# forall w (ProductWafer(w) implies not DummyWafer(w)) +# forall t (ProcessTool(t) implies not MetrologyTool(t)) diff --git a/examples/domain_semiconductor_fab.d2.svg b/examples/domain_semiconductor_fab.d2.svg new file mode 100644 index 0000000..06869e8 --- /dev/null +++ b/examples/domain_semiconductor_fab.d2.svg @@ -0,0 +1,123 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectSiteOccurrentProcessRoleFunctionQualityInformationContentEntityFacilityCleanroom+iso_class_numberInteger+particle_count_per_m3IntegerBayLithographyBayEtchBayDiffusionBayThinFilmBayMetrologyBayChemicalMechanicalPolishBayISOClassISOClass3ISOClass5ISOClass7Wafer+wafer_diameter_mmInteger+wafer_thickness_umInteger+defect_density_per_cm2Integer+die_yield_pctInteger+is_cross_contaminatedBooleanProductWaferMonitorWaferDummyWaferLot+lot_idString+wafer_countInteger+lot_priorityInteger+is_on_holdBoolean+rework_countIntegerProductionLotEngineeringLotHotLotFoupReticleDieGoodDieScrapDieProcessChemicalPhotoresistProcessGasSlurryTool+tool_stateString+is_qualifiedBoolean+is_in_maintenanceBooleanProcessTool+chamber_pressure_mtorrInteger+process_temp_cIntegerStepperScannerCoaterDeveloperPlasmaEtcherDiffusionFurnaceCvdChamberPvdChamberIonImplanterCmpPolisherWetBenchMetrologyToolCriticalDimensionSemOpticalOverlayToolFilmThicknessGaugeInspectionToolBrightFieldInspectorDarkFieldInspectorDefectReviewSemWaferProberAutomatedMaterialHandlingProcessStepPhotolithographyEtchDepositionImplantationDiffusionPlanarizationWetCleanMetrologyStepInspectionStepElectricalTestReworkProcessFlowLayerRecipe+is_releasedBoolean+is_goldenBooleanQualifiedRecipeRecipeParameterControlPlanMeasurementCriticalDimensionMeasurement+cd_nmInteger+cd_target_nmIntegerOverlayMeasurement+overlay_nmIntegerThicknessMeasurement+film_thickness_nmIntegerDefect+defect_size_nmInteger+is_killerBooleanParticleDefectScratchDefectPatternDefectKillerDefectWaferMapYieldReport+line_yield_pctIntegerSpcChartOutOfControlEventHoldOrderProcessEngineerRoleEquipmentTechnicianRoleYieldEngineerRoleOperatorRole contains_wafercarried_inlocated_inprocesses_lotperformed_onuses_recipehas_parameteruses_reticleforms_layerfollowspart_of_flowmeasuresmeasured_onproducesinspectsdetectsfound_onhold_fortriggered_bysummarisesmapsgoverned_by + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_semiconductor_fab.logic b/examples/domain_semiconductor_fab.logic new file mode 100644 index 0000000..62c0151 --- /dev/null +++ b/examples/domain_semiconductor_fab.logic @@ -0,0 +1,232 @@ +; --- Semiconductor Wafer Fab --- +; Models lots, wafers, process steps, tools, recipes, cleanroom classes, +; metrology, yield and defect inspection. +; Axioms enforce: cleanroom class limits per area, wafer/lot bounds, recipe +; qualification before use, metrology hold rules, and yield / defect sanity. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Site IndependentContinuant) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept Quality Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Facility and Cleanroom --- +(def-concept Facility Site) +(def-concept Cleanroom Site) +(def-concept Bay Cleanroom) +(def-concept LithographyBay Bay) +(def-concept EtchBay Bay) +(def-concept DiffusionBay Bay) +(def-concept ThinFilmBay Bay) +(def-concept MetrologyBay Bay) +(def-concept ChemicalMechanicalPolishBay Bay) +(def-concept ISOClass Quality) +(def-concept ISOClass3 ISOClass) +(def-concept ISOClass5 ISOClass) +(def-concept ISOClass7 ISOClass) + +; --- Material --- +(def-concept Wafer Object) +(def-concept ProductWafer Wafer) +(def-concept MonitorWafer Wafer) +(def-concept DummyWafer Wafer) +(def-concept Lot Object) +(def-concept ProductionLot Lot) +(def-concept EngineeringLot Lot) +(def-concept HotLot ProductionLot) +(def-concept Foup Object) +(def-concept Reticle Object) +(def-concept Die Object) +(def-concept GoodDie Die) +(def-concept ScrapDie Die) +(def-concept ProcessChemical Object) +(def-concept Photoresist ProcessChemical) +(def-concept ProcessGas ProcessChemical) +(def-concept Slurry ProcessChemical) + +; --- Tools --- +(def-concept Tool Object) +(def-concept ProcessTool Tool) +(def-concept Stepper ProcessTool) +(def-concept Scanner ProcessTool) +(def-concept CoaterDeveloper ProcessTool) +(def-concept PlasmaEtcher ProcessTool) +(def-concept DiffusionFurnace ProcessTool) +(def-concept CvdChamber ProcessTool) +(def-concept PvdChamber ProcessTool) +(def-concept IonImplanter ProcessTool) +(def-concept CmpPolisher ProcessTool) +(def-concept WetBench ProcessTool) +(def-concept MetrologyTool Tool) +(def-concept CriticalDimensionSem MetrologyTool) +(def-concept OpticalOverlayTool MetrologyTool) +(def-concept FilmThicknessGauge MetrologyTool) +(def-concept InspectionTool Tool) +(def-concept BrightFieldInspector InspectionTool) +(def-concept DarkFieldInspector InspectionTool) +(def-concept DefectReviewSem InspectionTool) +(def-concept WaferProber Tool) +(def-concept AutomatedMaterialHandling Tool) + +; --- Process Flow --- +(def-concept ProcessStep Process) +(def-concept Photolithography ProcessStep) +(def-concept Etch ProcessStep) +(def-concept Deposition ProcessStep) +(def-concept Implantation ProcessStep) +(def-concept Diffusion ProcessStep) +(def-concept Planarization ProcessStep) +(def-concept WetClean ProcessStep) +(def-concept MetrologyStep Process) +(def-concept InspectionStep Process) +(def-concept ElectricalTest Process) +(def-concept Rework Process) +(def-concept ProcessFlow InformationContentEntity) +(def-concept Layer InformationContentEntity) +(def-concept Recipe InformationContentEntity) +(def-concept QualifiedRecipe Recipe) +(def-concept RecipeParameter InformationContentEntity) +(def-concept ControlPlan InformationContentEntity) + +; --- Quality Data --- +(def-concept Measurement InformationContentEntity) +(def-concept CriticalDimensionMeasurement Measurement) +(def-concept OverlayMeasurement Measurement) +(def-concept ThicknessMeasurement Measurement) +(def-concept Defect InformationContentEntity) +(def-concept ParticleDefect Defect) +(def-concept ScratchDefect Defect) +(def-concept PatternDefect Defect) +(def-concept KillerDefect Defect) +(def-concept WaferMap InformationContentEntity) +(def-concept YieldReport InformationContentEntity) +(def-concept SpcChart InformationContentEntity) +(def-concept OutOfControlEvent InformationContentEntity) +(def-concept HoldOrder InformationContentEntity) + +; --- Roles --- +(def-concept ProcessEngineerRole Role) +(def-concept EquipmentTechnicianRole Role) +(def-concept YieldEngineerRole Role) +(def-concept OperatorRole Role) + +; --- Relations --- +(def-relation contains_wafer Lot Wafer :cardinality 1..*) +(def-relation carried_in Lot Foup :cardinality 1..1) +(def-relation located_in Tool Bay) +(def-relation processes_lot ProcessStep Lot :cardinality 1..*) +(def-relation performed_on ProcessStep Tool :cardinality 1..1) +(def-relation uses_recipe ProcessStep Recipe :cardinality 1..1) +(def-relation has_parameter Recipe RecipeParameter :cardinality 1..*) +(def-relation uses_reticle Photolithography Reticle :cardinality 1..1) +(def-relation forms_layer ProcessStep Layer) +(def-relation follows ProcessStep ProcessStep :cardinality 0..1) +(def-relation part_of_flow ProcessStep ProcessFlow) +(def-relation measures MetrologyStep Lot) +(def-relation measured_on MetrologyStep MetrologyTool) +(def-relation produces MetrologyStep Measurement :cardinality 1..*) +(def-relation inspects InspectionStep Wafer) +(def-relation detects InspectionStep Defect :cardinality 0..*) +(def-relation found_on Defect Wafer) +(def-relation hold_for HoldOrder Lot) +(def-relation triggered_by HoldOrder OutOfControlEvent) +(def-relation summarises YieldReport Lot) +(def-relation maps WaferMap Wafer) +(def-relation governed_by ProcessStep ControlPlan) + +; --- Properties --- +(def-property lot_id Lot String :cardinality 1..1) +(def-property wafer_count Lot Integer) +(def-property wafer_diameter_mm Wafer Integer) +(def-property wafer_thickness_um Wafer Integer) +(def-property lot_priority Lot Integer) +(def-property is_on_hold Lot Boolean) +(def-property tool_state Tool String) +(def-property is_qualified Tool Boolean) +(def-property is_in_maintenance Tool Boolean) +(def-property chamber_pressure_mtorr ProcessTool Integer) +(def-property process_temp_c ProcessTool Integer) +(def-property iso_class_number Cleanroom Integer) +(def-property particle_count_per_m3 Cleanroom Integer) +(def-property is_released Recipe Boolean) +(def-property is_golden Recipe Boolean) +(def-property cd_nm CriticalDimensionMeasurement Integer) +(def-property cd_target_nm CriticalDimensionMeasurement Integer) +(def-property overlay_nm OverlayMeasurement Integer) +(def-property film_thickness_nm ThicknessMeasurement Integer) +(def-property defect_density_per_cm2 Wafer Integer) +(def-property defect_size_nm Defect Integer) +(def-property is_killer Defect Boolean) +(def-property die_yield_pct Wafer Integer) +(def-property line_yield_pct YieldReport Integer) +(def-property rework_count Lot Integer) +(def-property is_cross_contaminated Wafer Boolean) + +; --- Axioms --- + +; 1. A lot carries 1 to 25 wafers (one FOUP) +(forall (l) + (implies (Lot l) + (and (gte wafer_count 1) (lte wafer_count 25)))) + +; 2. Wafer diameters are standard sizes within 100..450 mm +(forall (w) + (implies (Wafer w) + (and (gte wafer_diameter_mm 100) (lte wafer_diameter_mm 450)))) + +; 3. Yield figures are percentages +(forall (w) + (implies (Wafer w) + (and (gte die_yield_pct 0) (lte die_yield_pct 100)))) + +; 4. Lithography bays are held to at most ISO class 5 airborne cleanliness +(forall (b) + (implies (LithographyBay b) + (lte iso_class_number 5))) + +; 5. Process steps may only run a released recipe +(forall (r) + (implies (QualifiedRecipe r) (eq is_released True))) + +; 6. A process tool must be qualified before it processes product +(forall (t) + (implies (ProcessTool t) (eq is_qualified True))) + +; 7. Every process step uses a recipe +(forall (s) + (implies (ProcessStep s) + (exists (r) (and (Recipe r) (uses_recipe s r))))) + +; 8. Photolithography requires a reticle +(forall (p) + (implies (Photolithography p) + (exists (r) (and (Reticle r) (uses_reticle p r))))) + +; 9. Killer defects are always flagged as killers +(forall (d) + (implies (KillerDefect d) (eq is_killer True))) + +; 10. An out-of-control event produces a hold: a hold order must name its lot +(forall (h) + (implies (HoldOrder h) + (exists (l) (and (Lot l) (hold_for h l))))) + +; 11. Rework is limited to at most 2 passes per lot +(forall (l) + (implies (Lot l) (lte rework_count 2))) + +; 12. Wafer roles are exclusive: a product wafer is never a dummy wafer +(forall (w) + (implies (ProductWafer w) (not (DummyWafer w)))) + +; 13. Process tools and metrology tools are distinct equipment classes +(forall (t) + (implies (ProcessTool t) (not (MetrologyTool t)))) diff --git a/examples/domain_semiconductor_fab.mmd b/examples/domain_semiconductor_fab.mmd new file mode 100644 index 0000000..a37f2dc --- /dev/null +++ b/examples/domain_semiconductor_fab.mmd @@ -0,0 +1,255 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Site["Site"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class Quality["Quality"] + class InformationContentEntity["InformationContentEntity"] + class Facility["Facility"] + class Cleanroom["Cleanroom"] + class Bay["Bay"] + class LithographyBay["LithographyBay"] + class EtchBay["EtchBay"] + class DiffusionBay["DiffusionBay"] + class ThinFilmBay["ThinFilmBay"] + class MetrologyBay["MetrologyBay"] + class ChemicalMechanicalPolishBay["ChemicalMechanicalPolishBay"] + class ISOClass["ISOClass"] + class ISOClass3["ISOClass3"] + class ISOClass5["ISOClass5"] + class ISOClass7["ISOClass7"] + class Wafer["Wafer"] + class ProductWafer["ProductWafer"] + class MonitorWafer["MonitorWafer"] + class DummyWafer["DummyWafer"] + class Lot["Lot"] + class ProductionLot["ProductionLot"] + class EngineeringLot["EngineeringLot"] + class HotLot["HotLot"] + class Foup["Foup"] + class Reticle["Reticle"] + class Die["Die"] + class GoodDie["GoodDie"] + class ScrapDie["ScrapDie"] + class ProcessChemical["ProcessChemical"] + class Photoresist["Photoresist"] + class ProcessGas["ProcessGas"] + class Slurry["Slurry"] + class Tool["Tool"] + class ProcessTool["ProcessTool"] + class Stepper["Stepper"] + class Scanner["Scanner"] + class CoaterDeveloper["CoaterDeveloper"] + class PlasmaEtcher["PlasmaEtcher"] + class DiffusionFurnace["DiffusionFurnace"] + class CvdChamber["CvdChamber"] + class PvdChamber["PvdChamber"] + class IonImplanter["IonImplanter"] + class CmpPolisher["CmpPolisher"] + class WetBench["WetBench"] + class MetrologyTool["MetrologyTool"] + class CriticalDimensionSem["CriticalDimensionSem"] + class OpticalOverlayTool["OpticalOverlayTool"] + class FilmThicknessGauge["FilmThicknessGauge"] + class InspectionTool["InspectionTool"] + class BrightFieldInspector["BrightFieldInspector"] + class DarkFieldInspector["DarkFieldInspector"] + class DefectReviewSem["DefectReviewSem"] + class WaferProber["WaferProber"] + class AutomatedMaterialHandling["AutomatedMaterialHandling"] + class ProcessStep["ProcessStep"] + class Photolithography["Photolithography"] + class Etch["Etch"] + class Deposition["Deposition"] + class Implantation["Implantation"] + class Diffusion["Diffusion"] + class Planarization["Planarization"] + class WetClean["WetClean"] + class MetrologyStep["MetrologyStep"] + class InspectionStep["InspectionStep"] + class ElectricalTest["ElectricalTest"] + class Rework["Rework"] + class ProcessFlow["ProcessFlow"] + class Layer["Layer"] + class Recipe["Recipe"] + class QualifiedRecipe["QualifiedRecipe"] + class RecipeParameter["RecipeParameter"] + class ControlPlan["ControlPlan"] + class Measurement["Measurement"] + class CriticalDimensionMeasurement["CriticalDimensionMeasurement"] + class OverlayMeasurement["OverlayMeasurement"] + class ThicknessMeasurement["ThicknessMeasurement"] + class Defect["Defect"] + class ParticleDefect["ParticleDefect"] + class ScratchDefect["ScratchDefect"] + class PatternDefect["PatternDefect"] + class KillerDefect["KillerDefect"] + class WaferMap["WaferMap"] + class YieldReport["YieldReport"] + class SpcChart["SpcChart"] + class OutOfControlEvent["OutOfControlEvent"] + class HoldOrder["HoldOrder"] + class ProcessEngineerRole["ProcessEngineerRole"] + class EquipmentTechnicianRole["EquipmentTechnicianRole"] + class YieldEngineerRole["YieldEngineerRole"] + class OperatorRole["OperatorRole"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + IndependentContinuant <|-- Site + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- Quality + Continuant <|-- InformationContentEntity + Site <|-- Facility + Site <|-- Cleanroom + Cleanroom <|-- Bay + Bay <|-- LithographyBay + Bay <|-- EtchBay + Bay <|-- DiffusionBay + Bay <|-- ThinFilmBay + Bay <|-- MetrologyBay + Bay <|-- ChemicalMechanicalPolishBay + Quality <|-- ISOClass + ISOClass <|-- ISOClass3 + ISOClass <|-- ISOClass5 + ISOClass <|-- ISOClass7 + Object <|-- Wafer + Wafer <|-- ProductWafer + Wafer <|-- MonitorWafer + Wafer <|-- DummyWafer + Object <|-- Lot + Lot <|-- ProductionLot + Lot <|-- EngineeringLot + ProductionLot <|-- HotLot + Object <|-- Foup + Object <|-- Reticle + Object <|-- Die + Die <|-- GoodDie + Die <|-- ScrapDie + Object <|-- ProcessChemical + ProcessChemical <|-- Photoresist + ProcessChemical <|-- ProcessGas + ProcessChemical <|-- Slurry + Object <|-- Tool + Tool <|-- ProcessTool + ProcessTool <|-- Stepper + ProcessTool <|-- Scanner + ProcessTool <|-- CoaterDeveloper + ProcessTool <|-- PlasmaEtcher + ProcessTool <|-- DiffusionFurnace + ProcessTool <|-- CvdChamber + ProcessTool <|-- PvdChamber + ProcessTool <|-- IonImplanter + ProcessTool <|-- CmpPolisher + ProcessTool <|-- WetBench + Tool <|-- MetrologyTool + MetrologyTool <|-- CriticalDimensionSem + MetrologyTool <|-- OpticalOverlayTool + MetrologyTool <|-- FilmThicknessGauge + Tool <|-- InspectionTool + InspectionTool <|-- BrightFieldInspector + InspectionTool <|-- DarkFieldInspector + InspectionTool <|-- DefectReviewSem + Tool <|-- WaferProber + Tool <|-- AutomatedMaterialHandling + Process <|-- ProcessStep + ProcessStep <|-- Photolithography + ProcessStep <|-- Etch + ProcessStep <|-- Deposition + ProcessStep <|-- Implantation + ProcessStep <|-- Diffusion + ProcessStep <|-- Planarization + ProcessStep <|-- WetClean + Process <|-- MetrologyStep + Process <|-- InspectionStep + Process <|-- ElectricalTest + Process <|-- Rework + InformationContentEntity <|-- ProcessFlow + InformationContentEntity <|-- Layer + InformationContentEntity <|-- Recipe + Recipe <|-- QualifiedRecipe + InformationContentEntity <|-- RecipeParameter + InformationContentEntity <|-- ControlPlan + InformationContentEntity <|-- Measurement + Measurement <|-- CriticalDimensionMeasurement + Measurement <|-- OverlayMeasurement + Measurement <|-- ThicknessMeasurement + InformationContentEntity <|-- Defect + Defect <|-- ParticleDefect + Defect <|-- ScratchDefect + Defect <|-- PatternDefect + Defect <|-- KillerDefect + InformationContentEntity <|-- WaferMap + InformationContentEntity <|-- YieldReport + InformationContentEntity <|-- SpcChart + InformationContentEntity <|-- OutOfControlEvent + InformationContentEntity <|-- HoldOrder + Role <|-- ProcessEngineerRole + Role <|-- EquipmentTechnicianRole + Role <|-- YieldEngineerRole + Role <|-- OperatorRole + Lot : +String lot_id + Lot : +Integer wafer_count + Wafer : +Integer wafer_diameter_mm + Wafer : +Integer wafer_thickness_um + Lot : +Integer lot_priority + Lot : +Boolean is_on_hold + Tool : +String tool_state + Tool : +Boolean is_qualified + Tool : +Boolean is_in_maintenance + ProcessTool : +Integer chamber_pressure_mtorr + ProcessTool : +Integer process_temp_c + Cleanroom : +Integer iso_class_number + Cleanroom : +Integer particle_count_per_m3 + Recipe : +Boolean is_released + Recipe : +Boolean is_golden + CriticalDimensionMeasurement : +Integer cd_nm + CriticalDimensionMeasurement : +Integer cd_target_nm + OverlayMeasurement : +Integer overlay_nm + ThicknessMeasurement : +Integer film_thickness_nm + Wafer : +Integer defect_density_per_cm2 + Defect : +Integer defect_size_nm + Defect : +Boolean is_killer + Wafer : +Integer die_yield_pct + YieldReport : +Integer line_yield_pct + Lot : +Integer rework_count + Wafer : +Boolean is_cross_contaminated + Lot --> Wafer : contains_wafer + Lot --> Foup : carried_in + Tool --> Bay : located_in + ProcessStep --> Lot : processes_lot + ProcessStep --> Tool : performed_on + ProcessStep --> Recipe : uses_recipe + Recipe --> RecipeParameter : has_parameter + Photolithography --> Reticle : uses_reticle + ProcessStep --> Layer : forms_layer + ProcessStep --> ProcessStep : follows + ProcessStep --> ProcessFlow : part_of_flow + MetrologyStep --> Lot : measures + MetrologyStep --> MetrologyTool : measured_on + MetrologyStep --> Measurement : produces + InspectionStep --> Wafer : inspects + InspectionStep --> Defect : detects + Defect --> Wafer : found_on + HoldOrder --> Lot : hold_for + HoldOrder --> OutOfControlEvent : triggered_by + YieldReport --> Lot : summarises + WaferMap --> Wafer : maps + ProcessStep --> ControlPlan : governed_by + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall s (ProcessStep(s) implies exists r (Recipe(r) and uses_recipe(s, r))) +%% forall p (Photolithography(p) implies exists r (Reticle(r) and uses_reticle(p, r))) +%% forall h (HoldOrder(h) implies exists l (Lot(l) and hold_for(h, l))) +%% forall w (ProductWafer(w) implies not DummyWafer(w)) +%% forall t (ProcessTool(t) implies not MetrologyTool(t)) diff --git a/examples/domain_software_delivery.cypher b/examples/domain_software_delivery.cypher new file mode 100644 index 0000000..779e890 --- /dev/null +++ b/examples/domain_software_delivery.cypher @@ -0,0 +1,292 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Person'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Team'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Developer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Reviewer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CodeOwner'}) +MERGE (p:OntologyClass {name: 'Reviewer'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReleaseManager'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'OnCallEngineer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IncidentCommander'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SourceArtifact'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Repository'}) +MERGE (p:OntologyClass {name: 'SourceArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MonorepoRepository'}) +MERGE (p:OntologyClass {name: 'Repository'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Branch'}) +MERGE (p:OntologyClass {name: 'SourceArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProtectedBranch'}) +MERGE (p:OntologyClass {name: 'Branch'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FeatureBranch'}) +MERGE (p:OntologyClass {name: 'Branch'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Commit'}) +MERGE (p:OntologyClass {name: 'SourceArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SignedCommit'}) +MERGE (p:OntologyClass {name: 'Commit'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MergeCommit'}) +MERGE (p:OntologyClass {name: 'Commit'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Tag'}) +MERGE (p:OntologyClass {name: 'SourceArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CodeChange'}) +MERGE (p:OntologyClass {name: 'SourceArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PullRequest'}) +MERGE (p:OntologyClass {name: 'CodeChange'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DraftPullRequest'}) +MERGE (p:OntologyClass {name: 'PullRequest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MergedPullRequest'}) +MERGE (p:OntologyClass {name: 'PullRequest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReviewComment'}) +MERGE (p:OntologyClass {name: 'SourceArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BuildArtifact'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ContainerImage'}) +MERGE (p:OntologyClass {name: 'BuildArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Package'}) +MERGE (p:OntologyClass {name: 'BuildArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SoftwareBillOfMaterials'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Release'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CandidateRelease'}) +MERGE (p:OntologyClass {name: 'Release'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StableRelease'}) +MERGE (p:OntologyClass {name: 'Release'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HotfixRelease'}) +MERGE (p:OntologyClass {name: 'Release'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Changelog'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TestReport'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CoverageReport'}) +MERGE (p:OntologyClass {name: 'TestReport'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PostmortemReport'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Environment'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DevelopmentEnvironment'}) +MERGE (p:OntologyClass {name: 'Environment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StagingEnvironment'}) +MERGE (p:OntologyClass {name: 'Environment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductionEnvironment'}) +MERGE (p:OntologyClass {name: 'Environment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'BuildAgent'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Service'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FeatureFlag'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DeliveryProcess'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CodeReview'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Build'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FailedBuild'}) +MERGE (p:OntologyClass {name: 'Build'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TestRun'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'UnitTestRun'}) +MERGE (p:OntologyClass {name: 'TestRun'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IntegrationTestRun'}) +MERGE (p:OntologyClass {name: 'TestRun'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SecurityScan'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Deployment'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductionDeployment'}) +MERGE (p:OntologyClass {name: 'Deployment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'CanaryDeployment'}) +MERGE (p:OntologyClass {name: 'ProductionDeployment'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Rollback'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IncidentResponse'}) +MERGE (p:OntologyClass {name: 'DeliveryProcess'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Incident'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductionIncident'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SecurityIncident'}) +MERGE (p:OntologyClass {name: 'Incident'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Alert'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Repository'}) +MERGE (t:OntologyClass {name: 'Commit'}) +MERGE (s)-[:RELATION {name: 'contains_commit'}]->(t); +MERGE (s:OntologyClass {name: 'Commit'}) +MERGE (t:OntologyClass {name: 'Person'}) +MERGE (s)-[:RELATION {name: 'authored_by'}]->(t); +MERGE (s:OntologyClass {name: 'PullRequest'}) +MERGE (t:OntologyClass {name: 'Commit'}) +MERGE (s)-[:RELATION {name: 'proposes'}]->(t); +MERGE (s:OntologyClass {name: 'PullRequest'}) +MERGE (t:OntologyClass {name: 'Branch'}) +MERGE (s)-[:RELATION {name: 'targets_branch'}]->(t); +MERGE (s:OntologyClass {name: 'PullRequest'}) +MERGE (t:OntologyClass {name: 'Reviewer'}) +MERGE (s)-[:RELATION {name: 'reviewed_by'}]->(t); +MERGE (s:OntologyClass {name: 'CodeReview'}) +MERGE (t:OntologyClass {name: 'PullRequest'}) +MERGE (s)-[:RELATION {name: 'reviews'}]->(t); +MERGE (s:OntologyClass {name: 'Build'}) +MERGE (t:OntologyClass {name: 'Commit'}) +MERGE (s)-[:RELATION {name: 'builds_from'}]->(t); +MERGE (s:OntologyClass {name: 'Build'}) +MERGE (t:OntologyClass {name: 'BuildArtifact'}) +MERGE (s)-[:RELATION {name: 'produces'}]->(t); +MERGE (s:OntologyClass {name: 'TestRun'}) +MERGE (t:OntologyClass {name: 'Build'}) +MERGE (s)-[:RELATION {name: 'validates'}]->(t); +MERGE (s:OntologyClass {name: 'SecurityScan'}) +MERGE (t:OntologyClass {name: 'BuildArtifact'}) +MERGE (s)-[:RELATION {name: 'scans'}]->(t); +MERGE (s:OntologyClass {name: 'Release'}) +MERGE (t:OntologyClass {name: 'BuildArtifact'}) +MERGE (s)-[:RELATION {name: 'packages_artifact'}]->(t); +MERGE (s:OntologyClass {name: 'Release'}) +MERGE (t:OntologyClass {name: 'SoftwareBillOfMaterials'}) +MERGE (s)-[:RELATION {name: 'has_sbom'}]->(t); +MERGE (s:OntologyClass {name: 'Deployment'}) +MERGE (t:OntologyClass {name: 'Release'}) +MERGE (s)-[:RELATION {name: 'deploys'}]->(t); +MERGE (s:OntologyClass {name: 'Deployment'}) +MERGE (t:OntologyClass {name: 'Environment'}) +MERGE (s)-[:RELATION {name: 'deploys_to'}]->(t); +MERGE (s:OntologyClass {name: 'Rollback'}) +MERGE (t:OntologyClass {name: 'Deployment'}) +MERGE (s)-[:RELATION {name: 'rolls_back'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'Deployment'}) +MERGE (s)-[:RELATION {name: 'caused_by'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'IncidentCommander'}) +MERGE (s)-[:RELATION {name: 'owned_by'}]->(t); +MERGE (s:OntologyClass {name: 'IncidentResponse'}) +MERGE (t:OntologyClass {name: 'Incident'}) +MERGE (s)-[:RELATION {name: 'responds_to'}]->(t); +MERGE (s:OntologyClass {name: 'Incident'}) +MERGE (t:OntologyClass {name: 'PostmortemReport'}) +MERGE (s)-[:RELATION {name: 'documented_in'}]->(t); +MERGE (s:OntologyClass {name: 'Service'}) +MERGE (t:OntologyClass {name: 'Environment'}) +MERGE (s)-[:RELATION {name: 'runs_on'}]->(t); +// Axiom Validations +// Axiom validation: PullRequest lines_changed gte 0 +MATCH (n:`PullRequest`) WHERE NOT (n.`lines_changed` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: PullRequest lines_changed lte 5000 +MATCH (n:`PullRequest`) WHERE NOT (n.`lines_changed` <= 5000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: TestRun tests_failed gte 0 +MATCH (n:`TestRun`) WHERE NOT (n.`tests_failed` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: TestRun tests_total gte 0 +MATCH (n:`TestRun`) WHERE NOT (n.`tests_total` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Incident incident_severity gte 1 +MATCH (n:`Incident`) WHERE NOT (n.`incident_severity` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Incident incident_severity lte 4 +MATCH (n:`Incident`) WHERE NOT (n.`incident_severity` <= 4) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall p (PullRequest(p) and is_merged = True implies ci_passed = True) +// forall p (PullRequest(p) and is_merged = True implies gte(approval_count, 2)) +// forall b (Build(b) and build_succeeded = True implies exists t (TestRun(t))) +// forall r (Release(r) and is_published = True implies is_signed_off = True) +// forall d (forall r (Deployment(d) and deploys(d, r) implies Release(r))) +// forall r (Release(r) and is_signed_off = True implies exists s (has_sbom(r, s))) +// forall i (Incident(i) and is_resolved = False implies exists c (owned_by(i, c))) +// forall i (Incident(i) and incident_severity = 1 and is_resolved = True implies has_postmortem = True) +// forall x (not Commit(x) and Build(x)) +// forall x (not Release(x) and Deployment(x)) diff --git a/examples/domain_software_delivery.d2 b/examples/domain_software_delivery.d2 new file mode 100644 index 0000000..5d213d8 --- /dev/null +++ b/examples/domain_software_delivery.d2 @@ -0,0 +1,188 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"InformationContentEntity": { shape: class } +"Person": { shape: class } +"Team": { shape: class } +"Developer": { shape: class } +"Reviewer": { shape: class } +"CodeOwner": { shape: class } +"ReleaseManager": { shape: class } +"OnCallEngineer": { shape: class } +"IncidentCommander": { shape: class } +"SourceArtifact": { shape: class } +"Repository": { shape: class } +"MonorepoRepository": { shape: class } +"Branch": { shape: class } +"ProtectedBranch": { shape: class } +"FeatureBranch": { shape: class } +"Commit": { shape: class } +"SignedCommit": { shape: class } +"MergeCommit": { shape: class } +"Tag": { shape: class } +"CodeChange": { shape: class } +"PullRequest": { shape: class } +"DraftPullRequest": { shape: class } +"MergedPullRequest": { shape: class } +"ReviewComment": { shape: class } +"BuildArtifact": { shape: class } +"ContainerImage": { shape: class } +"Package": { shape: class } +"SoftwareBillOfMaterials": { shape: class } +"Release": { shape: class } +"CandidateRelease": { shape: class } +"StableRelease": { shape: class } +"HotfixRelease": { shape: class } +"Changelog": { shape: class } +"TestReport": { shape: class } +"CoverageReport": { shape: class } +"PostmortemReport": { shape: class } +"Environment": { shape: class } +"DevelopmentEnvironment": { shape: class } +"StagingEnvironment": { shape: class } +"ProductionEnvironment": { shape: class } +"BuildAgent": { shape: class } +"Service": { shape: class } +"FeatureFlag": { shape: class } +"DeliveryProcess": { shape: class } +"CodeReview": { shape: class } +"Build": { shape: class } +"FailedBuild": { shape: class } +"TestRun": { shape: class } +"UnitTestRun": { shape: class } +"IntegrationTestRun": { shape: class } +"SecurityScan": { shape: class } +"Deployment": { shape: class } +"ProductionDeployment": { shape: class } +"CanaryDeployment": { shape: class } +"Rollback": { shape: class } +"IncidentResponse": { shape: class } +"Incident": { shape: class } +"ProductionIncident": { shape: class } +"SecurityIncident": { shape: class } +"Alert": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Person" -> "Object" +"Team" -> "Object" +"Developer" -> "Role" +"Reviewer" -> "Role" +"CodeOwner" -> "Reviewer" +"ReleaseManager" -> "Role" +"OnCallEngineer" -> "Role" +"IncidentCommander" -> "Role" +"SourceArtifact" -> "InformationContentEntity" +"Repository" -> "SourceArtifact" +"MonorepoRepository" -> "Repository" +"Branch" -> "SourceArtifact" +"ProtectedBranch" -> "Branch" +"FeatureBranch" -> "Branch" +"Commit" -> "SourceArtifact" +"SignedCommit" -> "Commit" +"MergeCommit" -> "Commit" +"Tag" -> "SourceArtifact" +"CodeChange" -> "SourceArtifact" +"PullRequest" -> "CodeChange" +"DraftPullRequest" -> "PullRequest" +"MergedPullRequest" -> "PullRequest" +"ReviewComment" -> "SourceArtifact" +"BuildArtifact" -> "InformationContentEntity" +"ContainerImage" -> "BuildArtifact" +"Package" -> "BuildArtifact" +"SoftwareBillOfMaterials" -> "InformationContentEntity" +"Release" -> "InformationContentEntity" +"CandidateRelease" -> "Release" +"StableRelease" -> "Release" +"HotfixRelease" -> "Release" +"Changelog" -> "InformationContentEntity" +"TestReport" -> "InformationContentEntity" +"CoverageReport" -> "TestReport" +"PostmortemReport" -> "InformationContentEntity" +"Environment" -> "Object" +"DevelopmentEnvironment" -> "Environment" +"StagingEnvironment" -> "Environment" +"ProductionEnvironment" -> "Environment" +"BuildAgent" -> "Object" +"Service" -> "Object" +"FeatureFlag" -> "InformationContentEntity" +"DeliveryProcess" -> "Process" +"CodeReview" -> "DeliveryProcess" +"Build" -> "DeliveryProcess" +"FailedBuild" -> "Build" +"TestRun" -> "DeliveryProcess" +"UnitTestRun" -> "TestRun" +"IntegrationTestRun" -> "TestRun" +"SecurityScan" -> "DeliveryProcess" +"Deployment" -> "DeliveryProcess" +"ProductionDeployment" -> "Deployment" +"CanaryDeployment" -> "ProductionDeployment" +"Rollback" -> "DeliveryProcess" +"IncidentResponse" -> "DeliveryProcess" +"Incident" -> "Occurrent" +"ProductionIncident" -> "Incident" +"SecurityIncident" -> "Incident" +"Alert" -> "InformationContentEntity" +"Commit"."commit_hash": String +"PullRequest"."approval_count": Integer +"PullRequest"."lines_changed": Integer +"PullRequest"."is_merged": Boolean +"PullRequest"."ci_passed": Boolean +"Branch"."is_protected": Boolean +"Build"."build_duration_s": Integer +"Build"."build_succeeded": Boolean +"TestRun"."tests_total": Integer +"TestRun"."tests_failed": Integer +"CoverageReport"."coverage_percent": Integer +"Release"."semver": String +"Release"."is_signed_off": Boolean +"Release"."is_published": Boolean +"Deployment"."deploy_succeeded": Boolean +"Incident"."incident_severity": Integer +"Incident"."time_to_resolve_min": Integer +"Incident"."is_resolved": Boolean +"Incident"."has_postmortem": Boolean +"Repository" -> "Commit": contains_commit +"Commit" -> "Person": authored_by +"PullRequest" -> "Commit": proposes +"PullRequest" -> "Branch": targets_branch +"PullRequest" -> "Reviewer": reviewed_by +"CodeReview" -> "PullRequest": reviews +"Build" -> "Commit": builds_from +"Build" -> "BuildArtifact": produces +"TestRun" -> "Build": validates +"SecurityScan" -> "BuildArtifact": scans +"Release" -> "BuildArtifact": packages_artifact +"Release" -> "SoftwareBillOfMaterials": has_sbom +"Deployment" -> "Release": deploys +"Deployment" -> "Environment": deploys_to +"Rollback" -> "Deployment": rolls_back +"Incident" -> "Deployment": caused_by +"Incident" -> "IncidentCommander": owned_by +"IncidentResponse" -> "Incident": responds_to +"Incident" -> "PostmortemReport": documented_in +"Service" -> "Environment": runs_on +# WARNING: The following axioms could not be mapped to field constraints: +# forall p (PullRequest(p) and is_merged = True implies ci_passed = True) +# forall p (PullRequest(p) and is_merged = True implies gte(approval_count, 2)) +# forall b (Build(b) and build_succeeded = True implies exists t (TestRun(t))) +# forall r (Release(r) and is_published = True implies is_signed_off = True) +# forall d (forall r (Deployment(d) and deploys(d, r) implies Release(r))) +# forall r (Release(r) and is_signed_off = True implies exists s (has_sbom(r, s))) +# forall i (Incident(i) and is_resolved = False implies exists c (owned_by(i, c))) +# forall i (Incident(i) and incident_severity = 1 and is_resolved = True implies has_postmortem = True) +# forall x (not Commit(x) and Build(x)) +# forall x (not Release(x) and Deployment(x)) diff --git a/examples/domain_software_delivery.d2.svg b/examples/domain_software_delivery.d2.svg new file mode 100644 index 0000000..f1ac325 --- /dev/null +++ b/examples/domain_software_delivery.d2.svg @@ -0,0 +1,121 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectOccurrentProcessRoleFunctionInformationContentEntityPersonTeamDeveloperReviewerCodeOwnerReleaseManagerOnCallEngineerIncidentCommanderSourceArtifactRepositoryMonorepoRepositoryBranch+is_protectedBooleanProtectedBranchFeatureBranchCommit+commit_hashStringSignedCommitMergeCommitTagCodeChangePullRequest+approval_countInteger+lines_changedInteger+is_mergedBoolean+ci_passedBooleanDraftPullRequestMergedPullRequestReviewCommentBuildArtifactContainerImagePackageSoftwareBillOfMaterialsRelease+semverString+is_signed_offBoolean+is_publishedBooleanCandidateReleaseStableReleaseHotfixReleaseChangelogTestReportCoverageReport+coverage_percentIntegerPostmortemReportEnvironmentDevelopmentEnvironmentStagingEnvironmentProductionEnvironmentBuildAgentServiceFeatureFlagDeliveryProcessCodeReviewBuild+build_duration_sInteger+build_succeededBooleanFailedBuildTestRun+tests_totalInteger+tests_failedIntegerUnitTestRunIntegrationTestRunSecurityScanDeployment+deploy_succeededBooleanProductionDeploymentCanaryDeploymentRollbackIncidentResponseIncident+incident_severityInteger+time_to_resolve_minInteger+is_resolvedBoolean+has_postmortemBooleanProductionIncidentSecurityIncidentAlert contains_commitauthored_byproposestargets_branchreviewed_byreviewsbuilds_fromproducesvalidatesscanspackages_artifacthas_sbomdeploysdeploys_torolls_backcaused_byowned_byresponds_todocumented_inruns_on + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_software_delivery.logic b/examples/domain_software_delivery.logic new file mode 100644 index 0000000..602e8b6 --- /dev/null +++ b/examples/domain_software_delivery.logic @@ -0,0 +1,192 @@ +; Domain: Software delivery (source control through production incidents). +; Models repositories, commits, pull requests, reviews, builds, tests, releases, +; deployments and incidents, with a condensed BFO upper level. +; Axioms enforce delivery integrity: merged changes are reviewed and built, +; releases are signed off, production deployments need a passing release, +; incidents get severity and ownership, and artifacts/processes stay disjoint. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Agents and roles --- +(def-concept Person Object) +(def-concept Team Object) +(def-concept Developer Role) +(def-concept Reviewer Role) +(def-concept CodeOwner Reviewer) +(def-concept ReleaseManager Role) +(def-concept OnCallEngineer Role) +(def-concept IncidentCommander Role) + +; --- Source control artifacts --- +(def-concept SourceArtifact InformationContentEntity) +(def-concept Repository SourceArtifact) +(def-concept MonorepoRepository Repository) +(def-concept Branch SourceArtifact) +(def-concept ProtectedBranch Branch) +(def-concept FeatureBranch Branch) +(def-concept Commit SourceArtifact) +(def-concept SignedCommit Commit) +(def-concept MergeCommit Commit) +(def-concept Tag SourceArtifact) +(def-concept CodeChange SourceArtifact) +(def-concept PullRequest CodeChange) +(def-concept DraftPullRequest PullRequest) +(def-concept MergedPullRequest PullRequest) +(def-concept ReviewComment SourceArtifact) + +; --- Delivery artifacts --- +(def-concept BuildArtifact InformationContentEntity) +(def-concept ContainerImage BuildArtifact) +(def-concept Package BuildArtifact) +(def-concept SoftwareBillOfMaterials InformationContentEntity) +(def-concept Release InformationContentEntity) +(def-concept CandidateRelease Release) +(def-concept StableRelease Release) +(def-concept HotfixRelease Release) +(def-concept Changelog InformationContentEntity) +(def-concept TestReport InformationContentEntity) +(def-concept CoverageReport TestReport) +(def-concept PostmortemReport InformationContentEntity) + +; --- Environments and infrastructure --- +(def-concept Environment Object) +(def-concept DevelopmentEnvironment Environment) +(def-concept StagingEnvironment Environment) +(def-concept ProductionEnvironment Environment) +(def-concept BuildAgent Object) +(def-concept Service Object) +(def-concept FeatureFlag InformationContentEntity) + +; --- Processes --- +(def-concept DeliveryProcess Process) +(def-concept CodeReview DeliveryProcess) +(def-concept Build DeliveryProcess) +(def-concept FailedBuild Build) +(def-concept TestRun DeliveryProcess) +(def-concept UnitTestRun TestRun) +(def-concept IntegrationTestRun TestRun) +(def-concept SecurityScan DeliveryProcess) +(def-concept Deployment DeliveryProcess) +(def-concept ProductionDeployment Deployment) +(def-concept CanaryDeployment ProductionDeployment) +(def-concept Rollback DeliveryProcess) +(def-concept IncidentResponse DeliveryProcess) + +; --- Incidents --- +(def-concept Incident Occurrent) +(def-concept ProductionIncident Incident) +(def-concept SecurityIncident Incident) +(def-concept Alert InformationContentEntity) + +; --- Properties --- +(def-property commit_hash Commit String :cardinality 1..1) +(def-property approval_count PullRequest Integer) +(def-property lines_changed PullRequest Integer) +(def-property is_merged PullRequest Boolean) +(def-property ci_passed PullRequest Boolean) +(def-property is_protected Branch Boolean) +(def-property build_duration_s Build Integer) +(def-property build_succeeded Build Boolean) +(def-property tests_total TestRun Integer) +(def-property tests_failed TestRun Integer) +(def-property coverage_percent CoverageReport Integer) +(def-property semver Release String :cardinality 1..1) +(def-property is_signed_off Release Boolean) +(def-property is_published Release Boolean) +(def-property deploy_succeeded Deployment Boolean) +(def-property incident_severity Incident Integer) +(def-property time_to_resolve_min Incident Integer) +(def-property is_resolved Incident Boolean) +(def-property has_postmortem Incident Boolean) + +; --- Relations --- +(def-relation contains_commit Repository Commit :cardinality 0..*) +(def-relation authored_by Commit Person) +(def-relation proposes PullRequest Commit :cardinality 1..*) +(def-relation targets_branch PullRequest Branch) +(def-relation reviewed_by PullRequest Reviewer :cardinality 0..*) +(def-relation reviews CodeReview PullRequest) +(def-relation builds_from Build Commit) +(def-relation produces Build BuildArtifact :cardinality 0..*) +(def-relation validates TestRun Build) +(def-relation scans SecurityScan BuildArtifact) +(def-relation packages_artifact Release BuildArtifact :cardinality 1..*) +(def-relation has_sbom Release SoftwareBillOfMaterials) +(def-relation deploys Deployment Release) +(def-relation deploys_to Deployment Environment) +(def-relation rolls_back Rollback Deployment) +(def-relation caused_by Incident Deployment) +(def-relation owned_by Incident IncidentCommander) +(def-relation responds_to IncidentResponse Incident) +(def-relation documented_in Incident PostmortemReport) +(def-relation runs_on Service Environment) + +; --- Axioms --- +; 1. Integrity: a merged pull request must have passed CI. +(forall (p) + (implies (and (PullRequest p) (eq is_merged True)) + (eq ci_passed True))) + +; 2. Review policy: a merged pull request needs at least two approvals. +(forall (p) + (implies (and (PullRequest p) (eq is_merged True)) + (gte approval_count 2))) + +; 3. Change size: pull requests are bounded to keep review effective. +(forall (p) + (implies (PullRequest p) + (and (gte lines_changed 0) (lte lines_changed 5000)))) + +; 4. Build integrity: a build marked succeeded is validated by some test run. +(forall (b) + (implies (and (Build b) (eq build_succeeded True)) + (exists (t) (TestRun t)))) + +; 5. Test consistency: test counts are never negative. +(forall (t) + (implies (TestRun t) + (and (gte tests_failed 0) (gte tests_total 0)))) + +; 6. Release gate: a published release must be signed off. +(forall (r) + (implies (and (Release r) (eq is_published True)) + (eq is_signed_off True))) + +; 7. Production safety: anything deployed to an environment is a release. +(forall (d r) + (implies (and (Deployment d) (deploys d r)) + (Release r))) + +; 8. Traceability: a signed-off release carries a software bill of materials. +(forall (r) + (implies (and (Release r) (eq is_signed_off True)) + (exists (s) (has_sbom r s)))) + +; 9. Incident severity range: 1 (critical) to 4 (minor). +(forall (i) + (implies (Incident i) + (and (gte incident_severity 1) (lte incident_severity 4)))) + +; 10. Ownership: an unresolved incident must be owned by an incident commander. +(forall (i) + (implies (and (Incident i) (eq is_resolved False)) + (exists (c) (owned_by i c)))) + +; 11. Learning: a resolved severity-1 incident requires a documented postmortem. +(forall (i) + (implies (and (Incident i) (eq incident_severity 1) (eq is_resolved True)) + (eq has_postmortem True))) + +; 12. Disjointness: a source commit is never a process, a release is never a build. +(forall (x) (not (and (Commit x) (Build x)))) +(forall (x) (not (and (Release x) (Deployment x)))) diff --git a/examples/domain_software_delivery.mmd b/examples/domain_software_delivery.mmd new file mode 100644 index 0000000..a48b899 --- /dev/null +++ b/examples/domain_software_delivery.mmd @@ -0,0 +1,189 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class InformationContentEntity["InformationContentEntity"] + class Person["Person"] + class Team["Team"] + class Developer["Developer"] + class Reviewer["Reviewer"] + class CodeOwner["CodeOwner"] + class ReleaseManager["ReleaseManager"] + class OnCallEngineer["OnCallEngineer"] + class IncidentCommander["IncidentCommander"] + class SourceArtifact["SourceArtifact"] + class Repository["Repository"] + class MonorepoRepository["MonorepoRepository"] + class Branch["Branch"] + class ProtectedBranch["ProtectedBranch"] + class FeatureBranch["FeatureBranch"] + class Commit["Commit"] + class SignedCommit["SignedCommit"] + class MergeCommit["MergeCommit"] + class Tag["Tag"] + class CodeChange["CodeChange"] + class PullRequest["PullRequest"] + class DraftPullRequest["DraftPullRequest"] + class MergedPullRequest["MergedPullRequest"] + class ReviewComment["ReviewComment"] + class BuildArtifact["BuildArtifact"] + class ContainerImage["ContainerImage"] + class Package["Package"] + class SoftwareBillOfMaterials["SoftwareBillOfMaterials"] + class Release["Release"] + class CandidateRelease["CandidateRelease"] + class StableRelease["StableRelease"] + class HotfixRelease["HotfixRelease"] + class Changelog["Changelog"] + class TestReport["TestReport"] + class CoverageReport["CoverageReport"] + class PostmortemReport["PostmortemReport"] + class Environment["Environment"] + class DevelopmentEnvironment["DevelopmentEnvironment"] + class StagingEnvironment["StagingEnvironment"] + class ProductionEnvironment["ProductionEnvironment"] + class BuildAgent["BuildAgent"] + class Service["Service"] + class FeatureFlag["FeatureFlag"] + class DeliveryProcess["DeliveryProcess"] + class CodeReview["CodeReview"] + class Build["Build"] + class FailedBuild["FailedBuild"] + class TestRun["TestRun"] + class UnitTestRun["UnitTestRun"] + class IntegrationTestRun["IntegrationTestRun"] + class SecurityScan["SecurityScan"] + class Deployment["Deployment"] + class ProductionDeployment["ProductionDeployment"] + class CanaryDeployment["CanaryDeployment"] + class Rollback["Rollback"] + class IncidentResponse["IncidentResponse"] + class Incident["Incident"] + class ProductionIncident["ProductionIncident"] + class SecurityIncident["SecurityIncident"] + class Alert["Alert"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- InformationContentEntity + Object <|-- Person + Object <|-- Team + Role <|-- Developer + Role <|-- Reviewer + Reviewer <|-- CodeOwner + Role <|-- ReleaseManager + Role <|-- OnCallEngineer + Role <|-- IncidentCommander + InformationContentEntity <|-- SourceArtifact + SourceArtifact <|-- Repository + Repository <|-- MonorepoRepository + SourceArtifact <|-- Branch + Branch <|-- ProtectedBranch + Branch <|-- FeatureBranch + SourceArtifact <|-- Commit + Commit <|-- SignedCommit + Commit <|-- MergeCommit + SourceArtifact <|-- Tag + SourceArtifact <|-- CodeChange + CodeChange <|-- PullRequest + PullRequest <|-- DraftPullRequest + PullRequest <|-- MergedPullRequest + SourceArtifact <|-- ReviewComment + InformationContentEntity <|-- BuildArtifact + BuildArtifact <|-- ContainerImage + BuildArtifact <|-- Package + InformationContentEntity <|-- SoftwareBillOfMaterials + InformationContentEntity <|-- Release + Release <|-- CandidateRelease + Release <|-- StableRelease + Release <|-- HotfixRelease + InformationContentEntity <|-- Changelog + InformationContentEntity <|-- TestReport + TestReport <|-- CoverageReport + InformationContentEntity <|-- PostmortemReport + Object <|-- Environment + Environment <|-- DevelopmentEnvironment + Environment <|-- StagingEnvironment + Environment <|-- ProductionEnvironment + Object <|-- BuildAgent + Object <|-- Service + InformationContentEntity <|-- FeatureFlag + Process <|-- DeliveryProcess + DeliveryProcess <|-- CodeReview + DeliveryProcess <|-- Build + Build <|-- FailedBuild + DeliveryProcess <|-- TestRun + TestRun <|-- UnitTestRun + TestRun <|-- IntegrationTestRun + DeliveryProcess <|-- SecurityScan + DeliveryProcess <|-- Deployment + Deployment <|-- ProductionDeployment + ProductionDeployment <|-- CanaryDeployment + DeliveryProcess <|-- Rollback + DeliveryProcess <|-- IncidentResponse + Occurrent <|-- Incident + Incident <|-- ProductionIncident + Incident <|-- SecurityIncident + InformationContentEntity <|-- Alert + Commit : +String commit_hash + PullRequest : +Integer approval_count + PullRequest : +Integer lines_changed + PullRequest : +Boolean is_merged + PullRequest : +Boolean ci_passed + Branch : +Boolean is_protected + Build : +Integer build_duration_s + Build : +Boolean build_succeeded + TestRun : +Integer tests_total + TestRun : +Integer tests_failed + CoverageReport : +Integer coverage_percent + Release : +String semver + Release : +Boolean is_signed_off + Release : +Boolean is_published + Deployment : +Boolean deploy_succeeded + Incident : +Integer incident_severity + Incident : +Integer time_to_resolve_min + Incident : +Boolean is_resolved + Incident : +Boolean has_postmortem + Repository --> Commit : contains_commit + Commit --> Person : authored_by + PullRequest --> Commit : proposes + PullRequest --> Branch : targets_branch + PullRequest --> Reviewer : reviewed_by + CodeReview --> PullRequest : reviews + Build --> Commit : builds_from + Build --> BuildArtifact : produces + TestRun --> Build : validates + SecurityScan --> BuildArtifact : scans + Release --> BuildArtifact : packages_artifact + Release --> SoftwareBillOfMaterials : has_sbom + Deployment --> Release : deploys + Deployment --> Environment : deploys_to + Rollback --> Deployment : rolls_back + Incident --> Deployment : caused_by + Incident --> IncidentCommander : owned_by + IncidentResponse --> Incident : responds_to + Incident --> PostmortemReport : documented_in + Service --> Environment : runs_on + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall p (PullRequest(p) and is_merged = True implies ci_passed = True) +%% forall p (PullRequest(p) and is_merged = True implies gte(approval_count, 2)) +%% forall b (Build(b) and build_succeeded = True implies exists t (TestRun(t))) +%% forall r (Release(r) and is_published = True implies is_signed_off = True) +%% forall d (forall r (Deployment(d) and deploys(d, r) implies Release(r))) +%% forall r (Release(r) and is_signed_off = True implies exists s (has_sbom(r, s))) +%% forall i (Incident(i) and is_resolved = False implies exists c (owned_by(i, c))) +%% forall i (Incident(i) and incident_severity = 1 and is_resolved = True implies has_postmortem = True) +%% forall x (not Commit(x) and Build(x)) +%% forall x (not Release(x) and Deployment(x)) diff --git a/examples/domain_systems_engineering.cypher b/examples/domain_systems_engineering.cypher new file mode 100644 index 0000000..e387e26 --- /dev/null +++ b/examples/domain_systems_engineering.cypher @@ -0,0 +1,310 @@ +// Nodes and Hierarchy +MERGE (n:OntologyClass {name: 'Entity'}); +MERGE (n:OntologyClass {name: 'Continuant'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IndependentContinuant'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MaterialEntity'}) +MERGE (p:OntologyClass {name: 'IndependentContinuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Object'}) +MERGE (p:OntologyClass {name: 'MaterialEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Occurrent'}) +MERGE (p:OntologyClass {name: 'Entity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Process'}) +MERGE (p:OntologyClass {name: 'Occurrent'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Role'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Function'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InformationContentEntity'}) +MERGE (p:OntologyClass {name: 'Continuant'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Requirement'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'StakeholderNeed'}) +MERGE (p:OntologyClass {name: 'Requirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SystemRequirement'}) +MERGE (p:OntologyClass {name: 'Requirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FunctionalRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'PerformanceRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InterfaceRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SafetyRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SecurityRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ReliabilityRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConstraintRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DerivedRequirement'}) +MERGE (p:OntologyClass {name: 'SystemRequirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ComponentRequirement'}) +MERGE (p:OntologyClass {name: 'Requirement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AcceptanceCriterion'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SystemElement'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'System'}) +MERGE (p:OntologyClass {name: 'SystemElement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Subsystem'}) +MERGE (p:OntologyClass {name: 'SystemElement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Assembly'}) +MERGE (p:OntologyClass {name: 'SystemElement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Component'}) +MERGE (p:OntologyClass {name: 'SystemElement'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'HardwareComponent'}) +MERGE (p:OntologyClass {name: 'Component'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SoftwareComponent'}) +MERGE (p:OntologyClass {name: 'Component'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'COTSComponent'}) +MERGE (p:OntologyClass {name: 'Component'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Interface'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ElectricalInterface'}) +MERGE (p:OntologyClass {name: 'Interface'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'MechanicalInterface'}) +MERGE (p:OntologyClass {name: 'Interface'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DataInterface'}) +MERGE (p:OntologyClass {name: 'Interface'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Port'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DesignArtifact'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ArchitectureModel'}) +MERGE (p:OntologyClass {name: 'DesignArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'InterfaceControlDocument'}) +MERGE (p:OntologyClass {name: 'DesignArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Specification'}) +MERGE (p:OntologyClass {name: 'DesignArtifact'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Baseline'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'FunctionalBaseline'}) +MERGE (p:OntologyClass {name: 'Baseline'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'AllocatedBaseline'}) +MERGE (p:OntologyClass {name: 'Baseline'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductBaseline'}) +MERGE (p:OntologyClass {name: 'Baseline'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VerificationActivity'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Inspection'}) +MERGE (p:OntologyClass {name: 'VerificationActivity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Analysis'}) +MERGE (p:OntologyClass {name: 'VerificationActivity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Demonstration'}) +MERGE (p:OntologyClass {name: 'VerificationActivity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Test'}) +MERGE (p:OntologyClass {name: 'VerificationActivity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'UnitTest'}) +MERGE (p:OntologyClass {name: 'Test'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'IntegrationTest'}) +MERGE (p:OntologyClass {name: 'Test'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SystemQualificationTest'}) +MERGE (p:OntologyClass {name: 'Test'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ValidationActivity'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VerificationEvidence'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TestProcedure'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TestResult'}) +MERGE (p:OntologyClass {name: 'VerificationEvidence'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Nonconformance'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChangeRequest'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'EngineeringChangeProposal'}) +MERGE (p:OntologyClass {name: 'ChangeRequest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'WaiverRequest'}) +MERGE (p:OntologyClass {name: 'ChangeRequest'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChangeBoard'}) +MERGE (p:OntologyClass {name: 'Object'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChangeImpactAssessment'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ChangeImplementation'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'Stakeholder'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'SystemsEngineer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'RequirementOwner'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'VerificationEngineer'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConfigurationManager'}) +MERGE (p:OntologyClass {name: 'Role'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'LifecycleStage'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ConceptStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DevelopmentStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'ProductionStage'}) +MERGE (p:OntologyClass {name: 'LifecycleStage'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'DesignReview'}) +MERGE (p:OntologyClass {name: 'Process'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +MERGE (n:OntologyClass {name: 'TraceabilityLink'}) +MERGE (p:OntologyClass {name: 'InformationContentEntity'}) +MERGE (n)-[:SUBCLASS_OF]->(p); +// Relationships +MERGE (s:OntologyClass {name: 'Requirement'}) +MERGE (t:OntologyClass {name: 'Requirement'}) +MERGE (s)-[:RELATION {name: 'derives_from'}]->(t); +MERGE (s:OntologyClass {name: 'SystemElement'}) +MERGE (t:OntologyClass {name: 'Requirement'}) +MERGE (s)-[:RELATION {name: 'satisfies'}]->(t); +MERGE (s:OntologyClass {name: 'Requirement'}) +MERGE (t:OntologyClass {name: 'SystemElement'}) +MERGE (s)-[:RELATION {name: 'allocated_to'}]->(t); +MERGE (s:OntologyClass {name: 'Requirement'}) +MERGE (t:OntologyClass {name: 'VerificationActivity'}) +MERGE (s)-[:RELATION {name: 'verified_by'}]->(t); +MERGE (s:OntologyClass {name: 'VerificationActivity'}) +MERGE (t:OntologyClass {name: 'VerificationEvidence'}) +MERGE (s)-[:RELATION {name: 'produces_evidence'}]->(t); +MERGE (s:OntologyClass {name: 'VerificationActivity'}) +MERGE (t:OntologyClass {name: 'TestProcedure'}) +MERGE (s)-[:RELATION {name: 'uses_procedure'}]->(t); +MERGE (s:OntologyClass {name: 'SystemElement'}) +MERGE (t:OntologyClass {name: 'SystemElement'}) +MERGE (s)-[:RELATION {name: 'part_of'}]->(t); +MERGE (s:OntologyClass {name: 'Interface'}) +MERGE (t:OntologyClass {name: 'Port'}) +MERGE (s)-[:RELATION {name: 'connects'}]->(t); +MERGE (s:OntologyClass {name: 'SystemElement'}) +MERGE (t:OntologyClass {name: 'Port'}) +MERGE (s)-[:RELATION {name: 'exposes'}]->(t); +MERGE (s:OntologyClass {name: 'Interface'}) +MERGE (t:OntologyClass {name: 'InterfaceControlDocument'}) +MERGE (s)-[:RELATION {name: 'defined_in'}]->(t); +MERGE (s:OntologyClass {name: 'InterfaceRequirement'}) +MERGE (t:OntologyClass {name: 'Interface'}) +MERGE (s)-[:RELATION {name: 'specifies_interface'}]->(t); +MERGE (s:OntologyClass {name: 'Requirement'}) +MERGE (t:OntologyClass {name: 'RequirementOwner'}) +MERGE (s)-[:RELATION {name: 'owned_by'}]->(t); +MERGE (s:OntologyClass {name: 'ChangeRequest'}) +MERGE (t:OntologyClass {name: 'Requirement'}) +MERGE (s)-[:RELATION {name: 'modifies'}]->(t); +MERGE (s:OntologyClass {name: 'ChangeRequest'}) +MERGE (t:OntologyClass {name: 'DesignArtifact'}) +MERGE (s)-[:RELATION {name: 'modifies_design'}]->(t); +MERGE (s:OntologyClass {name: 'ChangeRequest'}) +MERGE (t:OntologyClass {name: 'ChangeImpactAssessment'}) +MERGE (s)-[:RELATION {name: 'assessed_by'}]->(t); +MERGE (s:OntologyClass {name: 'ChangeRequest'}) +MERGE (t:OntologyClass {name: 'ChangeBoard'}) +MERGE (s)-[:RELATION {name: 'decided_by'}]->(t); +MERGE (s:OntologyClass {name: 'TraceabilityLink'}) +MERGE (t:OntologyClass {name: 'Requirement'}) +MERGE (s)-[:RELATION {name: 'traces_from'}]->(t); +MERGE (s:OntologyClass {name: 'TraceabilityLink'}) +MERGE (t:OntologyClass {name: 'SystemElement'}) +MERGE (s)-[:RELATION {name: 'traces_to'}]->(t); +MERGE (s:OntologyClass {name: 'Requirement'}) +MERGE (t:OntologyClass {name: 'DesignReview'}) +MERGE (s)-[:RELATION {name: 'reviewed_in'}]->(t); +MERGE (s:OntologyClass {name: 'Nonconformance'}) +MERGE (t:OntologyClass {name: 'VerificationActivity'}) +MERGE (s)-[:RELATION {name: 'raised_by'}]->(t); +// Axiom Validations +// Axiom validation: Requirement req_priority gte 1 +MATCH (n:`Requirement`) WHERE NOT (n.`req_priority` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Requirement req_priority lte 5 +MATCH (n:`Requirement`) WHERE NOT (n.`req_priority` <= 5) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SafetyRequirement safety_integrity_level gte 1 +MATCH (n:`SafetyRequirement`) WHERE NOT (n.`safety_integrity_level` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SafetyRequirement safety_integrity_level lte 4 +MATCH (n:`SafetyRequirement`) WHERE NOT (n.`safety_integrity_level` <= 4) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SystemElement mass_kg gte 0 +MATCH (n:`SystemElement`) WHERE NOT (n.`mass_kg` >= 0) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: SystemElement mass_kg lte 1000000 +MATCH (n:`SystemElement`) WHERE NOT (n.`mass_kg` <= 1000000) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Component tech_readiness_level gte 1 +MATCH (n:`Component`) WHERE NOT (n.`tech_readiness_level` >= 1) RETURN elementId(n) AS invalid_node_id; +// Axiom validation: Component tech_readiness_level lte 9 +MATCH (n:`Component`) WHERE NOT (n.`tech_readiness_level` <= 9) RETURN elementId(n) AS invalid_node_id; + +// WARNING: The following axioms could not be mapped to field constraints: +// forall r (Requirement(r) and is_approved = True implies is_allocated = True) +// forall r (Requirement(r) and is_approved = True implies is_testable = True) +// forall r (Requirement(r) and is_verified = True implies exists v (verified_by(r, v))) +// forall r (SafetyRequirement(r) and is_approved = True implies hazard_analysis_done = True) +// forall c (forall d (ChangeRequest(c) and modifies_design(c, d) implies change_approved = True)) +// forall c (ChangeRequest(c) and change_approved = True implies impact_assessed = True) +// forall i (Interface(i) implies exists p (connects(i, p))) +// forall x (not Requirement(x) and SystemElement(x)) +// forall x (not VerificationActivity(x) and ChangeImplementation(x)) diff --git a/examples/domain_systems_engineering.d2 b/examples/domain_systems_engineering.d2 new file mode 100644 index 0000000..11999f9 --- /dev/null +++ b/examples/domain_systems_engineering.d2 @@ -0,0 +1,197 @@ +"Entity": { shape: class } +"Continuant": { shape: class } +"IndependentContinuant": { shape: class } +"MaterialEntity": { shape: class } +"Object": { shape: class } +"Occurrent": { shape: class } +"Process": { shape: class } +"Role": { shape: class } +"Function": { shape: class } +"InformationContentEntity": { shape: class } +"Requirement": { shape: class } +"StakeholderNeed": { shape: class } +"SystemRequirement": { shape: class } +"FunctionalRequirement": { shape: class } +"PerformanceRequirement": { shape: class } +"InterfaceRequirement": { shape: class } +"SafetyRequirement": { shape: class } +"SecurityRequirement": { shape: class } +"ReliabilityRequirement": { shape: class } +"ConstraintRequirement": { shape: class } +"DerivedRequirement": { shape: class } +"ComponentRequirement": { shape: class } +"AcceptanceCriterion": { shape: class } +"SystemElement": { shape: class } +"System": { shape: class } +"Subsystem": { shape: class } +"Assembly": { shape: class } +"Component": { shape: class } +"HardwareComponent": { shape: class } +"SoftwareComponent": { shape: class } +"COTSComponent": { shape: class } +"Interface": { shape: class } +"ElectricalInterface": { shape: class } +"MechanicalInterface": { shape: class } +"DataInterface": { shape: class } +"Port": { shape: class } +"DesignArtifact": { shape: class } +"ArchitectureModel": { shape: class } +"InterfaceControlDocument": { shape: class } +"Specification": { shape: class } +"Baseline": { shape: class } +"FunctionalBaseline": { shape: class } +"AllocatedBaseline": { shape: class } +"ProductBaseline": { shape: class } +"VerificationActivity": { shape: class } +"Inspection": { shape: class } +"Analysis": { shape: class } +"Demonstration": { shape: class } +"Test": { shape: class } +"UnitTest": { shape: class } +"IntegrationTest": { shape: class } +"SystemQualificationTest": { shape: class } +"ValidationActivity": { shape: class } +"VerificationEvidence": { shape: class } +"TestProcedure": { shape: class } +"TestResult": { shape: class } +"Nonconformance": { shape: class } +"ChangeRequest": { shape: class } +"EngineeringChangeProposal": { shape: class } +"WaiverRequest": { shape: class } +"ChangeBoard": { shape: class } +"ChangeImpactAssessment": { shape: class } +"ChangeImplementation": { shape: class } +"Stakeholder": { shape: class } +"SystemsEngineer": { shape: class } +"RequirementOwner": { shape: class } +"VerificationEngineer": { shape: class } +"ConfigurationManager": { shape: class } +"LifecycleStage": { shape: class } +"ConceptStage": { shape: class } +"DevelopmentStage": { shape: class } +"ProductionStage": { shape: class } +"DesignReview": { shape: class } +"TraceabilityLink": { shape: class } + +"Continuant" -> "Entity" +"IndependentContinuant" -> "Continuant" +"MaterialEntity" -> "IndependentContinuant" +"Object" -> "MaterialEntity" +"Occurrent" -> "Entity" +"Process" -> "Occurrent" +"Role" -> "Continuant" +"Function" -> "Continuant" +"InformationContentEntity" -> "Continuant" +"Requirement" -> "InformationContentEntity" +"StakeholderNeed" -> "Requirement" +"SystemRequirement" -> "Requirement" +"FunctionalRequirement" -> "SystemRequirement" +"PerformanceRequirement" -> "SystemRequirement" +"InterfaceRequirement" -> "SystemRequirement" +"SafetyRequirement" -> "SystemRequirement" +"SecurityRequirement" -> "SystemRequirement" +"ReliabilityRequirement" -> "SystemRequirement" +"ConstraintRequirement" -> "SystemRequirement" +"DerivedRequirement" -> "SystemRequirement" +"ComponentRequirement" -> "Requirement" +"AcceptanceCriterion" -> "InformationContentEntity" +"SystemElement" -> "Object" +"System" -> "SystemElement" +"Subsystem" -> "SystemElement" +"Assembly" -> "SystemElement" +"Component" -> "SystemElement" +"HardwareComponent" -> "Component" +"SoftwareComponent" -> "Component" +"COTSComponent" -> "Component" +"Interface" -> "Object" +"ElectricalInterface" -> "Interface" +"MechanicalInterface" -> "Interface" +"DataInterface" -> "Interface" +"Port" -> "Object" +"DesignArtifact" -> "InformationContentEntity" +"ArchitectureModel" -> "DesignArtifact" +"InterfaceControlDocument" -> "DesignArtifact" +"Specification" -> "DesignArtifact" +"Baseline" -> "InformationContentEntity" +"FunctionalBaseline" -> "Baseline" +"AllocatedBaseline" -> "Baseline" +"ProductBaseline" -> "Baseline" +"VerificationActivity" -> "Process" +"Inspection" -> "VerificationActivity" +"Analysis" -> "VerificationActivity" +"Demonstration" -> "VerificationActivity" +"Test" -> "VerificationActivity" +"UnitTest" -> "Test" +"IntegrationTest" -> "Test" +"SystemQualificationTest" -> "Test" +"ValidationActivity" -> "Process" +"VerificationEvidence" -> "InformationContentEntity" +"TestProcedure" -> "InformationContentEntity" +"TestResult" -> "VerificationEvidence" +"Nonconformance" -> "InformationContentEntity" +"ChangeRequest" -> "InformationContentEntity" +"EngineeringChangeProposal" -> "ChangeRequest" +"WaiverRequest" -> "ChangeRequest" +"ChangeBoard" -> "Object" +"ChangeImpactAssessment" -> "InformationContentEntity" +"ChangeImplementation" -> "Process" +"Stakeholder" -> "Role" +"SystemsEngineer" -> "Role" +"RequirementOwner" -> "Role" +"VerificationEngineer" -> "Role" +"ConfigurationManager" -> "Role" +"LifecycleStage" -> "Process" +"ConceptStage" -> "LifecycleStage" +"DevelopmentStage" -> "LifecycleStage" +"ProductionStage" -> "LifecycleStage" +"DesignReview" -> "Process" +"TraceabilityLink" -> "InformationContentEntity" +"Requirement"."req_id": String +"Requirement"."req_priority": Integer +"Requirement"."is_approved": Boolean +"Requirement"."is_verified": Boolean +"Requirement"."is_allocated": Boolean +"Requirement"."is_testable": Boolean +"SafetyRequirement"."safety_integrity_level": Integer +"SafetyRequirement"."hazard_analysis_done": Boolean +"SystemElement"."mass_kg": Integer +"SystemElement"."mass_budget_kg": Integer +"SystemElement"."power_draw_w": Integer +"Component"."tech_readiness_level": Integer +"DesignArtifact"."is_baselined": Boolean +"DataInterface"."interface_bandwidth_mbps": Integer +"VerificationActivity"."verification_passed": Boolean +"ChangeRequest"."change_status": String +"ChangeRequest"."change_approved": Boolean +"ChangeRequest"."impact_assessed": Boolean +"Nonconformance"."nonconformance_open": Boolean +"Requirement" -> "Requirement": derives_from +"SystemElement" -> "Requirement": satisfies +"Requirement" -> "SystemElement": allocated_to +"Requirement" -> "VerificationActivity": verified_by +"VerificationActivity" -> "VerificationEvidence": produces_evidence +"VerificationActivity" -> "TestProcedure": uses_procedure +"SystemElement" -> "SystemElement": part_of +"Interface" -> "Port": connects +"SystemElement" -> "Port": exposes +"Interface" -> "InterfaceControlDocument": defined_in +"InterfaceRequirement" -> "Interface": specifies_interface +"Requirement" -> "RequirementOwner": owned_by +"ChangeRequest" -> "Requirement": modifies +"ChangeRequest" -> "DesignArtifact": modifies_design +"ChangeRequest" -> "ChangeImpactAssessment": assessed_by +"ChangeRequest" -> "ChangeBoard": decided_by +"TraceabilityLink" -> "Requirement": traces_from +"TraceabilityLink" -> "SystemElement": traces_to +"Requirement" -> "DesignReview": reviewed_in +"Nonconformance" -> "VerificationActivity": raised_by +# WARNING: The following axioms could not be mapped to field constraints: +# forall r (Requirement(r) and is_approved = True implies is_allocated = True) +# forall r (Requirement(r) and is_approved = True implies is_testable = True) +# forall r (Requirement(r) and is_verified = True implies exists v (verified_by(r, v))) +# forall r (SafetyRequirement(r) and is_approved = True implies hazard_analysis_done = True) +# forall c (forall d (ChangeRequest(c) and modifies_design(c, d) implies change_approved = True)) +# forall c (ChangeRequest(c) and change_approved = True implies impact_assessed = True) +# forall i (Interface(i) implies exists p (connects(i, p))) +# forall x (not Requirement(x) and SystemElement(x)) +# forall x (not VerificationActivity(x) and ChangeImplementation(x)) diff --git a/examples/domain_systems_engineering.d2.svg b/examples/domain_systems_engineering.d2.svg new file mode 100644 index 0000000..3d96736 --- /dev/null +++ b/examples/domain_systems_engineering.d2.svg @@ -0,0 +1,121 @@ +EntityContinuantIndependentContinuantMaterialEntityObjectOccurrentProcessRoleFunctionInformationContentEntityRequirement+req_idString+req_priorityInteger+is_approvedBoolean+is_verifiedBoolean+is_allocatedBoolean+is_testableBooleanStakeholderNeedSystemRequirementFunctionalRequirementPerformanceRequirementInterfaceRequirementSafetyRequirement+safety_integrity_levelInteger+hazard_analysis_doneBooleanSecurityRequirementReliabilityRequirementConstraintRequirementDerivedRequirementComponentRequirementAcceptanceCriterionSystemElement+mass_kgInteger+mass_budget_kgInteger+power_draw_wIntegerSystemSubsystemAssemblyComponent+tech_readiness_levelIntegerHardwareComponentSoftwareComponentCOTSComponentInterfaceElectricalInterfaceMechanicalInterfaceDataInterface+interface_bandwidth_mbpsIntegerPortDesignArtifact+is_baselinedBooleanArchitectureModelInterfaceControlDocumentSpecificationBaselineFunctionalBaselineAllocatedBaselineProductBaselineVerificationActivity+verification_passedBooleanInspectionAnalysisDemonstrationTestUnitTestIntegrationTestSystemQualificationTestValidationActivityVerificationEvidenceTestProcedureTestResultNonconformance+nonconformance_openBooleanChangeRequest+change_statusString+change_approvedBoolean+impact_assessedBooleanEngineeringChangeProposalWaiverRequestChangeBoardChangeImpactAssessmentChangeImplementationStakeholderSystemsEngineerRequirementOwnerVerificationEngineerConfigurationManagerLifecycleStageConceptStageDevelopmentStageProductionStageDesignReviewTraceabilityLink derives_fromsatisfiesallocated_toverified_byproduces_evidenceuses_procedurepart_ofconnectsexposesdefined_inspecifies_interfaceowned_bymodifiesmodifies_designassessed_bydecided_bytraces_fromtraces_toreviewed_inraised_by + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/domain_systems_engineering.logic b/examples/domain_systems_engineering.logic new file mode 100644 index 0000000..cc8702b --- /dev/null +++ b/examples/domain_systems_engineering.logic @@ -0,0 +1,195 @@ +; Domain: Systems engineering (requirements to verification). +; Models requirements, system elements, interfaces, verification activities, +; change requests and traceability, with a condensed BFO upper level. +; Axioms enforce: every approved requirement is verified and allocated, safety +; requirements need analysis, baselined items change only via approved change +; requests, interfaces have two ends, and requirement/design artifacts stay disjoint. + +; --- BFO Upper Level (Condensed) --- +(def-concept Entity) +(def-concept Continuant Entity) +(def-concept IndependentContinuant Continuant) +(def-concept MaterialEntity IndependentContinuant) +(def-concept Object MaterialEntity) +(def-concept Occurrent Entity) +(def-concept Process Occurrent) +(def-concept Role Continuant) +(def-concept Function Continuant) +(def-concept InformationContentEntity Continuant) + +; --- Requirements --- +(def-concept Requirement InformationContentEntity) +(def-concept StakeholderNeed Requirement) +(def-concept SystemRequirement Requirement) +(def-concept FunctionalRequirement SystemRequirement) +(def-concept PerformanceRequirement SystemRequirement) +(def-concept InterfaceRequirement SystemRequirement) +(def-concept SafetyRequirement SystemRequirement) +(def-concept SecurityRequirement SystemRequirement) +(def-concept ReliabilityRequirement SystemRequirement) +(def-concept ConstraintRequirement SystemRequirement) +(def-concept DerivedRequirement SystemRequirement) +(def-concept ComponentRequirement Requirement) +(def-concept AcceptanceCriterion InformationContentEntity) + +; --- Design / system elements --- +(def-concept SystemElement Object) +(def-concept System SystemElement) +(def-concept Subsystem SystemElement) +(def-concept Assembly SystemElement) +(def-concept Component SystemElement) +(def-concept HardwareComponent Component) +(def-concept SoftwareComponent Component) +(def-concept COTSComponent Component) +(def-concept Interface Object) +(def-concept ElectricalInterface Interface) +(def-concept MechanicalInterface Interface) +(def-concept DataInterface Interface) +(def-concept Port Object) +(def-concept DesignArtifact InformationContentEntity) +(def-concept ArchitectureModel DesignArtifact) +(def-concept InterfaceControlDocument DesignArtifact) +(def-concept Specification DesignArtifact) +(def-concept Baseline InformationContentEntity) +(def-concept FunctionalBaseline Baseline) +(def-concept AllocatedBaseline Baseline) +(def-concept ProductBaseline Baseline) + +; --- Verification --- +(def-concept VerificationActivity Process) +(def-concept Inspection VerificationActivity) +(def-concept Analysis VerificationActivity) +(def-concept Demonstration VerificationActivity) +(def-concept Test VerificationActivity) +(def-concept UnitTest Test) +(def-concept IntegrationTest Test) +(def-concept SystemQualificationTest Test) +(def-concept ValidationActivity Process) +(def-concept VerificationEvidence InformationContentEntity) +(def-concept TestProcedure InformationContentEntity) +(def-concept TestResult VerificationEvidence) +(def-concept Nonconformance InformationContentEntity) + +; --- Change management --- +(def-concept ChangeRequest InformationContentEntity) +(def-concept EngineeringChangeProposal ChangeRequest) +(def-concept WaiverRequest ChangeRequest) +(def-concept ChangeBoard Object) +(def-concept ChangeImpactAssessment InformationContentEntity) +(def-concept ChangeImplementation Process) + +; --- Roles and lifecycle --- +(def-concept Stakeholder Role) +(def-concept SystemsEngineer Role) +(def-concept RequirementOwner Role) +(def-concept VerificationEngineer Role) +(def-concept ConfigurationManager Role) +(def-concept LifecycleStage Process) +(def-concept ConceptStage LifecycleStage) +(def-concept DevelopmentStage LifecycleStage) +(def-concept ProductionStage LifecycleStage) +(def-concept DesignReview Process) +(def-concept TraceabilityLink InformationContentEntity) + +; --- Properties --- +(def-property req_id Requirement String :cardinality 1..1) +(def-property req_priority Requirement Integer) +(def-property is_approved Requirement Boolean) +(def-property is_verified Requirement Boolean) +(def-property is_allocated Requirement Boolean) +(def-property is_testable Requirement Boolean) +(def-property safety_integrity_level SafetyRequirement Integer) +(def-property hazard_analysis_done SafetyRequirement Boolean) +(def-property mass_kg SystemElement Integer) +(def-property mass_budget_kg SystemElement Integer) +(def-property power_draw_w SystemElement Integer) +(def-property tech_readiness_level Component Integer) +(def-property is_baselined DesignArtifact Boolean) +(def-property interface_bandwidth_mbps DataInterface Integer) +(def-property verification_passed VerificationActivity Boolean) +(def-property change_status ChangeRequest String) +(def-property change_approved ChangeRequest Boolean) +(def-property impact_assessed ChangeRequest Boolean) +(def-property nonconformance_open Nonconformance Boolean) + +; --- Relations --- +(def-relation derives_from Requirement Requirement :cardinality 0..*) +(def-relation satisfies SystemElement Requirement :cardinality 0..*) +(def-relation allocated_to Requirement SystemElement) +(def-relation verified_by Requirement VerificationActivity :cardinality 0..*) +(def-relation produces_evidence VerificationActivity VerificationEvidence) +(def-relation uses_procedure VerificationActivity TestProcedure) +(def-relation part_of SystemElement SystemElement) +(def-relation connects Interface Port :cardinality 1..*) +(def-relation exposes SystemElement Port) +(def-relation defined_in Interface InterfaceControlDocument) +(def-relation specifies_interface InterfaceRequirement Interface) +(def-relation owned_by Requirement RequirementOwner) +(def-relation modifies ChangeRequest Requirement) +(def-relation modifies_design ChangeRequest DesignArtifact) +(def-relation assessed_by ChangeRequest ChangeImpactAssessment) +(def-relation decided_by ChangeRequest ChangeBoard) +(def-relation traces_from TraceabilityLink Requirement) +(def-relation traces_to TraceabilityLink SystemElement) +(def-relation reviewed_in Requirement DesignReview) +(def-relation raised_by Nonconformance VerificationActivity) + +; --- Axioms --- +; 1. Completeness: an approved requirement must be allocated to a system element. +(forall (r) + (implies (and (Requirement r) (eq is_approved True)) + (eq is_allocated True))) + +; 2. Verifiability: an approved requirement must be testable. +(forall (r) + (implies (and (Requirement r) (eq is_approved True)) + (eq is_testable True))) + +; 3. Verification: a verified requirement is backed by a verification activity. +(forall (r) + (implies (and (Requirement r) (eq is_verified True)) + (exists (v) (verified_by r v)))) + +; 4. Safety: a safety requirement needs a completed hazard analysis. +(forall (r) + (implies (and (SafetyRequirement r) (eq is_approved True)) + (eq hazard_analysis_done True))) + +; 5. Integrity level: safety integrity level lies between 1 and 4. +(forall (r) + (implies (SafetyRequirement r) + (and (gte safety_integrity_level 1) (lte safety_integrity_level 4)))) + +; 6. Baseline control: baselined artifacts can only be modified by approved changes. +(forall (c d) + (implies (and (ChangeRequest c) (modifies_design c d)) + (eq change_approved True))) + +; 7. Impact: an approved change must have its impact assessed. +(forall (c) + (implies (and (ChangeRequest c) (eq change_approved True)) + (eq impact_assessed True))) + +; 8. Interfaces: every interface connects at least one port (exact arity 2 is not expressible). +(forall (i) + (implies (Interface i) + (exists (p) (connects i p)))) + +; 9. Budgets: system element mass stays within its budget bounds. +(forall (e) + (implies (SystemElement e) + (and (gte mass_kg 0) (lte mass_kg 1000000)))) + +; 10. Maturity: technology readiness level is within the standard 1 to 9 scale. +(forall (c) + (implies (Component c) + (and (gte tech_readiness_level 1) (lte tech_readiness_level 9)))) + +; 11. Priority range for requirements. +(forall (r) + (implies (Requirement r) + (and (gte req_priority 1) (lte req_priority 5)))) + +; 12. Disjointness: requirements (information) are never design elements (objects). +(forall (x) (not (and (Requirement x) (SystemElement x)))) +(forall (x) (not (and (VerificationActivity x) (ChangeImplementation x)))) diff --git a/examples/domain_systems_engineering.mmd b/examples/domain_systems_engineering.mmd new file mode 100644 index 0000000..3116602 --- /dev/null +++ b/examples/domain_systems_engineering.mmd @@ -0,0 +1,198 @@ +classDiagram + class Entity["Entity"] + class Continuant["Continuant"] + class IndependentContinuant["IndependentContinuant"] + class MaterialEntity["MaterialEntity"] + class Object["Object"] + class Occurrent["Occurrent"] + class Process["Process"] + class Role["Role"] + class Function["Function"] + class InformationContentEntity["InformationContentEntity"] + class Requirement["Requirement"] + class StakeholderNeed["StakeholderNeed"] + class SystemRequirement["SystemRequirement"] + class FunctionalRequirement["FunctionalRequirement"] + class PerformanceRequirement["PerformanceRequirement"] + class InterfaceRequirement["InterfaceRequirement"] + class SafetyRequirement["SafetyRequirement"] + class SecurityRequirement["SecurityRequirement"] + class ReliabilityRequirement["ReliabilityRequirement"] + class ConstraintRequirement["ConstraintRequirement"] + class DerivedRequirement["DerivedRequirement"] + class ComponentRequirement["ComponentRequirement"] + class AcceptanceCriterion["AcceptanceCriterion"] + class SystemElement["SystemElement"] + class System["System"] + class Subsystem["Subsystem"] + class Assembly["Assembly"] + class Component["Component"] + class HardwareComponent["HardwareComponent"] + class SoftwareComponent["SoftwareComponent"] + class COTSComponent["COTSComponent"] + class Interface["Interface"] + class ElectricalInterface["ElectricalInterface"] + class MechanicalInterface["MechanicalInterface"] + class DataInterface["DataInterface"] + class Port["Port"] + class DesignArtifact["DesignArtifact"] + class ArchitectureModel["ArchitectureModel"] + class InterfaceControlDocument["InterfaceControlDocument"] + class Specification["Specification"] + class Baseline["Baseline"] + class FunctionalBaseline["FunctionalBaseline"] + class AllocatedBaseline["AllocatedBaseline"] + class ProductBaseline["ProductBaseline"] + class VerificationActivity["VerificationActivity"] + class Inspection["Inspection"] + class Analysis["Analysis"] + class Demonstration["Demonstration"] + class Test["Test"] + class UnitTest["UnitTest"] + class IntegrationTest["IntegrationTest"] + class SystemQualificationTest["SystemQualificationTest"] + class ValidationActivity["ValidationActivity"] + class VerificationEvidence["VerificationEvidence"] + class TestProcedure["TestProcedure"] + class TestResult["TestResult"] + class Nonconformance["Nonconformance"] + class ChangeRequest["ChangeRequest"] + class EngineeringChangeProposal["EngineeringChangeProposal"] + class WaiverRequest["WaiverRequest"] + class ChangeBoard["ChangeBoard"] + class ChangeImpactAssessment["ChangeImpactAssessment"] + class ChangeImplementation["ChangeImplementation"] + class Stakeholder["Stakeholder"] + class SystemsEngineer["SystemsEngineer"] + class RequirementOwner["RequirementOwner"] + class VerificationEngineer["VerificationEngineer"] + class ConfigurationManager["ConfigurationManager"] + class LifecycleStage["LifecycleStage"] + class ConceptStage["ConceptStage"] + class DevelopmentStage["DevelopmentStage"] + class ProductionStage["ProductionStage"] + class DesignReview["DesignReview"] + class TraceabilityLink["TraceabilityLink"] + Entity <|-- Continuant + Continuant <|-- IndependentContinuant + IndependentContinuant <|-- MaterialEntity + MaterialEntity <|-- Object + Entity <|-- Occurrent + Occurrent <|-- Process + Continuant <|-- Role + Continuant <|-- Function + Continuant <|-- InformationContentEntity + InformationContentEntity <|-- Requirement + Requirement <|-- StakeholderNeed + Requirement <|-- SystemRequirement + SystemRequirement <|-- FunctionalRequirement + SystemRequirement <|-- PerformanceRequirement + SystemRequirement <|-- InterfaceRequirement + SystemRequirement <|-- SafetyRequirement + SystemRequirement <|-- SecurityRequirement + SystemRequirement <|-- ReliabilityRequirement + SystemRequirement <|-- ConstraintRequirement + SystemRequirement <|-- DerivedRequirement + Requirement <|-- ComponentRequirement + InformationContentEntity <|-- AcceptanceCriterion + Object <|-- SystemElement + SystemElement <|-- System + SystemElement <|-- Subsystem + SystemElement <|-- Assembly + SystemElement <|-- Component + Component <|-- HardwareComponent + Component <|-- SoftwareComponent + Component <|-- COTSComponent + Object <|-- Interface + Interface <|-- ElectricalInterface + Interface <|-- MechanicalInterface + Interface <|-- DataInterface + Object <|-- Port + InformationContentEntity <|-- DesignArtifact + DesignArtifact <|-- ArchitectureModel + DesignArtifact <|-- InterfaceControlDocument + DesignArtifact <|-- Specification + InformationContentEntity <|-- Baseline + Baseline <|-- FunctionalBaseline + Baseline <|-- AllocatedBaseline + Baseline <|-- ProductBaseline + Process <|-- VerificationActivity + VerificationActivity <|-- Inspection + VerificationActivity <|-- Analysis + VerificationActivity <|-- Demonstration + VerificationActivity <|-- Test + Test <|-- UnitTest + Test <|-- IntegrationTest + Test <|-- SystemQualificationTest + Process <|-- ValidationActivity + InformationContentEntity <|-- VerificationEvidence + InformationContentEntity <|-- TestProcedure + VerificationEvidence <|-- TestResult + InformationContentEntity <|-- Nonconformance + InformationContentEntity <|-- ChangeRequest + ChangeRequest <|-- EngineeringChangeProposal + ChangeRequest <|-- WaiverRequest + Object <|-- ChangeBoard + InformationContentEntity <|-- ChangeImpactAssessment + Process <|-- ChangeImplementation + Role <|-- Stakeholder + Role <|-- SystemsEngineer + Role <|-- RequirementOwner + Role <|-- VerificationEngineer + Role <|-- ConfigurationManager + Process <|-- LifecycleStage + LifecycleStage <|-- ConceptStage + LifecycleStage <|-- DevelopmentStage + LifecycleStage <|-- ProductionStage + Process <|-- DesignReview + InformationContentEntity <|-- TraceabilityLink + Requirement : +String req_id + Requirement : +Integer req_priority + Requirement : +Boolean is_approved + Requirement : +Boolean is_verified + Requirement : +Boolean is_allocated + Requirement : +Boolean is_testable + SafetyRequirement : +Integer safety_integrity_level + SafetyRequirement : +Boolean hazard_analysis_done + SystemElement : +Integer mass_kg + SystemElement : +Integer mass_budget_kg + SystemElement : +Integer power_draw_w + Component : +Integer tech_readiness_level + DesignArtifact : +Boolean is_baselined + DataInterface : +Integer interface_bandwidth_mbps + VerificationActivity : +Boolean verification_passed + ChangeRequest : +String change_status + ChangeRequest : +Boolean change_approved + ChangeRequest : +Boolean impact_assessed + Nonconformance : +Boolean nonconformance_open + Requirement --> Requirement : derives_from + SystemElement --> Requirement : satisfies + Requirement --> SystemElement : allocated_to + Requirement --> VerificationActivity : verified_by + VerificationActivity --> VerificationEvidence : produces_evidence + VerificationActivity --> TestProcedure : uses_procedure + SystemElement --> SystemElement : part_of + Interface --> Port : connects + SystemElement --> Port : exposes + Interface --> InterfaceControlDocument : defined_in + InterfaceRequirement --> Interface : specifies_interface + Requirement --> RequirementOwner : owned_by + ChangeRequest --> Requirement : modifies + ChangeRequest --> DesignArtifact : modifies_design + ChangeRequest --> ChangeImpactAssessment : assessed_by + ChangeRequest --> ChangeBoard : decided_by + TraceabilityLink --> Requirement : traces_from + TraceabilityLink --> SystemElement : traces_to + Requirement --> DesignReview : reviewed_in + Nonconformance --> VerificationActivity : raised_by + +%% WARNING: The following axioms could not be mapped to field constraints: +%% forall r (Requirement(r) and is_approved = True implies is_allocated = True) +%% forall r (Requirement(r) and is_approved = True implies is_testable = True) +%% forall r (Requirement(r) and is_verified = True implies exists v (verified_by(r, v))) +%% forall r (SafetyRequirement(r) and is_approved = True implies hazard_analysis_done = True) +%% forall c (forall d (ChangeRequest(c) and modifies_design(c, d) implies change_approved = True)) +%% forall c (ChangeRequest(c) and change_approved = True implies impact_assessed = True) +%% forall i (Interface(i) implies exists p (connects(i, p))) +%% forall x (not Requirement(x) and SystemElement(x)) +%% forall x (not VerificationActivity(x) and ChangeImplementation(x)) diff --git a/ontologic.cabal b/ontologic.cabal index d6e5471..9334651 100644 --- a/ontologic.cabal +++ b/ontologic.cabal @@ -184,6 +184,7 @@ test-suite ontologic-test ComplianceGRCSpec CppSpec D2Spec + DomainExamplesSpec EcosystemSpec EcosystemUnifiedSpec ExamplesSpec diff --git a/logo.txt b/scripts/assets/logo.txt similarity index 100% rename from logo.txt rename to scripts/assets/logo.txt diff --git a/setup.sh b/setup.sh index 08e58b1..f580aca 100755 --- a/setup.sh +++ b/setup.sh @@ -3,10 +3,12 @@ set -euo pipefail # setup.sh - Install dependencies for OntoLogic -# Display the sick logo from logo.txt with Cyan/Green gradient style colors -if [ -f "logo.txt" ]; then +LOGO_FILE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/scripts/assets/logo.txt" + +# Display the logo from scripts/assets/logo.txt with Cyan/Green gradient style colors +if [ -f "$LOGO_FILE" ]; then echo -e "\033[1;36m" - cat logo.txt + cat "$LOGO_FILE" echo -e "\033[0m\033[1;32m" echo " OntoLogic: Logic as Code for the IoT Edge " echo -e "\033[0m" diff --git a/site/assets/style.css b/site/assets/style.css new file mode 100644 index 0000000..4742265 --- /dev/null +++ b/site/assets/style.css @@ -0,0 +1,82 @@ +:root{ + --bg:#03060f; --bg2:#070d1f; --panel:rgba(8,18,44,.72); + --cyan:#00e5ff; --blue:#18a0ff; --deep:#0a4a8a; + --text:#dbe9ff; --muted:#8fb0d6; --line:rgba(24,160,255,.35); + --glow:0 0 12px rgba(0,229,255,.55),0 0 32px rgba(24,160,255,.25); +} +*{box-sizing:border-box} +html{scroll-behavior:smooth} +body{ + margin:0;background:var(--bg);color:var(--text); + font:17px/1.65 "Inter",system-ui,sans-serif;overflow-x:hidden;min-width:0; + background-image: + linear-gradient(rgba(24,160,255,.07) 1px,transparent 1px), + linear-gradient(90deg,rgba(24,160,255,.07) 1px,transparent 1px), + radial-gradient(ellipse at 50% -10%,#0b2a5c 0%,transparent 60%); + background-size:48px 48px,48px 48px,100% 100%; + background-attachment:fixed; +} +h1,h2,h3,.brand{font-family:"Orbitron","Inter",sans-serif;letter-spacing:.06em;color:#fff} +h2{font-size:clamp(1.3rem,4vw,1.9rem);text-transform:uppercase;color:var(--cyan);text-shadow:var(--glow);margin:0 0 1.2rem} +h3{font-size:1.02rem;margin:0 0 .4rem;color:#fff} +a{color:var(--cyan);text-decoration:none} +a:hover,a:focus-visible{text-shadow:var(--glow);text-decoration:underline} +a:focus-visible,.btn:focus-visible{outline:2px solid var(--cyan);outline-offset:3px} +.wrap{width:min(1100px,100% - 32px);margin-inline:auto} +section{padding:3.2rem 0} +code,pre{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace} +pre{background:#020510;border:1px solid var(--line);border-radius:8px;padding:1rem;overflow-x:auto;font-size:.82rem;line-height:1.55;box-shadow:inset 0 0 24px rgba(24,160,255,.08),0 0 18px rgba(24,160,255,.12);margin:0;max-width:100%} +.skip{position:absolute;left:-999px}.skip:focus{left:8px;top:8px;background:#000;padding:.5rem;z-index:99} + +/* nav */ +header.nav{position:sticky;top:0;z-index:10;background:rgba(3,6,15,.88);backdrop-filter:blur(8px);border-bottom:1px solid var(--line);box-shadow:0 1px 18px rgba(0,229,255,.12)} +.nav .wrap{display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;padding:.7rem 0} +.brand{font-weight:800;font-size:1.15rem;color:var(--cyan);text-shadow:var(--glow);display:flex;align-items:center;gap:.5rem} +.brand:hover{text-decoration:none} +.nav ul{display:flex;gap:1.1rem;list-style:none;margin:0;padding:0;flex-wrap:wrap;font-family:"Orbitron",sans-serif;font-size:.78rem;text-transform:uppercase;letter-spacing:.1em} +.nav ul a[aria-current]{color:#fff;text-shadow:var(--glow)} + +/* hero */ +.hero{position:relative;text-align:center;padding:5rem 0 15rem;overflow:hidden;isolation:isolate} +.hero h1{font-size:clamp(2.2rem,9vw,5rem);margin:0;color:#fff;text-shadow:0 0 10px var(--cyan),0 0 40px var(--blue);text-transform:uppercase} +.hero p.lead{max-width:44rem;margin:1.2rem auto 2rem;font-size:clamp(1rem,2.6vw,1.25rem);color:var(--text)} +.floor{position:absolute;left:-50%;right:-50%;bottom:0;height:16rem;z-index:-1; + transform:perspective(420px) rotateX(62deg);transform-origin:50% 100%; + background: + linear-gradient(var(--blue) 1px,transparent 1px) 0 0/100% 48px, + linear-gradient(90deg,var(--blue) 1px,transparent 1px) 0 0/64px 100%; + opacity:.55; + -webkit-mask-image:linear-gradient(to top,#000 20%,transparent 100%);mask-image:linear-gradient(to top,#000 20%,transparent 100%); + animation:glide 3s linear infinite} +.horizon{position:absolute;left:0;right:0;bottom:15.7rem;height:2px;z-index:-1;background:linear-gradient(90deg,transparent,var(--cyan),transparent);box-shadow:0 0 24px 4px rgba(0,229,255,.6)} +@keyframes glide{to{background-position:0 48px,0 0}} +.btns{display:flex;gap:1rem;justify-content:center;flex-wrap:wrap} +.btn{display:inline-block;padding:.75rem 1.5rem;border:1px solid var(--cyan);border-radius:4px;font-family:"Orbitron",sans-serif;font-size:.8rem;letter-spacing:.12em;text-transform:uppercase;color:var(--cyan);background:rgba(0,229,255,.06);box-shadow:var(--glow)} +.btn:hover{text-decoration:none;background:rgba(0,229,255,.2);color:#fff} +.btn.primary{background:var(--cyan);color:#021018;font-weight:700} +.btn.primary:hover{background:#7ff3ff;color:#000} + +/* cards/grids */ +.grid{display:grid;gap:1rem;grid-template-columns:repeat(auto-fill,minmax(min(100%,240px),1fr))} +.card{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:1.1rem;box-shadow:0 0 18px rgba(24,160,255,.1),inset 0 0 20px rgba(0,229,255,.03);transition:border-color .2s,box-shadow .2s;min-width:0} +.card:hover{border-color:var(--cyan);box-shadow:0 0 22px rgba(0,229,255,.3)} +.card p{margin:0;color:var(--muted);font-size:.93rem} +.tag{display:inline-block;margin:.15rem .3rem .15rem 0;padding:.15rem .6rem;border:1px solid var(--line);border-radius:999px;font-size:.82rem;color:var(--cyan);background:rgba(0,229,255,.05)} +.pipeline{display:grid;gap:.8rem;grid-template-columns:repeat(auto-fit,minmax(min(100%,200px),1fr));counter-reset:s} +.pipeline .card{position:relative;padding-top:1.6rem} +.pipeline .card::before{counter-increment:s;content:"0" counter(s);position:absolute;top:.5rem;left:1rem;font-family:"Orbitron",sans-serif;font-size:.75rem;color:var(--cyan);text-shadow:var(--glow)} +.split{display:grid;gap:1.5rem;grid-template-columns:repeat(auto-fit,minmax(min(100%,420px),1fr));align-items:start} +.lede{color:var(--muted);max-width:46rem;margin-top:-.5rem} + +/* domains */ +.thumb{aspect-ratio:16/10;display:flex;align-items:center;justify-content:center;background:#fff;border-radius:5px;overflow:hidden;margin-bottom:.8rem;border:1px solid var(--line)} +.thumb img{width:100%;height:100%;object-fit:contain} +.thumb.ph{background:repeating-linear-gradient(45deg,#06122b,#06122b 10px,#081a3d 10px,#081a3d 20px);color:var(--blue);font-family:"Orbitron",sans-serif;font-size:.7rem;letter-spacing:.15em;text-transform:uppercase;text-align:center;padding:.5rem} +.sector h2{margin-top:2rem} +.docs-list{list-style:none;margin:0;padding:0;display:grid;gap:.8rem} + +footer{border-top:1px solid var(--line);padding:2rem 0;color:var(--muted);font-size:.9rem;box-shadow:0 -1px 18px rgba(0,229,255,.1)} +footer .wrap{display:flex;justify-content:space-between;gap:1rem;flex-wrap:wrap} + +@media (max-width:480px){body{font-size:16px}.hero{padding-bottom:11rem}.floor{height:12rem}.horizon{bottom:11.7rem}} +@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}html{scroll-behavior:auto}} diff --git a/site/build-assets.sh b/site/build-assets.sh new file mode 100755 index 0000000..be34f8b --- /dev/null +++ b/site/build-assets.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Copy example D2 diagrams into the site: examples/.d2.svg -> site/assets/diagrams/.svg +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +src="$here/../examples" +dst="$here/assets/diagrams" +mkdir -p "$dst" +n=0 +for f in "$src"/*.d2.svg; do + [ -e "$f" ] || continue + base="$(basename "$f" .d2.svg)" + cp "$f" "$dst/$base.svg" + n=$((n+1)) +done +echo "copied $n diagram(s) to site/assets/diagrams" diff --git a/site/docs.html b/site/docs.html new file mode 100644 index 0000000..72bee32 --- /dev/null +++ b/site/docs.html @@ -0,0 +1,13 @@ + + +Documentation | OntoLogic + + + + + + + + +

DOCUMENTATION

Documentation lives in the repository and opens on GitHub.

  • Documentation index

    Master table of contents for manuals, architecture and design guides.

  • User guide

    Tutorial, syntax reference, CLI flags, multi-target workflows and troubleshooting.

  • Architecture

    Compiler pipeline: AST, intermediate representation, linter and emitters.

  • Purpose

    Why the project exists and the problems it addresses.

  • Using OntoLogic

    Quick command-line manual, flags, syntax rules and examples.

  • Standard library

    Foundational ontologies (BFO, CCO, UCO), threat intelligence, AI governance and compliance libraries.

  • Domain catalog

    Overview of the domain example ontologies and how they are structured.

  • Changelog

    Release history and notable changes.

+ diff --git a/site/domains.html b/site/domains.html new file mode 100644 index 0000000..a300b64 --- /dev/null +++ b/site/domains.html @@ -0,0 +1,15 @@ + + +Domain examples | OntoLogic + + + + + + + + +

DOMAIN EXAMPLES

Each card links to the .logic source. Diagrams are generated from the models with the D2 emitter.

Energy, Mining & Industry

Cloud, Security & Software

IoT & Engineering

Science & Health

Business, Food & Logistics

+ diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..1b00978 --- /dev/null +++ b/site/index.html @@ -0,0 +1,74 @@ + + +OntoLogic | Logic-as-Code ontology compiler + + + + + + + + +
+

OntoLogic

+

Write your domain once as first-order logic. Lint it, prove it consistent, and compile it into OWL, SHACL, typed code, API contracts, graph schemas and diagrams.

+
+
+ +

What it does

+
+

Write .logic

A concise Lisp-style DSL for concepts, relations, typed properties and quantified axioms, with modular imports and namespaces.

+

Lint

Symbol resolution, circular inheritance, duplicate definitions and contradiction detection before anything runs.

+

Solve

Consistency checks, subsumption proofs, empty-concept detection and counterexamples via real solvers.

+

Emit and visualize

One model, many targets: schemas, code, API contracts, graph databases and architecture diagrams.

+
+ +

The language

+

A trimmed excerpt from examples/domain_mining.logic.

+
(def-concept HeavyMachinery MiningEquipment)
+(def-concept GasSensor Sensor)
+(def-concept SafetyAlert InformationContentEntity)
+
+(def-property methane_level GasSensor Integer)
+
+; High methane implies an evacuation alert exists
+(forall (s)
+    (implies (and (GasSensor s) (gt methane_level 5))
+             (exists (a) (SafetyAlert a))))
+ +

Emit targets

One model compiles to all of these. Pick any with -t.

OWL/RDFSHACLJavaPython (Pydantic)RustGoTypeScript/ZodOpenAPI 3.1GraphQLJSON SchemaProtobufC++SQL DDLNeo4j CypherTPTPSMT-LIB2MermaidD2
+ +

Solver backends

+
+

Z3

SMT-LIB2 consistency and satisfiability checking.

+

CVC5

Alternative SMT backend, same model, same flags.

+

Vampire

First-order ATP over TPTP FOF problems.

+

Native

Built-in solver with no external dependency. Auto-discovery picks what is installed.

+
+ +

Tooling

+
+

REPL

Incremental evaluation with :load, :solve, :prove, :emit.

+

LSP

Diagnostics, completion, hover, go-to-definition and rename.

+

VS Code

Syntax highlighting, snippets and solver commands.

+

Domain gallery

Dozens of worked ontologies across industry sectors.

+
+ +

Quickstart

# Interactive REPL
+stack exec ontologic-exe -- --repl
+
+# Lint a model
+stack exec ontologic-exe -- -i examples/smart_factory.logic -t lint
+
+# Check consistency with an SMT solver (z3, cvc5, vampire, native)
+stack exec ontologic-exe -- -i examples/smart_factory.logic -t solve --prover z3
+
+# Emit artifacts
+stack exec ontologic-exe -- -i examples/smart_factory.logic -t ts -o ./generated/ts
+stack exec ontologic-exe -- -i examples/smart_factory.logic -t openapi -o ./generated/openapi
+stack exec ontologic-exe -- -i examples/smart_grid_relational.logic -t d2 -o ./generated/diagrams --render
+
+# Language server for editors
+stack exec ontologic-lsp
+
+ diff --git a/test/DomainExamplesSpec.hs b/test/DomainExamplesSpec.hs new file mode 100644 index 0000000..26dac9c --- /dev/null +++ b/test/DomainExamplesSpec.hs @@ -0,0 +1,112 @@ +module DomainExamplesSpec (spec) where + +import Test.Hspec +import Control.Monad (forM_, unless) +import Data.Char (isSpace) +import Data.List (isPrefixOf, isSuffixOf, sort) +import System.Directory (doesFileExist, findExecutable, listDirectory) +import System.FilePath ((), takeBaseName) + +import OntoLogic +import Solver +import Loader (loadRegistryWithImports) + +fixturesDir :: FilePath +fixturesDir = "test/fixtures/domains" + +-- | 30s cap keeps a runaway fixture from hanging CI. +domainOpts :: SolverOptions +domainOpts = defaultSolverOptions { optTimeoutSeconds = Just 30 } + +-- | Z3 (then CVC5) reasons over the integer property bounds the conflict +-- fixtures rely on; the native prover does not. Nothing available -> Nothing. +pickSmtProver :: IO (Maybe Prover) +pickSmtProver = do + z3 <- findExecutable "z3" + cvc <- findExecutable "cvc5" + return $ case (z3, cvc) of + (Just _, _) -> Just Z3 + (_, Just _) -> Just CVC5 + _ -> Nothing + +data DomainExpect = ExpConcept String | ExpRelation String | ExpProperty String + +trim :: String -> String +trim = f . f where f = reverse . dropWhile isSpace + +parseExpect :: FilePath -> String -> Either String [DomainExpect] +parseExpect path = mapM one . filter keep . map trim . lines + where + keep l = not (null l) && not ("#" `isPrefixOf` l) + one l = case words l of + ["concept", n] -> Right (ExpConcept n) + ["relation", n] -> Right (ExpRelation n) + ["property", n] -> Right (ExpProperty n) + _ -> Left (path ++ ": malformed line: " ++ show l) + +checkExpectation :: FilePath -> Registry -> DomainExpect -> Maybe String +checkExpectation file reg e = case e of + ExpConcept n -> miss "concept" n (n `elem` map fst (concepts reg)) + ExpRelation n -> miss "relation" n (n `elem` map relName (relations reg)) + ExpProperty n -> miss "property" n (n `elem` map propName (properties reg)) + where + miss kind n ok + | ok = Nothing + | otherwise = Just (file ++ ": expected " ++ kind ++ " '" ++ n ++ "' not found in registry") + +spec :: Spec +spec = describe "Domain examples (data-driven fixtures)" $ do + expectFiles <- runIO $ sort . filter (".expect" `isSuffixOf`) <$> listDirectory fixturesDir + let names = map takeBaseName expectFiles + + describe "fixture coverage guard" $ + it "every examples/domain_*.logic has a matching .expect fixture" $ do + exs <- listDirectory "examples" + let domains = [ takeBaseName f | f <- sort exs, "domain_" `isPrefixOf` f, ".logic" `isSuffixOf` f ] + missing = [ d | d <- domains, d `notElem` names ] + unless (null missing) $ + expectationFailure $ "domain examples without " ++ fixturesDir ++ "/.expect: " ++ show missing + + forM_ names $ \name -> describe name $ do + let exampleF = "examples" name ++ ".logic" + expectF = fixturesDir name ++ ".expect" + conflict = fixturesDir name ++ "_conflict.logic" + + it "parses and declares every expected name" $ do + txt <- readFile expectF + exps <- either (\e -> expectationFailure e >> return []) return (parseExpect expectF txt) + r <- loadRegistryWithImports exampleF + case r of + Left err -> expectationFailure (exampleF ++ ": failed to load: " ++ err) + Right reg -> do + let problems = [ m | ex <- exps, Just m <- [checkExpectation exampleF reg ex] ] + unless (null problems) $ expectationFailure (unlines problems) + + it "is consistent (SAT)" $ do + prover <- maybe NativeProver id <$> pickSmtProver + r <- loadRegistryWithImports exampleF + case r of + Left err -> expectationFailure (exampleF ++ ": failed to load: " ++ err) + Right reg -> do + res <- checkConsistencyWithOptions domainOpts prover reg + case res of + Sat _ -> return () + _ -> expectationFailure (exampleF ++ ": expected SAT but got " ++ show res) + + hasConflict <- runIO (doesFileExist conflict) + if hasConflict + then it "conflict fixture is inconsistent (UNSAT)" $ do + mp <- pickSmtProver + case mp of + Nothing -> pendingWith "neither z3 nor cvc5 installed in PATH" + Just prover -> do + r <- loadRegistryWithImports conflict + case r of + Left err -> expectationFailure (conflict ++ ": failed to load: " ++ err) + Right reg -> do + res <- checkConsistencyWithOptions domainOpts prover reg + case res of + Unsat -> return () + _ -> expectationFailure (conflict ++ ": expected UNSAT but got " ++ show res) + else it "conflict fixture is inconsistent (UNSAT)" $ + pendingWith ("no " ++ conflict) diff --git a/test/fixtures/domains/domain_aerospace.expect b/test/fixtures/domains/domain_aerospace.expect new file mode 100644 index 0000000..868bf7c --- /dev/null +++ b/test/fixtures/domains/domain_aerospace.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Aircraft +concept LifeLimitedPart +concept AirworthinessCertificate +concept MaintenanceCheck +concept CommercialFlight +relation has_certificate +relation installed_on +relation commands +property is_airworthy +property hours_since_check +property flight_cycles diff --git a/test/fixtures/domains/domain_aerospace_conflict.logic b/test/fixtures/domains/domain_aerospace_conflict.logic new file mode 100644 index 0000000..800c719 --- /dev/null +++ b/test/fixtures/domains/domain_aerospace_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: asserts an aircraft that is airworthy but whose last check +; is overdue (600+ hours), violating the maintenance-interval axiom. +(import "../../../examples/domain_aerospace.logic") + +(exists (a) + (and (Aircraft a) (eq is_airworthy True) (gt hours_since_check 700))) diff --git a/test/fixtures/domains/domain_agriculture.expect b/test/fixtures/domains/domain_agriculture.expect new file mode 100644 index 0000000..b61bef7 --- /dev/null +++ b/test/fixtures/domains/domain_agriculture.expect @@ -0,0 +1,13 @@ +# key names +concept Farm +concept Field +concept Crop +concept Livestock +concept IrrigationSystem +concept MoistureSensor +concept Harvest +relation planted_with +relation irrigates +relation harvested_from +property soil_ph +property withdrawal_days diff --git a/test/fixtures/domains/domain_agriculture_conflict.logic b/test/fixtures/domains/domain_agriculture_conflict.logic new file mode 100644 index 0000000..2b237e0 --- /dev/null +++ b/test/fixtures/domains/domain_agriculture_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: violates the integrity axiom that crops are never livestock. +(import "../../../examples/domain_agriculture.logic") + +; Assert an individual that is both Crop and Livestock, +; contradicting the disjointness axiom in the base ontology. +(exists (x) (and (Crop x) (Livestock x))) diff --git a/test/fixtures/domains/domain_clinical_medicine.expect b/test/fixtures/domains/domain_clinical_medicine.expect new file mode 100644 index 0000000..a51d38a --- /dev/null +++ b/test/fixtures/domains/domain_clinical_medicine.expect @@ -0,0 +1,14 @@ +# key names +concept Patient +concept Clinician +concept MedicationOrder +concept ControlledSubstanceOrder +concept DrugAllergy +concept Contraindication +concept Diagnosis +concept EmergencyVisit +relation prescribes +relation has_allergy +relation triggers_allergy +property oxygen_saturation +property triage_level diff --git a/test/fixtures/domains/domain_clinical_medicine_conflict.logic b/test/fixtures/domains/domain_clinical_medicine_conflict.logic new file mode 100644 index 0000000..fd09389 --- /dev/null +++ b/test/fixtures/domains/domain_clinical_medicine_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: violates the clinical-medicine integrity axiom that +; patients and clinicians are disjoint record types. +(import "../../../examples/domain_clinical_medicine.logic") + +; Assert a staff member who is simultaneously a Patient and a Clinician. +(exists (x) (and (Patient x) (Clinician x))) diff --git a/test/fixtures/domains/domain_cloud_datacenter.expect b/test/fixtures/domains/domain_cloud_datacenter.expect new file mode 100644 index 0000000..6a4a554 --- /dev/null +++ b/test/fixtures/domains/domain_cloud_datacenter.expect @@ -0,0 +1,7 @@ +concept ComputeNode +concept PhysicalServer +concept VirtualMachine +concept Container +property cpu_usage +property memory_usage +property replica_count diff --git a/test/fixtures/domains/domain_cloud_datacenter_conflict.logic b/test/fixtures/domains/domain_cloud_datacenter_conflict.logic new file mode 100644 index 0000000..5240d5b --- /dev/null +++ b/test/fixtures/domains/domain_cloud_datacenter_conflict.logic @@ -0,0 +1,4 @@ +(import "../../../examples/domain_cloud_datacenter.logic") +(forall (n) + (implies (ComputeNode n) + (and (gt cpu_usage 90) (lt cpu_usage 10)))) diff --git a/test/fixtures/domains/domain_customer_service.expect b/test/fixtures/domains/domain_customer_service.expect new file mode 100644 index 0000000..ae3e124 --- /dev/null +++ b/test/fixtures/domains/domain_customer_service.expect @@ -0,0 +1,13 @@ +# key names +concept Ticket +concept SupportAgent +concept Escalation +concept ServiceLevelAgreement +concept PremiumSLA +concept KnowledgeArticle +concept Queue +relation raised_by +relation escalates +relation governed_by +property csat_score +property reopen_count diff --git a/test/fixtures/domains/domain_customer_service_conflict.logic b/test/fixtures/domains/domain_customer_service_conflict.logic new file mode 100644 index 0000000..6d0ee2e --- /dev/null +++ b/test/fixtures/domains/domain_customer_service_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: violates the integrity axiom that customers are never support staff. +(import "../../../examples/domain_customer_service.logic") + +; Assert an individual that is both Customer and SupportStaff, +; contradicting the disjointness axiom in the base ontology. +(exists (x) (and (Customer x) (SupportStaff x))) diff --git a/test/fixtures/domains/domain_customer_success.expect b/test/fixtures/domains/domain_customer_success.expect new file mode 100644 index 0000000..723dfe5 --- /dev/null +++ b/test/fixtures/domains/domain_customer_success.expect @@ -0,0 +1,13 @@ +# key names +concept Account +concept EnterpriseAccount +concept CustomerSuccessManager +concept HealthScore +concept Renewal +concept ChurnRisk +concept ExecutiveBusinessReview +relation managed_by +relation renews +relation derived_from +property health_score +property has_success_plan diff --git a/test/fixtures/domains/domain_customer_success_conflict.logic b/test/fixtures/domains/domain_customer_success_conflict.logic new file mode 100644 index 0000000..13dc33d --- /dev/null +++ b/test/fixtures/domains/domain_customer_success_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: violates the integrity axiom that an account cannot be both enterprise and small-business tier. +(import "../../../examples/domain_customer_success.logic") + +; Assert an individual that is both EnterpriseAccount and SmallBusinessAccount, +; contradicting the disjointness axiom in the base ontology. +(exists (x) (and (EnterpriseAccount x) (SmallBusinessAccount x))) diff --git a/test/fixtures/domains/domain_cybersecurity_soc.expect b/test/fixtures/domains/domain_cybersecurity_soc.expect new file mode 100644 index 0000000..b00c271 --- /dev/null +++ b/test/fixtures/domains/domain_cybersecurity_soc.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Incident +concept Alert +concept Playbook +concept PrivilegedAccount +concept Tier1Analyst +relation escalates_to +relation approved_by +relation handled_by_playbook +property cvss_score +property incident_severity +property is_escalated diff --git a/test/fixtures/domains/domain_cybersecurity_soc_conflict.logic b/test/fixtures/domains/domain_cybersecurity_soc_conflict.logic new file mode 100644 index 0000000..7c4c333 --- /dev/null +++ b/test/fixtures/domains/domain_cybersecurity_soc_conflict.logic @@ -0,0 +1,8 @@ +; Conflict fixture: violates the false-positive / true-positive exclusivity +; of domain_cybersecurity_soc. An alert is classified as both. +(import "../../../examples/domain_cybersecurity_soc.logic") + +(def-concept ContradictoryVerdictAlert FalsePositiveAlert) +(forall (x) + (implies (ContradictoryVerdictAlert x) (TruePositiveAlert x))) +(exists (u) (ContradictoryVerdictAlert u)) diff --git a/test/fixtures/domains/domain_food_service.expect b/test/fixtures/domains/domain_food_service.expect new file mode 100644 index 0000000..467eaae --- /dev/null +++ b/test/fixtures/domains/domain_food_service.expect @@ -0,0 +1,14 @@ +# key names +concept MenuItem +concept Allergen +concept Poultry +concept WalkInFridge +concept HotHoldingUnit +concept FoodBatch +concept GrillStation +relation contains +relation has_allergen +relation prepared_by +property cold_holding_temp_c +property poultry_core_temp_c +property hot_holding_temp_c diff --git a/test/fixtures/domains/domain_food_service_conflict.logic b/test/fixtures/domains/domain_food_service_conflict.logic new file mode 100644 index 0000000..0bc8f0a --- /dev/null +++ b/test/fixtures/domains/domain_food_service_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: violates the integrity axiom that a dessert is never a main course. +(import "../../../examples/domain_food_service.logic") + +; Assert an individual that is both Dessert and MainCourse, +; contradicting the disjointness axiom in the base ontology. +(exists (x) (and (Dessert x) (MainCourse x))) diff --git a/test/fixtures/domains/domain_ics.expect b/test/fixtures/domains/domain_ics.expect new file mode 100644 index 0000000..ed43b23 --- /dev/null +++ b/test/fixtures/domains/domain_ics.expect @@ -0,0 +1,11 @@ +# Key names asserted to exist in the parsed registry +concept Plc +concept SafetyController +concept Interlock +concept CriticalAlarm +concept Level35Dmz +relation resides_at_level +relation bypasses +relation authorised_by +property sil_level +property scan_time_ms diff --git a/test/fixtures/domains/domain_ics_conflict.logic b/test/fixtures/domains/domain_ics_conflict.logic new file mode 100644 index 0000000..7c57123 --- /dev/null +++ b/test/fixtures/domains/domain_ics_conflict.logic @@ -0,0 +1,8 @@ +; Conflict fixture: violates the SIS independence axiom of domain_ics. +; A SafetyController must never be a basic-process Plc, yet this unit is both. +(import "../../../examples/domain_ics.logic") + +(def-concept HybridSafetyPlc SafetyController) +(forall (x) + (implies (HybridSafetyPlc x) (Plc x))) +(exists (u) (HybridSafetyPlc u)) diff --git a/test/fixtures/domains/domain_iiot.expect b/test/fixtures/domains/domain_iiot.expect new file mode 100644 index 0000000..fb28e89 --- /dev/null +++ b/test/fixtures/domains/domain_iiot.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept EdgeGateway +concept MqttBroker +concept OpcUaServer +concept PredictiveWorkOrder +concept RemainingUsefulLifeEstimate +relation publishes_to +relation monitors +relation triggers +property qos_level +property health_score +property rul_hours diff --git a/test/fixtures/domains/domain_iiot_conflict.logic b/test/fixtures/domains/domain_iiot_conflict.logic new file mode 100644 index 0000000..632aa19 --- /dev/null +++ b/test/fixtures/domains/domain_iiot_conflict.logic @@ -0,0 +1,8 @@ +; Conflict fixture: violates the "gateways are not sensors" axiom of domain_iiot. +; A combined sensing gateway is declared as both an EdgeGateway and a Sensor. +(import "../../../examples/domain_iiot.logic") + +(def-concept SensingGateway EdgeGateway) +(forall (x) + (implies (SensingGateway x) (Sensor x))) +(exists (u) (SensingGateway u)) diff --git a/test/fixtures/domains/domain_iot_smart_home.expect b/test/fixtures/domains/domain_iot_smart_home.expect new file mode 100644 index 0000000..dcd5693 --- /dev/null +++ b/test/fixtures/domains/domain_iot_smart_home.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Hub +concept Camera +concept ConsentGrant +concept FirmwareUpdate +concept Automation +relation paired_with +relation covers +relation installs +property is_signed +property retention_days +property target_temp_c diff --git a/test/fixtures/domains/domain_iot_smart_home_conflict.logic b/test/fixtures/domains/domain_iot_smart_home_conflict.logic new file mode 100644 index 0000000..487873f --- /dev/null +++ b/test/fixtures/domains/domain_iot_smart_home_conflict.logic @@ -0,0 +1,8 @@ +; Conflict fixture: violates the consent grant / withdrawal exclusivity of +; domain_iot_smart_home. One consent record is declared as both. +(import "../../../examples/domain_iot_smart_home.logic") + +(def-concept AmbiguousConsent ConsentGrant) +(forall (x) + (implies (AmbiguousConsent x) (ConsentWithdrawal x))) +(exists (u) (AmbiguousConsent u)) diff --git a/test/fixtures/domains/domain_logistics.expect b/test/fixtures/domains/domain_logistics.expect new file mode 100644 index 0000000..494d384 --- /dev/null +++ b/test/fixtures/domains/domain_logistics.expect @@ -0,0 +1,13 @@ +# key names +concept Shipment +concept Warehouse +concept Carrier +concept ColdChainShipment +concept FrozenGoods +concept DangerousGoods +concept InventoryRecord +relation carried_by +relation transports +relation stored_in +property frozen_goods_temp_c +property on_hand_quantity diff --git a/test/fixtures/domains/domain_logistics_conflict.logic b/test/fixtures/domains/domain_logistics_conflict.logic new file mode 100644 index 0000000..fbf8f2b --- /dev/null +++ b/test/fixtures/domains/domain_logistics_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: violates the cold-chain axiom that frozen and chilled goods use different temperature regimes. +(import "../../../examples/domain_logistics.logic") + +; Assert an individual that is both FrozenGoods and ChilledGoods, +; contradicting the disjointness axiom in the base ontology. +(exists (x) (and (FrozenGoods x) (ChilledGoods x))) diff --git a/test/fixtures/domains/domain_mining.expect b/test/fixtures/domains/domain_mining.expect new file mode 100644 index 0000000..bbd5de3 --- /dev/null +++ b/test/fixtures/domains/domain_mining.expect @@ -0,0 +1,9 @@ +# Mining domain +concept Excavator +concept HaulTruck +concept GasSensor +concept SafetyAlert +concept TelemetryData +property payload_weight +property methane_level +property is_autonomous diff --git a/test/fixtures/domains/domain_mining_conflict.logic b/test/fixtures/domains/domain_mining_conflict.logic new file mode 100644 index 0000000..695833a --- /dev/null +++ b/test/fixtures/domains/domain_mining_conflict.logic @@ -0,0 +1,4 @@ +(import "../../../examples/domain_mining.logic") +(forall (s) + (implies (GasSensor s) + (and (gt methane_level 5) (lt methane_level 3)))) diff --git a/test/fixtures/domains/domain_research_projects.expect b/test/fixtures/domains/domain_research_projects.expect new file mode 100644 index 0000000..3cfb149 --- /dev/null +++ b/test/fixtures/domains/domain_research_projects.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Grant +concept HumanSubjectsStudy +concept EthicsApproval +concept Dataset +concept Publication +relation led_by +relation approved_by_ethics +relation reports_on +property award_amount +property is_preregistered +property data_is_public diff --git a/test/fixtures/domains/domain_research_projects_conflict.logic b/test/fixtures/domains/domain_research_projects_conflict.logic new file mode 100644 index 0000000..851fc16 --- /dev/null +++ b/test/fixtures/domains/domain_research_projects_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: asserts a started clinical trial that is not pre-registered, +; violating the pre-registration axiom for clinical trials. +(import "../../../examples/domain_research_projects.logic") + +(exists (t) + (and (ClinicalTrial t) (eq study_started True) (eq is_preregistered False))) diff --git a/test/fixtures/domains/domain_science_lab.expect b/test/fixtures/domains/domain_science_lab.expect new file mode 100644 index 0000000..a511ead --- /dev/null +++ b/test/fixtures/domains/domain_science_lab.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Sample +concept Instrument +concept CustodyRecord +concept Calibration +concept Experiment +relation measured_by +relation follows_protocol +relation recorded_in +property calibration_valid +property days_since_calibration +property protocol_approved diff --git a/test/fixtures/domains/domain_science_lab_conflict.logic b/test/fixtures/domains/domain_science_lab_conflict.logic new file mode 100644 index 0000000..8280cf3 --- /dev/null +++ b/test/fixtures/domains/domain_science_lab_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: asserts an instrument that is 400 days past calibration yet +; still flagged calibration-valid, violating the calibration-interval axiom. +(import "../../../examples/domain_science_lab.logic") + +(exists (i) + (and (Instrument i) (gt days_since_calibration 400) (eq calibration_valid True))) diff --git a/test/fixtures/domains/domain_security_trust.expect b/test/fixtures/domains/domain_security_trust.expect new file mode 100644 index 0000000..65ad529 --- /dev/null +++ b/test/fixtures/domains/domain_security_trust.expect @@ -0,0 +1,6 @@ +concept CISORole +concept AttackerRole +concept TrustedRole +property is_valid +property key_length +property risk_score diff --git a/test/fixtures/domains/domain_security_trust_conflict.logic b/test/fixtures/domains/domain_security_trust_conflict.logic new file mode 100644 index 0000000..c1772c7 --- /dev/null +++ b/test/fixtures/domains/domain_security_trust_conflict.logic @@ -0,0 +1,4 @@ +(import "../../../examples/domain_security_trust.logic") +(forall (k) + (implies (PrivateKey k) + (and (gt key_length 4096) (lt key_length 1024)))) diff --git a/test/fixtures/domains/domain_semiconductor_fab.expect b/test/fixtures/domains/domain_semiconductor_fab.expect new file mode 100644 index 0000000..ab96714 --- /dev/null +++ b/test/fixtures/domains/domain_semiconductor_fab.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Wafer +concept Lot +concept LithographyBay +concept QualifiedRecipe +concept KillerDefect +relation contains_wafer +relation uses_recipe +relation hold_for +property wafer_count +property die_yield_pct +property iso_class_number diff --git a/test/fixtures/domains/domain_semiconductor_fab_conflict.logic b/test/fixtures/domains/domain_semiconductor_fab_conflict.logic new file mode 100644 index 0000000..a940854 --- /dev/null +++ b/test/fixtures/domains/domain_semiconductor_fab_conflict.logic @@ -0,0 +1,8 @@ +; Conflict fixture: violates the product/dummy wafer exclusivity of +; domain_semiconductor_fab. A wafer is declared to be both. +(import "../../../examples/domain_semiconductor_fab.logic") + +(def-concept RecycledWafer ProductWafer) +(forall (x) + (implies (RecycledWafer x) (DummyWafer x))) +(exists (u) (RecycledWafer u)) diff --git a/test/fixtures/domains/domain_software_delivery.expect b/test/fixtures/domains/domain_software_delivery.expect new file mode 100644 index 0000000..e76237a --- /dev/null +++ b/test/fixtures/domains/domain_software_delivery.expect @@ -0,0 +1,13 @@ +# Key names asserted to exist in the parsed registry +concept PullRequest +concept Commit +concept Release +concept ProductionDeployment +concept Incident +concept Build +relation reviewed_by +relation deploys +relation builds_from +property approval_count +property is_signed_off +property incident_severity diff --git a/test/fixtures/domains/domain_software_delivery_conflict.logic b/test/fixtures/domains/domain_software_delivery_conflict.logic new file mode 100644 index 0000000..b6fc1b7 --- /dev/null +++ b/test/fixtures/domains/domain_software_delivery_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: asserts a published release that was never signed off, +; violating the release-gate axiom of domain_software_delivery. +(import "../../../examples/domain_software_delivery.logic") + +(exists (r) + (and (Release r) (eq is_published True) (eq is_signed_off False))) diff --git a/test/fixtures/domains/domain_systems_engineering.expect b/test/fixtures/domains/domain_systems_engineering.expect new file mode 100644 index 0000000..b781157 --- /dev/null +++ b/test/fixtures/domains/domain_systems_engineering.expect @@ -0,0 +1,12 @@ +# Key names asserted to exist in the parsed registry +concept Requirement +concept SafetyRequirement +concept Interface +concept VerificationActivity +concept ChangeRequest +relation verified_by +relation allocated_to +relation derives_from +property is_approved +property is_allocated +property change_approved diff --git a/test/fixtures/domains/domain_systems_engineering_conflict.logic b/test/fixtures/domains/domain_systems_engineering_conflict.logic new file mode 100644 index 0000000..8adebd0 --- /dev/null +++ b/test/fixtures/domains/domain_systems_engineering_conflict.logic @@ -0,0 +1,6 @@ +; Conflict fixture: asserts an approved requirement that is not allocated to any +; element, violating the allocation-completeness axiom. +(import "../../../examples/domain_systems_engineering.logic") + +(exists (r) + (and (Requirement r) (eq is_approved True) (eq is_allocated False)))