Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

The reasoner benchmark measures what it says it measures (#310)

Fabio Rovai818d2c6cf89f
diff --git a/benchmark/reasoner/.gitignore b/benchmark/reasoner/.gitignore
index f8d385b9..49c9895f 100644
--- a/benchmark/reasoner/.gitignore
+++ b/benchmark/reasoner/.gitignore
@@ -2,3 +2,9 @@ lib/
*.class
*.owl
target/
+corpora/
+results/ore_*
+results/oo_batch.json
+results/oo_result.json
+results/hermit_result.json
+results/pellet_result.json
diff --git a/benchmark/reasoner/Convert.java b/benchmark/reasoner/Convert.java
new file mode 100644
index 00000000..f2c23204
--- /dev/null
+++ b/benchmark/reasoner/Convert.java
@@ -0,0 +1,28 @@
+import org.semanticweb.owlapi.apibinding.OWLManager;
+import org.semanticweb.owlapi.formats.RDFXMLDocumentFormat;
+import org.semanticweb.owlapi.model.*;
+import java.io.*;
+
+/**
+ * Re-serialise an ontology to RDF/XML with the OWL API.
+ *
+ * The ORE 2015 corpus ships in OWL Functional Syntax. run_ore.py converts each
+ * input ONCE with this program and then feeds the converted file to both the
+ * engine and HermiT, so the two reasoners always read the same bytes. Run
+ * run_ore.py with --native to skip the conversion and feed the original file.
+ *
+ * Usage: java -cp <classes>:<lib>/* Convert <in> <out.rdf>
+ */
+public class Convert {
+ public static void main(String[] args) throws Exception {
+ if (args.length != 2) {
+ System.err.println("Usage: Convert <in> <out.rdf>");
+ System.exit(1);
+ }
+ OWLOntologyManager m = OWLManager.createOWLOntologyManager();
+ OWLOntology o = m.loadOntologyFromOntologyDocument(new File(args[0]));
+ try (OutputStream out = new BufferedOutputStream(new FileOutputStream(args[1]))) {
+ m.saveOntology(o, new RDFXMLDocumentFormat(), out);
+ }
+ }
+}
diff --git a/benchmark/reasoner/JavaReasoner.java b/benchmark/reasoner/JavaReasoner.java
index 2089ebd2..a5de49fa 100644
--- a/benchmark/reasoner/JavaReasoner.java
+++ b/benchmark/reasoner/JavaReasoner.java
@@ -1,75 +1,233 @@
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;
+import org.semanticweb.owlapi.model.parameters.Imports;
import org.semanticweb.owlapi.reasoner.*;
import java.io.*;
+import java.lang.management.ManagementFactory;
import java.util.*;
+/**
+ * Reference classification for the reasoner benchmarks.
+ *
+ * Output is the FULL entailed named-class hierarchy, not the direct one. For
+ * every named class C that the reasoner finds satisfiable, it emits "C -> D"
+ * for every named D with C entailed to be a subclass of D: all superclasses
+ * (direct=false) plus all equivalent classes. owl:Thing and owl:Nothing never
+ * appear in a pair. Unsatisfiable classes are listed under "unsatisfiable" and
+ * contribute no pairs, because an unsatisfiable class is trivially a subclass
+ * of everything and would swamp the comparison.
+ *
+ * Why not direct superclasses: the engine reports all superclasses, so a
+ * direct-only reference makes every indirect pair look like an unsound extra.
+ * Direct superclasses also never include equivalent classes. In ORE file
+ * ore_ont_8937, axioms SubClassOf(owl:Thing C23) make C23 equivalent to
+ * owl:Thing, so the true pair C25 -> C23 is absent from a direct-only
+ * reference and a correct engine answer was misread as unsound.
+ *
+ * It also emits "told_subsumptions": the reflexive-free transitive closure of
+ * the ASSERTED named hierarchy, i.e. SubClassOf(A, B) with A and B named,
+ * pairwise EquivalentClasses among named members, and the tautological edge
+ * A -> owl:Thing for every named A. No reasoner is involved in computing it.
+ * A structural walk of the asserted axioms finds exactly these pairs, so the
+ * benchmark subtracts them to measure what reasoning adds.
+ *
+ * Times are reported separately and never summed silently:
+ * jvm_start_ms JVM start to entry of main (process boot cost)
+ * load_ms parse the document into an OWLOntology
+ * reasoner_create_ms construct the reasoner (HermiT clausifies here)
+ * classify_ms precomputeInferences(CLASS_HIERARCHY) only
+ * extract_ms read the hierarchy back out (not reasoning cost)
+ * time_ms reasoner_create_ms + classify_ms, kept for older callers
+ */
public class JavaReasoner {
public static void main(String[] args) throws Exception {
+ long mainEntry = System.currentTimeMillis();
+ long jvmStart = ManagementFactory.getRuntimeMXBean().getStartTime();
if (args.length < 3) {
- System.err.println("Usage: JavaReasoner <reasoner> <ontology.owl> <output.json>");
+ System.err.println("Usage: JavaReasoner <hermit|pellet> <ontology> <output.json>");
System.exit(1);
}
- String reasonerName = args[0]; // "hermit" or "pellet"
+ String reasonerName = args[0];
String ontologyPath = args[1];
String outputPath = args[2];
+ long t0 = System.nanoTime();
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(ontologyPath));
+ long loadNs = System.nanoTime() - t0;
- OWLReasonerFactory factory;
- if (reasonerName.equals("hermit")) {
- factory = new org.semanticweb.HermiT.ReasonerFactory();
- } else if (reasonerName.equals("pellet")) {
- // Load Pellet via reflection (may not be on classpath)
- try {
- Class<?> cls = Class.forName("com.clarkparsia.pellet.owlapi.PelletReasonerFactory");
- factory = (OWLReasonerFactory) cls.getMethod("getInstance").invoke(null);
- } catch (ClassNotFoundException e) {
- // Try Openllet fork
- try {
- Class<?> cls = Class.forName("openllet.owlapi.OpenlletReasonerFactory");
- factory = (OWLReasonerFactory) cls.getMethod("getInstance").invoke(null);
- } catch (ClassNotFoundException e2) {
- System.err.println("ERROR: Neither Pellet nor Openllet found on classpath");
- System.exit(1);
- return;
- }
- }
- } else {
- throw new IllegalArgumentException("Unknown reasoner: " + reasonerName);
- }
+ OWLReasonerFactory factory = factoryFor(reasonerName);
- long startTime = System.currentTimeMillis();
+ long t1 = System.nanoTime();
OWLReasoner reasoner = factory.createReasoner(ontology);
- reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);
- long elapsed = System.currentTimeMillis() - startTime;
+ long createNs = System.nanoTime() - t1;
- // Extract all subsumption pairs
- Set<OWLClass> classes = ontology.getClassesInSignature();
+ // An inconsistent ontology makes HermiT throw from precomputeInferences.
+ // Report it as consistent=false with no pairs rather than crashing, so
+ // the driver can check whether the engine noticed.
+ long t2 = System.nanoTime();
+ boolean consistent;
+ try {
+ reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY);
+ consistent = reasoner.isConsistent();
+ } catch (InconsistentOntologyException e) {
+ consistent = false;
+ }
+ long classifyNs = System.nanoTime() - t2;
+
+ long t3 = System.nanoTime();
+ Set<OWLClass> classes = ontology.getClassesInSignature(Imports.INCLUDED);
List<String> subsumptions = new ArrayList<>();
+ List<String> unsatisfiable = new ArrayList<>();
+ int namedClasses = 0;
for (OWLClass cls : classes) {
- for (OWLClass sup : reasoner.getSuperClasses(cls, true).getFlattened()) {
+ if (cls.isOWLThing() || cls.isOWLNothing()) continue;
+ namedClasses++;
+ if (!consistent) continue;
+ if (!reasoner.isSatisfiable(cls)) {
+ unsatisfiable.add(cls.getIRI().toString());
+ continue;
+ }
+ Set<OWLClass> supers = new HashSet<>(reasoner.getSuperClasses(cls, false).getFlattened());
+ supers.addAll(reasoner.getEquivalentClasses(cls).getEntities());
+ for (OWLClass sup : supers) {
+ if (sup.equals(cls) || sup.isOWLThing() || sup.isOWLNothing()) continue;
subsumptions.add(cls.getIRI().toString() + " -> " + sup.getIRI().toString());
}
}
Collections.sort(subsumptions);
+ Collections.sort(unsatisfiable);
+ long extractNs = System.nanoTime() - t3;
- // Write JSON output
+ long t4 = System.nanoTime();
+ List<String> told = toldClosure(ontology, classes);
+ long toldNs = System.nanoTime() - t4;
+
+ long createMs = createNs / 1_000_000L;
+ long classifyMs = classifyNs / 1_000_000L;
StringBuilder sb = new StringBuilder();
- sb.append("{\"reasoner\":\"").append(reasonerName).append("\",");
- sb.append("\"time_ms\":").append(elapsed).append(",");
- sb.append("\"classes\":").append(classes.size()).append(",");
- sb.append("\"subsumptions\":[");
- for (int i = 0; i < subsumptions.size(); i++) {
+ sb.append("{\"reasoner\":").append(q(reasonerName)).append(",");
+ sb.append("\"ontology\":").append(q(ontologyPath)).append(",");
+ sb.append("\"pairs\":\"all_superclasses_plus_equivalents\",");
+ sb.append("\"jvm_start_ms\":").append(mainEntry - jvmStart).append(",");
+ sb.append("\"load_ms\":").append(loadNs / 1_000_000L).append(",");
+ sb.append("\"reasoner_create_ms\":").append(createMs).append(",");
+ sb.append("\"classify_ms\":").append(classifyMs).append(",");
+ sb.append("\"extract_ms\":").append(extractNs / 1_000_000L).append(",");
+ sb.append("\"told_ms\":").append(toldNs / 1_000_000L).append(",");
+ sb.append("\"time_ms\":").append(createMs + classifyMs).append(",");
+ sb.append("\"consistent\":").append(consistent).append(",");
+ sb.append("\"axioms\":").append(ontology.getLogicalAxiomCount()).append(",");
+ sb.append("\"classes\":").append(namedClasses).append(",");
+ appendArray(sb, "unsatisfiable", unsatisfiable);
+ sb.append(",");
+ appendArray(sb, "subsumptions", subsumptions);
+ sb.append(",");
+ appendArray(sb, "told_subsumptions", told);
+ sb.append("}");
+
+ try (Writer w = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8")) {
+ w.write(sb.toString());
+ }
+ reasoner.dispose();
+ System.out.println("Done: " + reasonerName + " create " + createMs + "ms, classify "
+ + classifyMs + "ms, " + subsumptions.size() + " entailed pairs, "
+ + told.size() + " told pairs, " + unsatisfiable.size() + " unsatisfiable");
+ }
+
+ /** Transitive closure of the asserted named-class hierarchy, no reasoner. */
+ static List<String> toldClosure(OWLOntology ontology, Set<OWLClass> classes) {
+ Map<OWLClass, Set<OWLClass>> up = new HashMap<>();
+ OWLClass thing = null;
+ for (OWLClass c : classes) {
+ if (c.isOWLThing()) thing = c;
+ }
+ for (OWLSubClassOfAxiom ax : ontology.getAxioms(AxiomType.SUBCLASS_OF, Imports.INCLUDED)) {
+ if (ax.getSubClass().isAnonymous() || ax.getSuperClass().isAnonymous()) continue;
+ edge(up, ax.getSubClass().asOWLClass(), ax.getSuperClass().asOWLClass());
+ }
+ for (OWLEquivalentClassesAxiom ax : ontology.getAxioms(AxiomType.EQUIVALENT_CLASSES, Imports.INCLUDED)) {
+ List<OWLClass> named = new ArrayList<>(ax.getNamedClasses());
+ for (OWLClass a : named) {
+ for (OWLClass b : named) {
+ if (!a.equals(b)) edge(up, a, b);
+ }
+ }
+ }
+ // Every named class is a subclass of owl:Thing. This only matters when
+ // the ontology gives owl:Thing a told superclass, as ore_ont_8937 does.
+ if (thing != null) {
+ for (OWLClass c : classes) {
+ if (!c.isOWLThing() && !c.isOWLNothing()) edge(up, c, thing);
+ }
+ }
+ List<String> out = new ArrayList<>();
+ for (OWLClass c : classes) {
+ if (c.isOWLThing() || c.isOWLNothing()) continue;
+ Set<OWLClass> seen = new HashSet<>();
+ Deque<OWLClass> stack = new ArrayDeque<>(up.getOrDefault(c, Collections.emptySet()));
+ while (!stack.isEmpty()) {
+ OWLClass d = stack.pop();
+ if (!seen.add(d)) continue;
+ stack.addAll(up.getOrDefault(d, Collections.emptySet()));
+ }
+ for (OWLClass d : seen) {
+ if (d.equals(c) || d.isOWLThing() || d.isOWLNothing()) continue;
+ out.add(c.getIRI().toString() + " -> " + d.getIRI().toString());
+ }
+ }
+ Collections.sort(out);
+ return out;
+ }
+
+ static void edge(Map<OWLClass, Set<OWLClass>> up, OWLClass a, OWLClass b) {
+ up.computeIfAbsent(a, k -> new HashSet<>()).add(b);
+ }
+
+ static OWLReasonerFactory factoryFor(String name) throws Exception {
+ if (name.equals("hermit")) {
+ return new org.semanticweb.HermiT.ReasonerFactory();
+ }
+ if (name.equals("pellet")) {
+ for (String fqcn : new String[] {
+ "com.clarkparsia.pellet.owlapi.PelletReasonerFactory",
+ "openllet.owlapi.OpenlletReasonerFactory"}) {
+ try {
+ Class<?> cls = Class.forName(fqcn);
+ return (OWLReasonerFactory) cls.getMethod("getInstance").invoke(null);
+ } catch (ClassNotFoundException e) {
+ // try the next one
+ }
+ }
+ System.err.println("ERROR: Neither Pellet nor Openllet found on classpath");
+ System.exit(2);
+ }
+ throw new IllegalArgumentException("Unknown reasoner: " + name);
+ }
+
+ static void appendArray(StringBuilder sb, String key, List<String> items) {
+ sb.append(q(key)).append(":[");
+ for (int i = 0; i < items.size(); i++) {
if (i > 0) sb.append(",");
- sb.append("\"").append(subsumptions.get(i).replace("\"", "\\\"")).append("\"");
+ sb.append(q(items.get(i)));
}
- sb.append("]}");
+ sb.append("]");
+ }
- try (FileWriter fw = new FileWriter(outputPath)) {
- fw.write(sb.toString());
+ static String q(String s) {
+ StringBuilder sb = new StringBuilder("\"");
+ for (char ch : s.toCharArray()) {
+ switch (ch) {
+ case '"': sb.append("\\\""); break;
+ case '\\': sb.append("\\\\"); break;
+ case '\n': sb.append("\\n"); break;
+ case '\r': sb.append("\\r"); break;
+ case '\t': sb.append("\\t"); break;
+ default:
+ if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
+ else sb.append(ch);
+ }
}
- System.out.println("Done: " + reasonerName + " in " + elapsed + "ms, " + subsumptions.size() + " subsumptions");
+ return sb.append("\"").toString();
}
}
diff --git a/benchmark/reasoner/README.md b/benchmark/reasoner/README.md
index dcb41967..9018945d 100644
--- a/benchmark/reasoner/README.md
+++ b/benchmark/reasoner/README.md
@@ -4,31 +4,161 @@ Compare Open Ontologies reasoning against HermiT and Pellet.
## Setup
-### Java Reasoners
+### Java reasoners
-Download these JARs into `lib/`:
+`setup_jars.sh` downloads OWL API 4.5.29, HermiT 1.4.3.456 and Pellet
+2.4.0-ignazio into `lib/`. The harness has been run against a `lib/` holding
+`owlapi-osgidistribution-4.5.29.jar`, `HermiT-1.4.3.456.jar` and the OWL API's
+runtime dependencies (guava, caffeine, rdf4j, jackson, commons-io,
+commons-lang3, hppcrt, xz, javax.inject, automaton, slf4j). Pellet is optional:
+the Pizza script runs it only when a `pellet-*.jar` or `openllet-*.jar` is
+present. Earlier text here asked for OWL API 5.x and `HermiT.jar` from
+hermit-reasoner.net; neither matches `JavaReasoner.java`, which is compiled
+against OWL API 4.
-1. **OWL API** (5.x): `owlapi-distribution-5.1.20.jar`
-2. **HermiT**: `HermiT.jar` from [hermit-reasoner.net](http://www.hermit-reasoner.net/)
-3. **Pellet**: `pellet-cli-2.4.0.jar` and dependencies from [Pellet releases](https://github.com/stardog-union/pellet/releases)
+The scripts compile `JavaReasoner.java` and `Convert.java` themselves into
+`target/java/` (ignored by git). No Maven step is needed.
### Python
-```bash
-pip install matplotlib
-```
+`run_ore.py` and `compare_results.py` use the standard library only.
+`plot_results.py` needs `pip install matplotlib`.
+
+## What the reference is
+
+`JavaReasoner.java` emits, for every named class HermiT finds satisfiable, every
+named class it is entailed to be a subclass of: all superclasses with
+`direct=false` plus all equivalent classes. `owl:Thing` and `owl:Nothing` never
+appear in a pair, and unsatisfiable classes are listed separately under
+`unsatisfiable` instead of contributing a pair to every class in the ontology.
+The engine's `classification[].superclasses` is also the full set, so the two
+sides now count the same thing.
+
+An earlier version emitted `getSuperClasses(cls, true)`, the DIRECT
+superclasses. Compared with the engine's full set, every indirect pair the
+engine got right looked like an unsound extra. Direct superclasses also never
+include equivalent classes: in ORE file `ore_ont_8937`, axioms such as
+`SubClassOf(owl:Thing C23)` make `C23` equivalent to `owl:Thing`, so the true
+pair `C25 -> C23` was missing from the reference and a correct engine answer
+was read as unsound.
+
+`JavaReasoner` reports its times separately: `jvm_start_ms` (JVM boot to
+`main`), `load_ms` (parse), `reasoner_create_ms` (HermiT clausifies here),
+`classify_ms` (`precomputeInferences` only) and `extract_ms` (reading the
+hierarchy back, not reasoning cost). `time_ms` is create plus classify and is
+kept for older callers.
## Benchmarks
### Pizza Correctness
-Compares classification of the Pizza ontology across all three reasoners. Note that `benchmark/reference/pizza-reference.owl` contains six `owl:hasValue` restrictions and two `owl:oneOf` enumerations, which this reasoner does not implement, so the `owl-dl` profile currently returns 143 of 144 classes undetermined and zero inferred subsumptions on it:
+Compares the engine's `owl-dl` classification of
+`benchmark/reference/pizza-reference.owl` with HermiT's, and with Pellet's when
+its jars are present. The file contains six `owl:hasValue` restrictions and one
+`owl:oneOf` enumeration of five individuals, so it is a nominal-bearing
+ontology; see [`regressions/`](regressions/) for what that does to this
+reasoner.
```bash
export OO_BIN=./target/release/open-ontologies
bash benchmark/reasoner/run_pizza_correctness.sh
```
+The engine runs as `load` then `reason --profile owl-dl` inside one
+`batch -` process, because the store is in memory and a second process would
+reason over an empty graph. Before anything is compared, the script refuses
+the run unless the load line reports `triples_loaded > 0` with no error and the
+reason line carries no error and a non-zero `named_classes`. The previous guard
+read `classes` or `class_count`, keys the `owl-dl` result does not have, so it
+aborted every real run with "reasoned over an empty graph". The guard can be
+exercised with `PIZZA_OWL=/path/to/empty.owl`, which it rejects.
+
+`compare_results.py` reads the engine side from `classification` plus
+`equivalences` and scores it with the same code as the ORE driver below. It
+previously read a `subsumptions` key from the engine result, which the engine
+never emits, so it compared HermiT's direct superclasses against an empty set.
+
+`run_benchmark.py` and `results/pizza_comparison.json` predate these fixes.
+`run_benchmark.py` still runs `load` and `reason` as separate processes, and
+the committed JSON reports `named_classes: 1`, the signature of a reasoner that
+saw an empty store. Do not quote either.
+
+### ORE 2015 classification
+
+`run_ore.py` runs the engine and HermiT over files from the ORE 2015
+competition corpus and scores the engine against HermiT pair by pair. It
+expects the corpus's `pool_sample` directory at `corpora/ore2015/pool_sample`
+(ignored by git; pass `--corpus` to point elsewhere) and reads
+`<track>/classification/fileorder.txt` for the track (`el`, `dl` or
+`pure_dl`).
+
+```bash
+python3 benchmark/reasoner/run_ore.py --selftest
+python3 benchmark/reasoner/run_ore.py --track el --sort-by-size --limit 6 \
+ --engine ./target/release/open-ontologies
+python3 benchmark/reasoner/run_ore.py --track dl --files ore_ont_9695.owl ore_ont_1325.owl
+python3 benchmark/reasoner/run_ore.py --track pure_dl --file-list my_files.txt --repeat 5
+```
+
+**Same bytes to both reasoners.** ORE files are OWL Functional Syntax, which
+the engine does not read yet. Each input is converted once to RDF/XML by the OWL
+API (`Convert.java`), cached under `--work-dir`, and the converted file is given
+to both the engine and HermiT. `--native` skips the conversion and gives the
+original file to both, for when the engine reads Functional Syntax; until then
+every `--native` run fails the load gate, which is the intended outcome.
+
+**One engine process per run.** The engine is driven as
+`printf 'load <f>\nreason --profile owl-dl\n' | <bin> batch -` with a
+wall-clock cap enforced by the driver (`--engine-timeout`, default 120 s), which
+kills the process group when it expires. HermiT has its own cap
+(`--hermit-timeout`).
+
+**Gates.** No timing is reported for a run whose load line lacks
+`triples_loaded` or has it at 0 or carries an error, whose reason line carries
+an error or is missing, whose process exits non-zero, or which the cap killed.
+Such a file is listed under its failure status with its time withheld.
+
+**Told-closure subtraction.** For every file the driver also asks the OWL API,
+with no reasoner, for the TOLD closure: the transitive closure of
+`SubClassOf(A, B)` with both sides named, pairwise `EquivalentClasses` among
+named members, and the tautological edge from every named class to
+`owl:Thing`. Gold minus told is the INFERRED-only set, the pairs that need
+reasoning to find. Recall is reported on both, and the headline uses
+inferred-only recall. A file whose inferred-only set is empty is flagged
+`told_only` and excluded from the headline, because a structural walk of the
+asserted axioms scores 100% on it without reasoning at all. This is not a
+corner case. An ontology whose logical axioms are all `SubClassOf` with a named
+class on the left and a named class or an existential restriction on the right,
+the shape of many files in the EL track, entails no named subsumption beyond
+the told closure apart from those through unsatisfiable classes, at any size.
+Without the subtraction, a told-hierarchy walk and a complete reasoner are
+indistinguishable on such files.
+
+**Per file** the driver reports engine wall time (median over repeats, load
+plus reason), the engine's own `agents.total_time_ms`, HermiT create and
+classify times, gold, told and inferred-only counts, engine pairs, recall on
+all and on inferred-only pairs, the WRONG pairs (the engine claims, HermiT
+does not entail; listed in full in the JSON), wrong and missed unsatisfiable
+classes, the engine's undetermined count and `budget_exhausted_in`, and whether
+the engine's answer was identical across `--repeat` runs (default 3). Pairs
+whose subclass HermiT finds unsatisfiable are excluded from both sides, since
+such a class is a subclass of everything. Engine pairs involving blank nodes
+are dropped and counted. A file HermiT finds inconsistent has no hierarchy to
+compare; it is reported as `hermit_inconsistent`, together with whether the
+engine reported `consistent: true` for it, which counts as a wrong answer. A
+file whose engine run fails a gate still shows its gold, told and
+inferred-only counts, so the table says what the failure cost, but it carries
+no recall and no time. Results go to `results/ore_<track>_<timestamp>.json`
+and `.md` (ignored by git).
+
+**Self-test.** `--selftest` drives fake engines through the same code: a
+correct one, a structural walk, an empty classification, a fabricated wrong
+pair, a false unsatisfiability claim, an empty load, a load error, a missing
+`triples_loaded`, a reason error, a crash, a hang past a 1 s cap, an engine
+whose answer changes between runs, an engine that calls an inconsistent
+ontology consistent, and a told-only file. Each check asserts
+the driver reports the defect, and the command exits non-zero if any does not.
+
### LUBM Performance
Generates university ontologies at increasing scale and measures classification time:
@@ -74,6 +204,9 @@ individuals), same task, same machine, HermiT 1.4.3.456 on JDK 17:
| Inferred subsumptions | **311** | **0** |
| Outcome | complete | incomplete, 143 undetermined |
+The pair counts in this table predate the full-hierarchy reference described
+above and are not comparable with what the current harness reports.
+
The claim was not merely unsupported. It was inverted. **No speed claim against
any Java reasoner should be made from this repository.** The reason our reasoner
does not complete is documented in [`regressions/`](regressions/): it does not
diff --git a/benchmark/reasoner/compare_results.py b/benchmark/reasoner/compare_results.py
index c25d2411..b098ee90 100755
--- a/benchmark/reasoner/compare_results.py
+++ b/benchmark/reasoner/compare_results.py
@@ -1,70 +1,87 @@
#!/usr/bin/env python3
-"""Compare reasoner classification results for correctness."""
+"""Compare the engine's owl-dl classification with HermiT's, like with like.
+
+Usage: compare_results.py <hermit.json> <oo_result.json> [--pellet <pellet.json>]
+
+<hermit.json> is JavaReasoner output: the FULL entailed named hierarchy (all
+superclasses plus equivalent classes) and the told closure. <oo_result.json> is
+the engine's `reason --profile owl-dl` result. The engine side is read from
+classification[].superclasses plus equivalences, never from a `subsumptions`
+key, which the engine does not emit. An earlier version read that key from the
+engine result, got an empty set, and compared HermiT's direct superclasses
+against nothing.
+
+The pair contract and the scoring are shared with run_ore.py, so the Pizza
+figure and the ORE figures mean the same thing.
+"""
+import argparse
import json
+import os
import sys
-
-def load_subsumptions(path):
- with open(path) as f:
- data = json.load(f)
- return set(data.get("subsumptions", [])), data.get("time_ms", 0), data.get("reasoner", "unknown")
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from run_ore import compare, engine_view, java_pairs, pct # noqa: E402
def main():
- if len(sys.argv) < 4:
- print("Usage: compare_results.py <hermit.json> <pellet.json> <oo.json>")
- sys.exit(1)
-
- hermit_subs, hermit_ms, _ = load_subsumptions(sys.argv[1])
- pellet_subs, pellet_ms, _ = load_subsumptions(sys.argv[2])
- oo_subs, oo_ms, _ = load_subsumptions(sys.argv[3])
-
- # Compare OO against HermiT (reference)
- oo_vs_hermit_missing = hermit_subs - oo_subs
- oo_vs_hermit_extra = oo_subs - hermit_subs
-
- # Compare OO against Pellet
- oo_vs_pellet_missing = pellet_subs - oo_subs
- oo_vs_pellet_extra = oo_subs - pellet_subs
-
- # Compare HermiT vs Pellet (baseline)
- hermit_vs_pellet_diff = hermit_subs.symmetric_difference(pellet_subs)
-
- print(f"{'Reasoner':<25} {'Time (ms)':<12} {'Subsumptions':<15}")
- print("-" * 52)
- print(f"{'HermiT':<25} {hermit_ms:<12} {len(hermit_subs):<15}")
- print(f"{'Pellet':<25} {pellet_ms:<12} {len(pellet_subs):<15}")
- print(f"{'Open Ontologies':<25} {oo_ms:<12} {len(oo_subs):<15}")
- print()
-
- if hermit_vs_pellet_diff:
- print(f"HermiT vs Pellet: {len(hermit_vs_pellet_diff)} differences (baseline)")
- else:
- print("HermiT vs Pellet: EXACT MATCH (baseline)")
-
+ ap = argparse.ArgumentParser()
+ ap.add_argument("hermit")
+ ap.add_argument("oo")
+ ap.add_argument("--pellet")
+ args = ap.parse_args()
+
+ hermit = json.load(open(args.hermit))
+ oo = json.load(open(args.oo))
+ if "subsumptions" not in hermit or "told_subsumptions" not in hermit:
+ sys.exit("ERROR: {} is not JavaReasoner output with the full hierarchy; "
+ "rebuild JavaReasoner.java".format(args.hermit))
+ if "classification" not in oo:
+ sys.exit("ERROR: {} has no classification; it is not an owl-dl reason result".format(args.oo))
+
+ view = engine_view(oo)
+ r = compare(view, hermit)
+
+ print("HermiT: load {} ms, create {} ms, classify {} ms (JVM start {} ms, excluded)".format(
+ hermit.get("load_ms"), hermit.get("reasoner_create_ms"), hermit.get("classify_ms"),
+ hermit.get("jvm_start_ms")))
+ print("Engine: reason {} ms (agents.total_time_ms), complete={}, undetermined={}, "
+ "budget_exhausted_in={}".format(view["reason_ms"], view["complete"],
+ len(view["undetermined"]), view["budget_exhausted_in"] or "none"))
print()
+ print("Gold (HermiT, all superclasses + equivalents): {}".format(r["gold"]))
+ print(" told closure (asserted hierarchy): {}".format(r["told"]))
+ print(" inferred only (gold minus told): {}".format(r["inferred_only"]))
+ if r["told_not_entailed"]:
+ print(" WARNING: {} told pairs HermiT does not entail; the told closure is wrong".format(
+ r["told_not_entailed"]))
+ print("Engine pairs: {}".format(r["engine_pairs"]))
+ print(" found in gold: {} recall {}".format(r["found"], pct(r["recall_all"])))
+ print(" found among inferred-only: {} recall {}".format(
+ r["found_inferred"], pct(r["recall_inferred"])))
+ print(" WRONG (engine claims, HermiT rejects): {}".format(len(r["wrong"])))
+ for p in r["wrong"][:20]:
+ print(" WRONG: {}".format(p))
+ print("Unsatisfiable: HermiT {}, engine {}; engine-only (wrong) {}, missed {}".format(
+ r["hermit_unsat"], r["engine_unsat"], len(r["wrong_unsat"]), len(r["missed_unsat"])))
+ for c in r["wrong_unsat"][:20]:
+ print(" WRONG UNSAT: {}".format(c))
+ if r["told_only"]:
+ print("NOTE: no inferred-only pairs; a structural walk scores 100% here, so this file proves nothing about reasoning")
+
+ if args.pellet:
+ pellet = json.load(open(args.pellet))
+ h, p = java_pairs(hermit["subsumptions"]), java_pairs(pellet.get("subsumptions") or [])
+ diff = h ^ p
+ print()
+ print("HermiT vs Pellet (baseline): {}".format(
+ "EXACT MATCH" if not diff else "{} differences".format(len(diff))))
- if not oo_vs_hermit_missing and not oo_vs_hermit_extra:
- print("OO vs HermiT: EXACT MATCH")
- else:
- print(f"OO vs HermiT: {len(oo_vs_hermit_missing)} missing, {len(oo_vs_hermit_extra)} extra")
- for s in sorted(oo_vs_hermit_missing)[:10]:
- print(f" MISSING: {s}")
- for s in sorted(oo_vs_hermit_extra)[:10]:
- print(f" EXTRA: {s}")
-
- if not oo_vs_pellet_missing and not oo_vs_pellet_extra:
- print("OO vs Pellet: EXACT MATCH")
- else:
- print(f"OO vs Pellet: {len(oo_vs_pellet_missing)} missing, {len(oo_vs_pellet_extra)} extra")
-
- # Summary
print()
- total_issues = len(oo_vs_hermit_missing) + len(oo_vs_hermit_extra)
- if total_issues == 0:
- print("RESULT: Open Ontologies produces identical classification to HermiT")
+ if r["wrong"] or r["wrong_unsat"]:
+ print("RESULT: {} wrong answers vs HermiT".format(len(r["wrong"]) + len(r["wrong_unsat"])))
else:
- print(f"RESULT: {total_issues} differences found vs HermiT reference")
+ print("RESULT: no wrong answers; {} of {} entailed pairs found ({} of {} inferred-only)".format(
+ r["found"], r["gold"], r["found_inferred"], r["inferred_only"]))
if __name__ == "__main__":
diff --git a/benchmark/reasoner/regressions/README.md b/benchmark/reasoner/regressions/README.md
index a0ba6412..3b031acb 100644
--- a/benchmark/reasoner/regressions/README.md
+++ b/benchmark/reasoner/regressions/README.md
@@ -33,8 +33,23 @@ This is why the LUBM benchmark never completes at any size: `generate_lubm.py`
emits one `owl:equivalentClass [ owl:hasValue ... ]` per department, so even the
1,000-axiom file carries dozens of nominals.
-The Pizza ontology contains no `owl:hasValue` and classifies in ~0.04s, so the
-defect is specific to nominals, not to scale.
+An earlier version of this file said the Pizza ontology contains no
+`owl:hasValue` and classifies in about 0.04s, and concluded that the defect is
+specific to nominals rather than to scale. That figure came from a stripped
+566-triple Pizza fixture, not from the reference file. The reference
+`benchmark/reference/pizza-reference.owl` carries six `owl:hasValue`
+restrictions and one `owl:oneOf` enumeration of five individuals (`Country`),
+counted as XML elements rather than lines, since `grep -c oneOf` also counts the
+closing tag and reports two. It is itself a nominal-bearing ontology and cannot
+separate nominals from scale.
+
+Measured on 2026-10-13 with a development build, `reason --profile owl-dl`
+over its 2,332 loaded triples did not complete: `complete: false`,
+`budget_exhausted_in: ["satisfiability", "abox"]`, 143 of 144 named classes
+undetermined, zero inferred subsumptions. Its run time is set by the phase
+budgets, not by classification finishing, so it is not quoted here. The
+conclusion that the blowup is specific to nominals rests on the table above
+alone, not on Pizza.
**Status: contained, not fixed.**
@@ -73,9 +88,10 @@ answer to give when you cannot decide.
ontologies. The fix is the NI-rule of Motik, Shearer and Horrocks, *Optimizing
the Nominal Introduction Rule in (Hyper)Tableau Calculi*, which bounds root
individual creation at `n` per `≤n R⁻.A` restriction instead of generating them
-freely. Separately, `update_blocking` implements ancestor **subset** blocking,
-Pairwise blocking, the second prerequisite noted here, has since been
-implemented: see `is_pairwise_blocked` in `src/tableaux.rs`. The NI-rule is
-still outstanding.
-restrictions are present (Horrocks and Sattler). Both are prerequisites for any
-published performance claim on a real corpus.
+freely. The second prerequisite was blocking: `update_blocking` implemented
+ancestor **subset** blocking, while SHIQ and SHOIQ require **pairwise**
+blocking once inverse roles and number restrictions are present (Horrocks and
+Sattler). Pairwise blocking has since been implemented, see
+`is_pairwise_blocked` in `src/tableaux.rs`. The NI-rule is still outstanding,
+and it remains a prerequisite for any published performance claim on a real
+corpus.
diff --git a/benchmark/reasoner/run_ore.py b/benchmark/reasoner/run_ore.py
new file mode 100644
index 00000000..c7d3e87c
--- /dev/null
+++ b/benchmark/reasoner/run_ore.py
@@ -0,0 +1,746 @@
+#!/usr/bin/env python3
+"""ORE 2015 classification benchmark: Open Ontologies against HermiT.
+
+Both reasoners read the SAME bytes. By default every ORE input (OWL Functional
+Syntax) is converted once to RDF/XML with the OWL API (Convert.java) and the
+converted file is given to both. With --native the original file is given to
+both instead, for when the engine reads Functional Syntax itself.
+
+The reference is HermiT's FULL entailed named-class hierarchy (all superclasses
+plus equivalent classes, see JavaReasoner.java), compared against the engine's
+classification[].superclasses plus its equivalences. The TOLD closure (the
+asserted named hierarchy, computed by the OWL API without a reasoner) is
+subtracted from the reference to give the INFERRED-only pairs. A file whose
+inferred-only set is empty is flagged told_only and kept out of the headline,
+because a structural walk of the asserted axioms scores 100% on it.
+
+Gates. A run reports no timing when its load line lacks triples_loaded or has
+it at 0, when its reason line carries an error or is missing, when the process
+exits non-zero, or when the driver's wall-clock cap kills it. --selftest feeds
+deliberately broken engine outputs through the same code and asserts that each
+gate fires.
+
+Python 3 standard library only.
+"""
+import argparse
+import json
+import os
+import shutil
+import signal
+import statistics
+import subprocess
+import sys
+import tempfile
+import time
+
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+DEFAULT_CORPUS = os.path.join(SCRIPT_DIR, "corpora", "ore2015", "pool_sample")
+DEFAULT_LIB = os.path.join(SCRIPT_DIR, "lib")
+DEFAULT_CLASSES = os.path.join(SCRIPT_DIR, "target", "java")
+DEFAULT_WORK = os.path.join(SCRIPT_DIR, "corpora", "ore2015", "converted")
+DEFAULT_OUT = os.path.join(SCRIPT_DIR, "results")
+JAVA_SOURCES = ("JavaReasoner.java", "Convert.java")
+
+OWL_THING = "http://www.w3.org/2002/07/owl#Thing"
+OWL_NOTHING = "http://www.w3.org/2002/07/owl#Nothing"
+
+
+# ---------------------------------------------------------------------------
+# Normalisation shared with compare_results.py
+# ---------------------------------------------------------------------------
+
+def norm_iri(term):
+ """Engine terms come as <iri> or _:bnode. Return a bare IRI or None."""
+ if not isinstance(term, str):
+ return None
+ t = term.strip()
+ if t.startswith("<") and t.endswith(">"):
+ t = t[1:-1]
+ if not t or t.startswith("_:"):
+ return None
+ return t
+
+
+def named_pair(sub, sup):
+ """A comparable (sub, sup) pair, or None if it falls outside the contract."""
+ a, b = norm_iri(sub), norm_iri(sup)
+ if a is None or b is None or a == b:
+ return None
+ if a in (OWL_THING, OWL_NOTHING) or b in (OWL_THING, OWL_NOTHING):
+ return None
+ return (a, b)
+
+
+def java_pairs(strings):
+ out = set()
+ for s in strings:
+ sub, _, sup = s.partition(" -> ")
+ p = named_pair(sub, sup)
+ if p:
+ out.add(p)
+ return out
+
+
+def engine_view(result):
+ """Reduce an engine `reason --profile owl-dl` result to comparable sets."""
+ pairs, dropped = set(), 0
+ for entry in result.get("classification") or []:
+ for sup in entry.get("superclasses") or []:
+ p = named_pair(entry.get("class"), sup)
+ if p:
+ pairs.add(p)
+ else:
+ dropped += 1
+ for eq in result.get("equivalences") or []:
+ for a, b in ((eq.get("class_a"), eq.get("class_b")),
+ (eq.get("class_b"), eq.get("class_a"))):
+ p = named_pair(a, b)
+ if p:
+ pairs.add(p)
+ unsat = {norm_iri(c) for c in result.get("unsatisfiable_classes") or []}
+ unsat.discard(None)
+ unsat -= {OWL_NOTHING}
+ undetermined = [c for c in result.get("undetermined_classes") or []]
+ return {
+ "pairs": pairs,
+ "pairs_dropped_out_of_contract": dropped,
+ "unsat": unsat,
+ "undetermined": undetermined,
+ "budget_exhausted_in": list(result.get("budget_exhausted_in") or []),
+ "complete": result.get("complete"),
+ "consistent": result.get("consistent"),
+ "named_classes": result.get("named_classes"),
+ "reason_ms": (result.get("agents") or {}).get("total_time_ms"),
+ }
+
+
+def compare(engine, hermit):
+ """Score one engine view against one HermiT result. Pure function."""
+ h_unsat = set(hermit.get("unsatisfiable") or [])
+ gold = {p for p in java_pairs(hermit.get("subsumptions") or []) if p[0] not in h_unsat}
+ told_raw = {p for p in java_pairs(hermit.get("told_subsumptions") or []) if p[0] not in h_unsat}
+ told = told_raw & gold
+ inferred = gold - told
+ e_pairs = {p for p in engine["pairs"] if p[0] not in h_unsat}
+ on_unsat = len(engine["pairs"]) - len(e_pairs)
+ found = e_pairs & gold
+ wrong = e_pairs - gold
+ return {
+ "gold": len(gold),
+ "told": len(told),
+ "told_not_entailed": len(told_raw - gold),
+ "inferred_only": len(inferred),
+ "engine_pairs": len(e_pairs),
+ "engine_pairs_on_hermit_unsat_classes": on_unsat,
+ "found": len(found),
+ "found_inferred": len(e_pairs & inferred),
+ "recall_all": (len(found) / len(gold)) if gold else None,
+ "recall_inferred": (len(e_pairs & inferred) / len(inferred)) if inferred else None,
+ "told_only": not inferred,
+ "wrong": sorted("{} -> {}".format(a, b) for a, b in wrong),
+ "hermit_unsat": len(h_unsat),
+ "engine_unsat": len(engine["unsat"]),
+ "wrong_unsat": sorted(engine["unsat"] - h_unsat),
+ "missed_unsat": sorted(h_unsat - engine["unsat"]),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Engine
+# ---------------------------------------------------------------------------
+
+def parse_engine_output(stdout):
+ """Pick the load and reason lines out of `batch -` output."""
+ load = reason = None
+ for line in stdout.splitlines():
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ obj = json.loads(line)
+ except ValueError:
+ continue
+ if obj.get("command") == "load" and load is None:
+ load = obj.get("result") or {}
+ elif obj.get("command") == "reason":
+ reason = obj.get("result") or {}
+ return load, reason
+
+
+def gate_engine_run(load, reason, returncode, timed_out):
+ """Return (status, detail). Only status 'ok' may carry a timing."""
+ if timed_out:
+ return "engine_timeout", "killed at the driver's wall-clock cap"
+ if load is None:
+ return "load_failed", "no load line in output"
+ if load.get("error"):
+ return "load_failed", "load error: {}".format(load["error"])[:300]
+ triples = load.get("triples_loaded")
+ if not isinstance(triples, int) or triples <= 0:
+ return "load_failed", "triples_loaded is {!r}".format(triples)
+ if reason is None:
+ return "engine_no_reason", "no reason line in output (exit {})".format(returncode)
+ if reason.get("error"):
+ return "reason_error", "reason error: {}".format(reason["error"])[:300]
+ if returncode != 0:
+ return "engine_exit", "exit code {}".format(returncode)
+ return "ok", ""
+
+
+def run_engine(binary, path, cap_s):
+ if any(c.isspace() for c in path):
+ raise SystemExit("ERROR: batch input paths may not contain whitespace: " + path)
+ script = "load {}\nreason --profile owl-dl\n".format(path)
+ start = time.monotonic()
+ proc = subprocess.Popen([binary, "batch", "-"], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, start_new_session=True)
+ timed_out = False
+ try:
+ out, err = proc.communicate(script, timeout=cap_s)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ out, err = proc.communicate()
+ wall_ms = int((time.monotonic() - start) * 1000)
+ load, reason = parse_engine_output(out or "")
+ status, detail = gate_engine_run(load, reason, proc.returncode, timed_out)
+ run = {
+ "status": status,
+ "detail": detail,
+ "triples_loaded": (load or {}).get("triples_loaded"),
+ "wall_ms": wall_ms if status == "ok" else None,
+ "stderr_tail": (err or "")[-300:] if status != "ok" else "",
+ }
+ if status == "ok":
+ view = engine_view(reason)
+ run["view"] = view
+ run["reason_ms"] = view["reason_ms"]
+ return run
+
+
+def run_signature(run):
+ if run["status"] != "ok":
+ return ("failed", run["status"])
+ v = run["view"]
+ return (tuple(sorted(v["pairs"])), tuple(sorted(v["unsat"])), tuple(sorted(v["undetermined"])))
+
+
+# ---------------------------------------------------------------------------
+# Java side
+# ---------------------------------------------------------------------------
+
+def java_cp(classes_dir, lib_dir):
+ return "{}{}{}".format(classes_dir, os.pathsep, os.path.join(lib_dir, "*"))
+
+
+def ensure_java_built(java, classes_dir, lib_dir):
+ javac = os.path.join(os.path.dirname(os.path.realpath(shutil.which(java) or java)), "javac")
+ if not os.path.exists(javac):
+ javac = shutil.which("javac") or "javac"
+ os.makedirs(classes_dir, exist_ok=True)
+ stale = []
+ for src in JAVA_SOURCES:
+ s = os.path.join(SCRIPT_DIR, src)
+ c = os.path.join(classes_dir, src.replace(".java", ".class"))
+ if not os.path.exists(c) or os.path.getmtime(c) < os.path.getmtime(s):
+ stale.append(s)
+ if stale:
+ r = subprocess.run([javac, "-nowarn", "-cp", os.path.join(lib_dir, "*"), "-d", classes_dir] + stale,
+ capture_output=True, text=True)
+ if r.returncode != 0:
+ raise SystemExit("ERROR: javac failed:\n" + r.stderr[-2000:])
+
+
+def convert(java, cp, src, dst, cap_s):
+ if os.path.exists(dst) and os.path.getmtime(dst) >= os.path.getmtime(src) and os.path.getsize(dst) > 0:
+ return None
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
+ tmp = dst + ".part"
+ try:
+ r = subprocess.run([java, "-cp", cp, "Convert", src, tmp], capture_output=True, text=True, timeout=cap_s)
+ except subprocess.TimeoutExpired:
+ return "conversion timed out"
+ if r.returncode != 0 or not os.path.exists(tmp) or os.path.getsize(tmp) == 0:
+ return "conversion failed: " + r.stderr.strip()[-300:]
+ os.replace(tmp, dst)
+ return None
+
+
+def run_hermit(java, cp, path, cap_s, out_json):
+ start = time.monotonic()
+ try:
+ r = subprocess.run([java, "-cp", cp, "JavaReasoner", "hermit", path, out_json],
+ capture_output=True, text=True, timeout=cap_s)
+ except subprocess.TimeoutExpired:
+ return None, "hermit_timeout", None
+ wall_ms = int((time.monotonic() - start) * 1000)
+ if r.returncode != 0 or not os.path.exists(out_json):
+ lines = [l.strip() for l in r.stderr.splitlines() if l.strip() and not l.strip().startswith("at ")
+ and not l.startswith("WARNING")]
+ cause = next((l for l in reversed(lines) if "Exception" in l or "Error" in l), lines[-1] if lines else "")
+ return None, "hermit_error: " + cause[:300], wall_ms
+ with open(out_json) as f:
+ return json.load(f), None, wall_ms
+
+
+# ---------------------------------------------------------------------------
+# Per-file evaluation and reporting
+# ---------------------------------------------------------------------------
+
+def evaluate_file(name, runs, hermit, hermit_error=None, hermit_wall_ms=None):
+ row = {"file": name, "hermit_error": hermit_error, "runs": []}
+ for r in runs:
+ row["runs"].append({k: v for k, v in r.items() if k != "view"})
+ first = runs[0]
+ row["triples_loaded"] = first.get("triples_loaded")
+ sigs = {run_signature(r) for r in runs}
+ row["repeats"] = len(runs)
+ row["identical_across_repeats"] = len(sigs) == 1 and all(r["status"] == "ok" for r in runs)
+ ok_runs = [r for r in runs if r["status"] == "ok"]
+ bad_runs = [r for r in runs if r["status"] != "ok"]
+ # One failed repeat withholds the timing for the whole file: a median over
+ # the runs that happened to finish would hide the ones that did not.
+ timed = ok_runs if not bad_runs else []
+ row["engine_wall_ms"] = int(statistics.median(r["wall_ms"] for r in timed)) if timed else None
+ reason_ms = [r["reason_ms"] for r in timed if isinstance(r.get("reason_ms"), (int, float))]
+ row["engine_reason_ms"] = int(statistics.median(reason_ms)) if reason_ms else None
+ if hermit is not None:
+ for k in ("jvm_start_ms", "load_ms", "reasoner_create_ms", "classify_ms"):
+ row["hermit_" + k] = hermit.get(k)
+ row["hermit_process_wall_ms"] = hermit_wall_ms
+ row["hermit_consistent"] = hermit.get("consistent")
+
+ if bad_runs:
+ row["status"] = bad_runs[0]["status"]
+ row["detail"] = "{} of {} runs: {}".format(len(bad_runs), len(runs), bad_runs[0]["detail"])
+ if hermit is not None and hermit.get("consistent", True):
+ # Show what was at stake, but score nothing: no recall, no timing.
+ empty = {"pairs": set(), "unsat": set()}
+ stake = compare(empty, hermit)
+ for k in ("gold", "told", "inferred_only"):
+ row[k] = stake[k]
+ return row
+ if hermit is None:
+ row["status"] = "hermit_failed"
+ row["detail"] = hermit_error
+ return row
+ if not hermit.get("consistent", True):
+ engine_says = first["view"]["consistent"]
+ row["engine_consistent"] = engine_says
+ row["wrong_consistency"] = engine_says is True
+ row["status"] = "hermit_inconsistent"
+ row["detail"] = ("HermiT finds the ontology inconsistent and the engine reports "
+ "consistent: {}".format(engine_says))
+ return row
+ v = first["view"]
+ row.update(compare(v, hermit))
+ row["undetermined"] = len(v["undetermined"])
+ row["budget_exhausted_in"] = v["budget_exhausted_in"]
+ row["engine_complete"] = v["complete"]
+ row["engine_pairs_dropped_out_of_contract"] = v["pairs_dropped_out_of_contract"]
+ if len(ok_runs) > 1:
+ # Recall is reported from the first run and the other runs are listed,
+ # but a wrong answer from ANY run is reported: a defect that shows up
+ # one time in three is still a defect.
+ per = [compare(r["view"], hermit) for r in ok_runs]
+ row["per_run"] = [{"engine_pairs": c["engine_pairs"], "found": c["found"],
+ "found_inferred": c["found_inferred"], "wrong": len(c["wrong"]),
+ "wrong_unsat": len(c["wrong_unsat"])} for c in per]
+ row["wrong"] = sorted(set().union(*(c["wrong"] for c in per)))
+ row["wrong_unsat"] = sorted(set().union(*(c["wrong_unsat"] for c in per)))
+ row["status"] = "told_only" if row["told_only"] else "ok"
+ return row
+
+
+def headline(rows):
+ scored = [r for r in rows if r.get("status") == "ok"]
+ told_only = [r["file"] for r in rows if r.get("status") == "told_only"]
+ failed = [(r["file"], r.get("status")) for r in rows if r.get("status") not in ("ok", "told_only")]
+ gold = sum(r["gold"] for r in scored)
+ inferred = sum(r["inferred_only"] for r in scored)
+ macro = [r["recall_inferred"] for r in scored if r.get("recall_inferred") is not None]
+ out = {
+ "files_total": len(rows),
+ "files_scored": len(scored),
+ "files_told_only_excluded": told_only,
+ "files_failed": failed,
+ "micro_recall_all": (sum(r["found"] for r in scored) / gold) if gold else None,
+ "micro_recall_inferred": (sum(r["found_inferred"] for r in scored) / inferred) if inferred else None,
+ "macro_recall_inferred": (statistics.mean(macro) if macro else None),
+ "wrong_pairs_total": sum(len(r.get("wrong") or []) for r in rows),
+ "wrong_unsat_total": sum(len(r.get("wrong_unsat") or []) for r in rows),
+ "wrong_consistency_files": [r["file"] for r in rows if r.get("wrong_consistency")],
+ "missed_unsat_total": sum(len(r.get("missed_unsat") or []) for r in rows),
+ "files_not_identical_across_repeats": [r["file"] for r in rows
+ if r.get("status") in ("ok", "told_only")
+ and not r["identical_across_repeats"]],
+ }
+ return out
+
+
+def md_cell(x):
+ return " ".join(str(x).split()).replace("|", "\\|")
+
+
+def pct(x):
+ return "n/a" if x is None else "{:.1f}%".format(100.0 * x)
+
+
+def cell(x):
+ return "n/a" if x is None else str(x)
+
+
+def markdown(meta, rows, head):
+ L = []
+ L.append("# ORE 2015 classification, track `{}`".format(meta["track"]))
+ L.append("")
+ L.append("Generated {} by `run_ore.py`. Engine `{}`. Input: {}. Engine wall-clock cap {} s, "
+ "repeats {}.".format(meta["generated"], meta["engine"],
+ "original OWL Functional Syntax (--native)" if meta["native"]
+ else "RDF/XML converted once by the OWL API, same file to both",
+ meta["engine_timeout_s"], meta["repeat"]))
+ L.append("")
+ L.append("Engine ms is the median wall clock of the whole `batch -` process (load plus reason). "
+ "Reason ms is the engine's own `agents.total_time_ms`. HermiT create and classify are "
+ "`createReasoner` and `precomputeInferences` only, excluding JVM start and parsing. "
+ "Gold is HermiT's full entailed named hierarchy; told is the asserted closure; inferred is "
+ "gold minus told. A dash in the timing columns means the run failed a gate and its time "
+ "is withheld.")
+ L.append("")
+ L.append("| file | triples | engine ms | reason ms | HermiT create / classify ms | gold | told | inferred "
+ "| engine pairs | recall all | recall inferred | wrong | unsat H/E | undetermined "
+ "| budget exhausted in | identical | status |")
+ L.append("|" + "---|" * 17)
+ for r in rows:
+ hc = "{} / {}".format(cell(r.get("hermit_reasoner_create_ms")), cell(r.get("hermit_classify_ms")))
+ L.append("| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |".format(
+ r["file"], cell(r.get("triples_loaded")),
+ r["engine_wall_ms"] if r.get("engine_wall_ms") is not None else "-",
+ r["engine_reason_ms"] if r.get("engine_reason_ms") is not None else "-",
+ hc, cell(r.get("gold")), cell(r.get("told")), cell(r.get("inferred_only")),
+ cell(r.get("engine_pairs")), pct(r.get("recall_all")), pct(r.get("recall_inferred")),
+ len(r["wrong"]) + len(r["wrong_unsat"]) if "wrong" in r else "n/a",
+ "{}/{}".format(r["hermit_unsat"], r["engine_unsat"]) if "hermit_unsat" in r else "n/a",
+ cell(r.get("undetermined")),
+ ",".join(r.get("budget_exhausted_in") or []) or "none" if "budget_exhausted_in" in r else "n/a",
+ "yes" if r["identical_across_repeats"] else "NO",
+ md_cell(r["status"] + (" ({})".format(r["detail"]) if r.get("detail") else ""))))
+ L.append("")
+ L.append("## Headline (files with status ok only; told_only files excluded)")
+ L.append("")
+ L.append("- files scored: {} of {}".format(head["files_scored"], head["files_total"]))
+ L.append("- told_only, excluded: {}".format(", ".join(head["files_told_only_excluded"]) or "none"))
+ L.append("- not scored (engine gate, HermiT failure or inconsistent reference): {}".format(", ".join("{} ({})".format(f, s) for f, s in head["files_failed"]) or "none"))
+ L.append("- micro recall, inferred-only pairs: {}".format(pct(head["micro_recall_inferred"])))
+ L.append("- micro recall, all pairs: {}".format(pct(head["micro_recall_all"])))
+ L.append("- wrong subsumption pairs, all files: {}".format(head["wrong_pairs_total"]))
+ L.append("- wrong unsatisfiability claims, all files: {}".format(head["wrong_unsat_total"]))
+ L.append("- unsatisfiable classes HermiT finds and the engine does not, all files: {}".format(
+ head["missed_unsat_total"]))
+ L.append("- engine reports consistent where HermiT finds inconsistency: {}".format(
+ ", ".join(head["wrong_consistency_files"]) or "none"))
+ L.append("- not identical across repeats: {}".format(", ".join(head["files_not_identical_across_repeats"]) or "none"))
+ wrong_rows = [r for r in rows if r.get("wrong") or r.get("wrong_unsat")]
+ if wrong_rows:
+ L.append("")
+ L.append("## Wrong answers (engine claims, HermiT rejects)")
+ for r in wrong_rows:
+ L.append("")
+ L.append("`{}`:".format(r["file"]))
+ for p in r.get("wrong", [])[:25]:
+ L.append("- {}".format(p))
+ if len(r.get("wrong", [])) > 25:
+ L.append("- ... {} more in the JSON".format(len(r["wrong"]) - 25))
+ for c in r.get("wrong_unsat", []):
+ L.append("- unsatisfiable claimed: {}".format(c))
+ L.append("")
+ return "\n".join(L)
+
+
+# ---------------------------------------------------------------------------
+# Self-test: the gates must be able to fail
+# ---------------------------------------------------------------------------
+
+def selftest():
+ ns = "http://selftest.example/"
+ A, B, C, D = (ns + x for x in "ABCD")
+ hermit = {
+ "consistent": True, "unsatisfiable": [],
+ # Told: A -> B -> C. Inferred by reasoning: D -> C.
+ "subsumptions": ["{} -> {}".format(A, B), "{} -> {}".format(A, C), "{} -> {}".format(B, C),
+ "{} -> {}".format(D, C)],
+ "told_subsumptions": ["{} -> {}".format(A, B), "{} -> {}".format(A, C), "{} -> {}".format(B, C)],
+ "reasoner_create_ms": 1, "classify_ms": 1,
+ }
+ hermit_told_only = dict(hermit, subsumptions=hermit["told_subsumptions"])
+
+ def reason(classification, **extra):
+ r = {"named_classes": 4, "classification": classification, "equivalences": [],
+ "unsatisfiable_classes": [], "undetermined_classes": [], "budget_exhausted_in": [],
+ "complete": True, "consistent": True, "agents": {"total_time_ms": 5}}
+ r.update(extra)
+ return r
+
+ def cls(c, *sups):
+ return {"class": "<{}>".format(c), "superclasses": ["<{}>".format(s) for s in sups]}
+
+ correct = [cls(A, B, C), cls(B, C), cls(D, C)]
+ structural = [cls(A, B, C), cls(B, C)]
+ load_ok = {"command": "load", "result": {"ok": True, "triples_loaded": 12}, "seq": 0}
+
+ def lines(*objs):
+ return "\n".join(json.dumps(o) for o in objs) + "\n"
+
+ def reason_line(r):
+ return {"command": "reason", "result": r, "seq": 1}
+
+ tmp = tempfile.mkdtemp(prefix="run_ore_selftest_")
+ counter = os.path.join(tmp, "counter")
+
+ def fake(name, body):
+ p = os.path.join(tmp, name)
+ with open(p, "w") as f:
+ f.write("#!{}\nimport sys, json, time, os\nsys.stdin.read()\n{}\n".format(sys.executable, body))
+ os.chmod(p, 0o755)
+ return p
+
+ def emit(text):
+ return "sys.stdout.write({!r})".format(text)
+
+ engines = {
+ "correct": fake("correct", emit(lines(load_ok, reason_line(reason(correct))))),
+ "structural": fake("structural", emit(lines(load_ok, reason_line(reason(structural))))),
+ "empty_classification": fake("empty_cls", emit(lines(load_ok, reason_line(reason([]))))),
+ "fabricated_pair": fake("fabricated", emit(lines(load_ok, reason_line(
+ reason(correct + [cls(C, A)] + [{"class": "_:b0", "superclasses": ["<{}>".format(A)]}]))))),
+ "wrong_unsat": fake("wrong_unsat", emit(lines(load_ok, reason_line(
+ reason(correct, unsatisfiable_classes=["<{}>".format(D)]))))),
+ "empty_load": fake("empty_load", emit(lines(
+ {"command": "load", "result": {"ok": True, "triples_loaded": 0}, "seq": 0},
+ reason_line(reason([]))))),
+ "load_error": fake("load_error", emit(lines(
+ {"command": "load", "result": {"error": "Unexpected text event"}, "seq": 0},
+ reason_line(reason([]))))),
+ "missing_triples": fake("missing_triples", emit(lines(
+ {"command": "load", "result": {"ok": True}, "seq": 0}, reason_line(reason(correct))))),
+ "reason_error": fake("reason_error", emit(lines(load_ok, reason_line({"error": "boom"})))),
+ "crash": fake("crash", emit(lines(load_ok)) + "\nsys.exit(101)"),
+ "timeout": fake("timeout", "time.sleep(30)\n" + emit(lines(load_ok, reason_line(reason(correct))))),
+ "hang_on_second": fake("hang2", "p={!r}\nn=int(open(p).read()) if os.path.exists(p) else 0\n"
+ "open(p,'w').write(str(n+1))\n"
+ "time.sleep(30 if n == 1 else 0)\n"
+ "sys.stdout.write({!r})".format(
+ counter + "2", lines(load_ok, reason_line(reason(correct))))),
+ "wrong_on_second": fake("wrong2", "p={!r}\nn=int(open(p).read()) if os.path.exists(p) else 0\n"
+ "open(p,'w').write(str(n+1))\n"
+ "sys.stdout.write({!r} if n == 1 else {!r})".format(
+ counter + "3",
+ lines(load_ok, reason_line(reason(correct + [cls(C, A)]))),
+ lines(load_ok, reason_line(reason(correct))))),
+ "flaky": fake("flaky", "p={!r}\nn=int(open(p).read()) if os.path.exists(p) else 0\n"
+ "open(p,'w').write(str(n+1))\n"
+ "sys.stdout.write({!r} if n % 2 == 0 else {!r})".format(
+ counter, lines(load_ok, reason_line(reason(correct))),
+ lines(load_ok, reason_line(reason(structural))))),
+ }
+ dummy = os.path.join(tmp, "input.owl")
+ open(dummy, "w").close()
+
+ def go(name, ref=hermit, repeat=1, cap=10):
+ runs = [run_engine(engines[name], dummy, cap) for _ in range(repeat)]
+ return evaluate_file(name, runs, ref)
+
+ checks = []
+
+ def check(label, cond, got):
+ checks.append((label, bool(cond), got))
+
+ r = go("correct", repeat=3)
+ check("positive control: correct engine scores 100% inferred recall, 0 wrong, ok, identical",
+ r["status"] == "ok" and r["recall_inferred"] == 1.0 and not r["wrong"] and r["identical_across_repeats"]
+ and r["engine_wall_ms"] is not None,
+ (r["status"], r["recall_inferred"], r["wrong"], r["identical_across_repeats"]))
+ r = go("structural")
+ check("structural walk: 100% on told, 0% on inferred-only",
+ r["recall_inferred"] == 0.0 and r["found"] == r["told"] == 3,
+ (r["recall_inferred"], r["found"], r["told"]))
+ r = go("empty_classification")
+ check("empty classification: reported as 0 pairs and 0% recall, not as missing",
+ r["status"] == "ok" and r["engine_pairs"] == 0 and r["recall_all"] == 0.0 and r["recall_inferred"] == 0.0,
+ (r["status"], r["engine_pairs"], r["recall_all"]))
+ r = go("fabricated_pair")
+ check("fabricated pair C -> A is listed as WRONG; blank-node pair is dropped, not scored",
+ r["wrong"] == ["{} -> {}".format(C, A)] and r["engine_pairs_dropped_out_of_contract"] == 1,
+ (r["wrong"], r["engine_pairs_dropped_out_of_contract"]))
+ r = go("wrong_unsat")
+ check("engine claims D unsatisfiable, HermiT says satisfiable: listed as wrong_unsat",
+ r["wrong_unsat"] == [D], r["wrong_unsat"])
+ for name, want in (("empty_load", "load_failed"), ("load_error", "load_failed"),
+ ("missing_triples", "load_failed"), ("reason_error", "reason_error"),
+ ("crash", "engine_no_reason")):
+ r = go(name)
+ check("{}: status {} and timing withheld".format(name, want),
+ r["status"] == want and r["engine_wall_ms"] is None and "recall_all" not in r,
+ (r["status"], r["engine_wall_ms"]))
+ t0 = time.monotonic()
+ r = go("timeout", cap=1)
+ check("timeout: killed at the 1 s cap, status engine_timeout, timing withheld",
+ r["status"] == "engine_timeout" and r["engine_wall_ms"] is None and time.monotonic() - t0 < 10,
+ (r["status"], r["engine_wall_ms"]))
+ r = go("hang_on_second", repeat=3, cap=1)
+ check("one repeat of three hangs: file status engine_timeout, no timing from the other two",
+ r["status"] == "engine_timeout" and r["engine_wall_ms"] is None and "recall_all" not in r,
+ (r["status"], r["engine_wall_ms"], r.get("detail")))
+ r = go("wrong_on_second", repeat=3)
+ check("a fabricated pair in the second of three runs only is still listed as WRONG",
+ r["wrong"] == ["{} -> {}".format(C, A)] and r["identical_across_repeats"] is False,
+ (r["wrong"], r["identical_across_repeats"]))
+ r = go("flaky", repeat=3)
+ check("flaky engine: identical_across_repeats is False", r["identical_across_repeats"] is False,
+ r["identical_across_repeats"])
+ r = go("correct", ref=dict(hermit, consistent=False, subsumptions=[], told_subsumptions=[]))
+ check("inconsistent reference: an engine reporting consistent is flagged wrong_consistency",
+ r["status"] == "hermit_inconsistent" and r["wrong_consistency"] is True,
+ (r["status"], r.get("wrong_consistency")))
+ r_told = go("structural", ref=hermit_told_only)
+ check("told_only file: flagged, scores 100% recall, excluded from headline",
+ r_told["status"] == "told_only" and r_told["recall_all"] == 1.0, (r_told["status"], r_told["recall_all"]))
+ r_ok = go("structural")
+ h = headline([r_told, r_ok, go("empty_load")])
+ check("headline: told_only excluded, failed run listed, recall from the scored file only",
+ h["files_scored"] == 1 and h["files_told_only_excluded"] == ["structural"]
+ and h["files_failed"] == [("empty_load", "load_failed")] and h["micro_recall_inferred"] == 0.0,
+ h)
+
+ shutil.rmtree(tmp, ignore_errors=True)
+ failed = 0
+ for label, ok, got in checks:
+ print("{} {}".format("PASS" if ok else "FAIL", label))
+ if not ok:
+ failed += 1
+ print(" got: {}".format(got))
+ print("{} of {} self-test checks passed".format(len(checks) - failed, len(checks)))
+ return 1 if failed else 0
+
+
+# ---------------------------------------------------------------------------
+# Main
+# ---------------------------------------------------------------------------
+
+def select_files(args):
+ order_path = os.path.join(args.corpus, args.track, "classification", "fileorder.txt")
+ with open(order_path) as f:
+ order = [l.strip() for l in f if l.strip()]
+ if args.files:
+ names = list(args.files)
+ elif args.file_list:
+ with open(args.file_list) as f:
+ names = [l.strip() for l in f if l.strip()]
+ else:
+ names = order
+ unknown = [n for n in names if n not in order]
+ if unknown:
+ raise SystemExit("ERROR: not in {} fileorder.txt: {}".format(args.track, ", ".join(unknown)))
+ files_dir = os.path.join(args.corpus, "files")
+ if args.max_bytes:
+ names = [n for n in names if os.path.getsize(os.path.join(files_dir, n)) <= args.max_bytes]
+ if args.sort_by_size:
+ names.sort(key=lambda n: os.path.getsize(os.path.join(files_dir, n)))
+ if args.limit:
+ names = names[:args.limit]
+ return names
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("--track", choices=("el", "dl", "pure_dl"))
+ ap.add_argument("--files", nargs="+", help="file names from the track's fileorder.txt")
+ ap.add_argument("--file-list", help="text file with one ORE file name per line")
+ ap.add_argument("--limit", type=int, help="take the first N files after filtering")
+ ap.add_argument("--max-bytes", type=int, help="skip inputs larger than this")
+ ap.add_argument("--sort-by-size", action="store_true", help="smallest inputs first")
+ ap.add_argument("--engine", default=os.environ.get("OO_BIN", "open-ontologies"))
+ ap.add_argument("--java", default=os.environ.get("JAVA", "java"))
+ ap.add_argument("--corpus", default=DEFAULT_CORPUS, help="ORE pool_sample directory")
+ ap.add_argument("--lib", default=DEFAULT_LIB, help="directory of OWL API and HermiT jars")
+ ap.add_argument("--classes-dir", default=DEFAULT_CLASSES)
+ ap.add_argument("--work-dir", default=DEFAULT_WORK, help="cache for converted RDF/XML")
+ ap.add_argument("--out-dir", default=DEFAULT_OUT)
+ ap.add_argument("--engine-timeout", type=float, default=120.0, help="seconds per engine run")
+ ap.add_argument("--hermit-timeout", type=float, default=300.0, help="seconds per HermiT run")
+ ap.add_argument("--repeat", type=int, default=3)
+ ap.add_argument("--native", action="store_true",
+ help="feed the original OWL Functional Syntax file to both reasoners")
+ ap.add_argument("--tag", default="", help="label appended to output file names")
+ ap.add_argument("--selftest", action="store_true")
+ args = ap.parse_args()
+
+ if args.selftest:
+ sys.exit(selftest())
+ if not args.track:
+ ap.error("--track is required unless --selftest")
+ if args.repeat < 1:
+ ap.error("--repeat must be at least 1")
+
+ names = select_files(args)
+ if not names:
+ raise SystemExit("ERROR: no files selected")
+ ensure_java_built(args.java, args.classes_dir, args.lib)
+ cp = java_cp(args.classes_dir, args.lib)
+ os.makedirs(args.out_dir, exist_ok=True)
+ scratch = tempfile.mkdtemp(prefix="run_ore_")
+
+ rows = []
+ for i, name in enumerate(names, 1):
+ src = os.path.abspath(os.path.join(args.corpus, "files", name))
+ if args.native:
+ path = src
+ else:
+ path = os.path.abspath(os.path.join(args.work_dir, name.rsplit(".", 1)[0] + ".rdf"))
+ err = convert(args.java, cp, src, path, args.hermit_timeout)
+ if err:
+ rows.append({"file": name, "status": "conversion_failed", "detail": err,
+ "identical_across_repeats": False, "engine_wall_ms": None})
+ print("[{}/{}] {}: {}".format(i, len(names), name, err), file=sys.stderr)
+ continue
+ hermit, herr, hwall = run_hermit(args.java, cp, path, args.hermit_timeout,
+ os.path.join(scratch, name + ".hermit.json"))
+ runs = [run_engine(args.engine, path, args.engine_timeout) for _ in range(args.repeat)]
+ row = evaluate_file(name, runs, hermit, herr, hwall)
+ row["input"] = path
+ row["input_bytes"] = os.path.getsize(path)
+ rows.append(row)
+ print("[{}/{}] {}: {} engine={} ms gold={} inferred={} recall_inferred={} wrong={}".format(
+ i, len(names), name, row["status"], cell(row.get("engine_wall_ms")), cell(row.get("gold")),
+ cell(row.get("inferred_only")), pct(row.get("recall_inferred")),
+ len(row.get("wrong") or [])), file=sys.stderr)
+
+ shutil.rmtree(scratch, ignore_errors=True)
+ head = headline(rows)
+ meta = {
+ "generated": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
+ "track": args.track, "engine": os.path.abspath(args.engine) if os.path.exists(args.engine) else args.engine,
+ "native": args.native, "repeat": args.repeat, "engine_timeout_s": args.engine_timeout,
+ "hermit_timeout_s": args.hermit_timeout, "corpus": os.path.abspath(args.corpus),
+ "pair_contract": "named classes only; all entailed superclasses plus equivalents; "
+ "owl:Thing and owl:Nothing excluded; HermiT-unsatisfiable subclasses excluded",
+ }
+ stem = "ore_{}_{}{}".format(args.track, time.strftime("%Y%m%d_%H%M%S"),
+ "_" + args.tag if args.tag else "")
+ jpath = os.path.join(args.out_dir, stem + ".json")
+ mpath = os.path.join(args.out_dir, stem + ".md")
+ with open(jpath, "w") as f:
+ json.dump({"meta": meta, "headline": head, "files": rows}, f, indent=1)
+ md = markdown(meta, rows, head)
+ with open(mpath, "w") as f:
+ f.write(md)
+ print(md)
+ print("wrote {}\nwrote {}".format(jpath, mpath), file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmark/reasoner/run_pizza_correctness.sh b/benchmark/reasoner/run_pizza_correctness.sh
index 2ae4fd66..d5b04836 100755
--- a/benchmark/reasoner/run_pizza_correctness.sh
+++ b/benchmark/reasoner/run_pizza_correctness.sh
@@ -1,10 +1,13 @@
#!/bin/bash
-set -e
+set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
BENCHMARK_DIR="$SCRIPT_DIR/.."
-PIZZA_OWL="$BENCHMARK_DIR/reference/pizza-reference.owl"
+PIZZA_OWL="${PIZZA_OWL:-$BENCHMARK_DIR/reference/pizza-reference.owl}"
OO_BIN="${OO_BIN:-open-ontologies}"
-RESULTS_DIR="$SCRIPT_DIR/results"
+JAVA="${JAVA:-java}"
+LIB_DIR="${LIB_DIR:-$SCRIPT_DIR/lib}"
+CLASSES_DIR="$SCRIPT_DIR/target/java"
+RESULTS_DIR="${RESULTS_DIR:-$SCRIPT_DIR/results}"
mkdir -p "$RESULTS_DIR"
@@ -19,55 +22,95 @@ fi
# 1. Open Ontologies
#
# `load` and `reason` must run in ONE process. The store is in memory and dies
-# with the process, so invoking them separately reasoned over an empty graph
-# and wrote a result that described nothing, while the script exited 0 and the
-# comparison downstream treated it as a measurement. `batch -` keeps one
-# process alive across both commands, which is what benchmark/lubm already
-# does (see run_lubm.py:90).
+# with the process, so invoking them separately reasoned over an empty graph.
+# `batch -` keeps one process alive across both commands.
echo "Running Open Ontologies (owl-dl)..."
+# The engine exits non-zero when any batch command fails. Capture the status
+# instead of letting `set -e` end the script silently, so the gate below can
+# say which command failed.
+set +e
printf '%s\n' "load $PIZZA_OWL" "reason --profile owl-dl" \
| $OO_BIN batch - > "$RESULTS_DIR/oo_batch.json"
+OO_STATUS=$?
+set -e
-# Take the reason result, which is the last line, and refuse to continue on an
-# empty graph rather than reporting a correctness figure derived from nothing.
-python3 - "$RESULTS_DIR/oo_batch.json" "$RESULTS_DIR/oo_result.json" <<'PY'
+# Gate the run before anything downstream reads it. The load line must report
+# triples_loaded > 0 and carry no error, and the reason line must carry no
+# error and report a non-zero class count under `named_classes`, a key the
+# owl-dl result actually has. (An earlier version read `classes` or
+# `class_count`, neither of which exists, so it aborted on every real run.)
+python3 - "$RESULTS_DIR/oo_batch.json" "$RESULTS_DIR/oo_result.json" "$OO_STATUS" <<'PY'
import json, sys
-lines = [l for l in open(sys.argv[1]) if l.strip()]
-if not lines:
- sys.exit("ERROR: batch produced no output")
-result = json.loads(lines[-1])
-if result.get("error"):
- sys.exit("ERROR: reason failed: {}".format(result["error"]))
-classes = result.get("classes") or result.get("class_count") or 0
-if not classes:
- sys.exit("ERROR: reasoned over an empty graph. The load step did not "
- "reach the reasoner, so any number printed here would be "
- "meaningless. Check that `batch` accepted the load command.")
-json.dump(result, open(sys.argv[2], "w"), indent=1)
-print(" {} classes reasoned.".format(classes))
+load = reason = None
+for line in open(sys.argv[1]):
+ if not line.strip():
+ continue
+ obj = json.loads(line)
+ if obj.get("command") == "load":
+ load = obj.get("result") or {}
+ elif obj.get("command") == "reason":
+ reason = obj.get("result") or {}
+if load is None:
+ sys.exit("ERROR: batch produced no load line")
+if load.get("error"):
+ sys.exit("ERROR: load failed: {}".format(load["error"]))
+triples = load.get("triples_loaded")
+if not isinstance(triples, int) or triples <= 0:
+ sys.exit("ERROR: load reported triples_loaded={!r}. The reasoner would run "
+ "over an empty graph, so no figure is written.".format(triples))
+if reason is None:
+ sys.exit("ERROR: batch produced no reason line")
+if reason.get("error"):
+ sys.exit("ERROR: reason failed: {}".format(reason["error"]))
+classes = reason.get("named_classes")
+if classes is None:
+ classes = ((reason.get("agents") or {}).get("satisfiability_agent") or {}).get("classes_checked")
+if not isinstance(classes, int) or classes <= 0:
+ sys.exit("ERROR: reason result reports {!r} named classes over {} loaded "
+ "triples; refusing to write a result.".format(classes, triples))
+if sys.argv[3] != "0":
+ sys.exit("ERROR: the engine exited with status {}".format(sys.argv[3]))
+reason["triples_loaded"] = triples
+json.dump(reason, open(sys.argv[2], "w"), indent=1)
+print(" {} triples loaded, {} named classes reasoned, complete={}.".format(
+ triples, classes, reason.get("complete")))
PY
echo " Done."
-# 2. HermiT
-if ls "$SCRIPT_DIR/lib/"*.jar 1>/dev/null 2>&1; then
- echo "Running HermiT..."
- java -cp "$SCRIPT_DIR:$SCRIPT_DIR/lib/*" JavaReasoner hermit "$PIZZA_OWL" "$RESULTS_DIR/hermit_result.json"
-
- # 3. Pellet
- echo "Running Pellet..."
- java -cp "$SCRIPT_DIR:$SCRIPT_DIR/lib/*" JavaReasoner pellet "$PIZZA_OWL" "$RESULTS_DIR/pellet_result.json"
-
- # 4. Compare
- echo ""
- echo "Comparing results..."
- python3 "$SCRIPT_DIR/compare_results.py" \
- "$RESULTS_DIR/hermit_result.json" \
- "$RESULTS_DIR/pellet_result.json" \
- "$RESULTS_DIR/oo_result.json"
-else
+# 2. Java reasoners
+if ! ls "$LIB_DIR/"*.jar 1>/dev/null 2>&1; then
echo ""
- echo "SKIPPING Java reasoners (no jars in $SCRIPT_DIR/lib/)"
+ echo "SKIPPING Java reasoners (no jars in $LIB_DIR)"
echo "See README.md for setup instructions."
echo ""
echo "Open Ontologies result saved to $RESULTS_DIR/oo_result.json"
+ exit 0
fi
+
+mkdir -p "$CLASSES_DIR"
+JAVAC="$(dirname "$(command -v "$JAVA")")/javac"
+[ -x "$JAVAC" ] || JAVAC=javac
+"$JAVAC" -nowarn -cp "$LIB_DIR/*" -d "$CLASSES_DIR" "$SCRIPT_DIR/JavaReasoner.java"
+CP="$CLASSES_DIR:$LIB_DIR/*"
+
+echo "Running HermiT..."
+"$JAVA" -cp "$CP" JavaReasoner hermit "$PIZZA_OWL" "$RESULTS_DIR/hermit_result.json"
+
+PELLET_ARG=()
+if ls "$LIB_DIR"/pellet-*.jar "$LIB_DIR"/openllet-*.jar 1>/dev/null 2>&1; then
+ echo "Running Pellet..."
+ "$JAVA" -cp "$CP" JavaReasoner pellet "$PIZZA_OWL" "$RESULTS_DIR/pellet_result.json"
+ PELLET_ARG=(--pellet "$RESULTS_DIR/pellet_result.json")
+else
+ echo "Skipping Pellet (no pellet-*.jar or openllet-*.jar in $LIB_DIR)."
+fi
+
+# 3. Compare. Both sides are the FULL entailed named hierarchy: JavaReasoner
+# emits all superclasses plus equivalents, and compare_results.py reads the
+# engine's classification[].superclasses plus its equivalences.
+echo ""
+echo "Comparing results..."
+python3 "$SCRIPT_DIR/compare_results.py" \
+ "$RESULTS_DIR/hermit_result.json" \
+ "$RESULTS_DIR/oo_result.json" \
+ ${PELLET_ARG[@]+"${PELLET_ARG[@]}"}