eyemind 0.8.33 → 0.8.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LS-SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The Logic Script (LS) Language and Proof Format
5
- Version: eyemind 0.8.33
5
+ Version: eyemind 0.8.35
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/README.md CHANGED
@@ -306,9 +306,11 @@ class; later messages of that shape only add their own facts. The result is
306
306
  the same as running the whole program over the background and the message,
307
307
  and the whole program runs instead when new triples could have any property,
308
308
  as `owl:sameAs` between individuals makes, or when a negation could retract
309
- a background conclusion. `--program` prints the specialized program of each
310
- new shape, and `--stats` says whether each message used one. Streamed
311
- messages have no proofs.
309
+ a background conclusion. With `--qudt`, the compiler reads the units and
310
+ metadata of each message and runs the whole program for it. SHACL contracts
311
+ still filter the input of closed shapes and project the output.
312
+ `--program` prints the specialized program of each new shape, and `--stats`
313
+ says whether each message used one. Streamed messages have no proofs.
312
314
 
313
315
  An [output contract](#rdf-logic-profiles) prunes the specialized rules to
314
316
  those that can contribute to a triple it asks for, following premises back
@@ -331,11 +333,11 @@ a message whose triples are all instances of them uses that program, and one
331
333
  with other triples gets rules of its own shape. When every input shape is
332
334
  closed, a message triple whose property no shape names or ignores is dropped
333
335
  first; `--stats` reports `conforms` and `dropped` per message.
334
- `--shacl-out FILE` reads output shapes as an output contract: each property
335
- shape asks for triples of its path, of the values it allows, and only rules
336
- concluding those, or what such a rule reads, stay. A variable property or
337
- class in a rule takes the values its schema premise has in the background, as
338
- partial evaluation gives them. Planned rules derive what the shapes lead to,
336
+ `--shacl-out FILE` reads output shapes as an output contract. Each property
337
+ shape asks for triples of its path with the values it allows. Planning
338
+ keeps rules that conclude those triples and rules they depend on. A variable
339
+ property or class in a rule takes the values its schema premise has in the
340
+ background, as partial evaluation gives them. Planned rules derive what the shapes lead to,
339
341
  not every OWL 2 RL consequence: equality that the output does not ask for is
340
342
  not derived. See the
341
343
  [shape-planning](https://eyereasoner.github.io/eyemind/examples/deck/shape-planning-owl2rl) deck.
@@ -392,8 +394,9 @@ query(rdf(O, iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), sosa('Obser
392
394
  an offline catalog adapted from [QUDT.org](https://qudt.org/) (CC BY 4.0):
393
395
  `"36 km/h"^^cdt:speed` yields `"10.0 m/s"^^cdt:speed`. Input metadata adds
394
396
  units: with `qudt:conversionMultiplier` and `qudt:hasDimensionVector`,
395
- composed from QUDT units with `qudt:hasFactorUnit` or `qudt:prefix` and
396
- `qudt:scalingOf`, or aligned with `owl:sameAs` or `skos:exactMatch`. The
397
+ composed from QUDT units with `qudt:hasFactorUnit` and an optional
398
+ `qudt:factorUnitScalar`, derived from `qudt:prefix` and `qudt:scalingOf`,
399
+ or aligned with `owl:sameAs` or `skos:exactMatch`. The
397
400
  other units of the QUDT unit vocabulary with a fixed conversion, such as
398
401
  `unit:W-PER-M2`, come from an offline catalog that `tools/qudt-catalog.js`
399
402
  generates from a QUDT release, also by the UCUM code of a CDT literal. A
@@ -402,8 +405,12 @@ query(rdf(O, iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), sosa('Obser
402
405
  separate runs agree: one that shares a quantity kind with it (QUDT's, or
403
406
  those the input states with `qudt:hasQuantityKind`), then one of SI base
404
407
  units, then the one with the fewest UCUM factors. So kW/m² is W/m² in any
405
- run, and a radiance stays W/(m²·sr). A quantity whose unit cannot be
406
- resolved, such as a currency, is reported with `qconv:unresolvedUnit`.
408
+ run, and a radiance stays W/(m²·sr). A property can choose another unit
409
+ with `qconv:normalizationProfile`. That profile supplies `qconv:targetUnit`,
410
+ `qconv:targetUcumCode` and `qconv:datatype`.
411
+ `qconv:unresolvedUnit` reports quantity values whose units lack a usable
412
+ conversion, including composed units whose multipliers are zero or
413
+ overflow binary64.
407
414
  - `--skos` adds positive [SKOS Core](https://www.w3.org/TR/skos-reference/)
408
415
  entailments, without integrity checks or SKOS-XL.
409
416
  - `--shacl` compiles shapes to LS and writes a standard `sh:ValidationReport`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.8.33",
3
+ "version": "0.8.35",
4
4
  "description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3), SPARQL 1.2 RL (SRL) and Logical English (LE) interoperability.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/qudt.js CHANGED
@@ -10,6 +10,10 @@ const U = 'http://qudt.org/vocab/unit/';
10
10
  const C = 'https://eyereasoner.github.io/eyemind/qudt#';
11
11
  const D = 'http://qudt.org/vocab/dimensionvector/';
12
12
  const K = 'http://qudt.org/vocab/quantitykind/';
13
+ const SAME_AS = 'http://www.w3.org/2002/07/owl#sameAs';
14
+ const EXACT_MATCH = 'http://www.w3.org/2004/02/skos/core#exactMatch';
15
+ const ALIGNED_UNIT = C + 'alignedQudtUnit';
16
+ const TARGET_UNIT = C + 'targetUnit';
13
17
  const dimensions = {
14
18
  length: 'A0E0L1I0M0H0T0D0', area: 'A0E0L2I0M0H0T0D0', volume: 'A0E0L3I0M0H0T0D0',
15
19
  time: 'A0E0L0I0M0H0T1D0', mass: 'A0E0L0I0M1H0T0D0', speed: 'A0E0L1I0M0H0T-1D0',
@@ -90,7 +94,7 @@ implied_by(qu_dimension(U, G, iri('http://qudt.org/vocab/dimensionvector/A0E0L0I
90
94
  implied_by(qu_token(T, U, G), qu_builtin_token(T, U));
91
95
  for (const p of ['symbol', 'ucumCode', 'expression']) implied_by(qu_token(T, U, G), [ent_base(U, qu(p), L, G), srl_str(L, literal(T, datatype(quString)))]);
92
96
  implied_by(qu_align(U, U, G), qu_dimension(U, G, _));
93
- for (const p of [iri('http://www.w3.org/2002/07/owl#sameAs'), iri('http://www.w3.org/2004/02/skos/core#exactMatch'), qc('alignedQudtUnit')]) {
97
+ for (const p of [iri('${SAME_AS}'), iri('${EXACT_MATCH}'), qc('alignedQudtUnit')]) {
94
98
  implied_by(qu_align(Local, U, G), [rdf(Local, p, U, G), qu_dimension(U, G, _)]);
95
99
  }
96
100
  implied_by(qu_custom_profile(P, G), ent_base(P, qc('targetUnit'), _, G));
@@ -163,6 +167,7 @@ const exact = (n) => {
163
167
  const rounded = Number(n.toPrecision(15));
164
168
  return rounded.toExponential().replace(/e.*$/, '').replace(/[-.]/g, '').length <= 12 ? rounded : n;
165
169
  };
170
+ const usableMultiplier = (n) => Number.isFinite(n) && n !== 0;
166
171
  // QUDT's units with a fixed conversion (qudt-catalog.js), read on first use:
167
172
  // each one's dimension vector, multiplier, offset, whether it is a coherent
168
173
  // SI unit and its UCUM code; and the units a UCUM code names, when it names
@@ -191,10 +196,11 @@ const builtinTokens = new Set(units.flatMap(([, , , , tokens]) => tokens));
191
196
 
192
197
  // Facts for the units of these quads that QUDT composes from other units:
193
198
  // qudt:hasFactorUnit with qudt:hasUnit and qudt:exponent, or qudt:prefix
194
- // with qudt:scalingOf. Their multiplier is the product of their factors'
195
- // multipliers, each to its exponent, and their dimension the sum of their
196
- // factors' dimensions times it; as in QUDT, a factor's offset does not
197
- // carry over, but a unit that is one factor with an offset is not a new one.
199
+ // with qudt:scalingOf. The conversion multiplier is the product of the
200
+ // factors' multipliers raised to their exponents, times qudt:factorUnitScalar
201
+ // if given. The dimension is the sum of the factors' scaled dimensions.
202
+ // A factor's offset does not carry over, but a unit that is one factor with
203
+ // an offset is not a new one.
198
204
  // The QUDT units the quads use and the catalog of builtin units lacks, by
199
205
  // IRI or by the UCUM code of a CDT literal, come from QUDT's catalog.
200
206
  export function qudtUnits(quads) {
@@ -219,9 +225,13 @@ export function qudtUnits(quads) {
219
225
  seen.add(id);
220
226
  let found = null;
221
227
  const multiplier = numberOf(values(unit, 'conversionMultiplier')[0]);
222
- const dimension = values(unit, 'hasDimensionVector')[0]?.args?.[0]?.slice(D.length);
223
- if (multiplier !== null && dimension && vector(dimension)) {
224
- found = { exponents: vector(dimension), mult: multiplier, offset: numberOf(values(unit, 'conversionOffset')[0]) ?? 0 };
228
+ const exponents = vector(values(unit, 'hasDimensionVector')[0]?.args?.[0]?.slice(D.length));
229
+ if (multiplier !== null && exponents !== null) {
230
+ const offset = values(unit, 'conversionOffset')[0];
231
+ const offsetValue = offset === undefined ? 0 : numberOf(offset);
232
+ if (usableMultiplier(multiplier) && Number.isFinite(offsetValue) && exponents.every(Number.isFinite)) {
233
+ found = { exponents, mult: multiplier, offset: offsetValue };
234
+ }
225
235
  } else if (builtin.has(id)) {
226
236
  found = builtin.get(id);
227
237
  } else if (catalogUnits().units.has(id)) {
@@ -233,16 +243,22 @@ export function qudtUnits(quads) {
233
243
  let parts = null;
234
244
  if (factors.length) parts = factors.map((f) => [values(f, 'hasUnit')[0], numberOf(values(f, 'exponent')[0])]);
235
245
  else if (prefix && base) {
236
- const scale = numberOf(values(prefix, 'prefixMultiplier')[0]) ?? PREFIXES[prefix.args?.[0]?.slice('http://qudt.org/vocab/prefix/'.length)];
237
- if (scale !== undefined && scale !== null) parts = [[base, 1, scale]];
246
+ const stated = values(prefix, 'prefixMultiplier')[0];
247
+ const scale = stated === undefined ? PREFIXES[prefix.args?.[0]?.slice('http://qudt.org/vocab/prefix/'.length)] : numberOf(stated);
248
+ if (usableMultiplier(scale)) parts = [[base, 1, scale]];
238
249
  }
239
- if (parts && parts.every(([u, e]) => u && e !== null)) {
250
+ const scalar = factors.length ? values(unit, 'factorUnitScalar')[0] : undefined;
251
+ const factor = scalar === undefined ? 1 : numberOf(scalar);
252
+ if (usableMultiplier(factor) && parts?.every(([u, e]) => u && Number.isFinite(e))) {
240
253
  const resolved = parts.map(([u, e, scale = 1]) => [resolve(u, seen), e, scale]);
241
254
  if (resolved.every(([r]) => r) && (factors.length > 1 || resolved[0][1] !== 1 || resolved[0][0].offset === 0)) {
242
- const exponents = BASES.map((_, i) => resolved.reduce((sum, [r, e]) => sum + r.exponents[i] * e, 0));
243
- const mult = exact(resolved.reduce((product, [r, e, scale]) => product * scale * r.mult ** e, 1));
244
- found = { exponents, mult, offset: 0 };
245
- derived.push(`fact(qu_derived(${iri(id)}, ${graphOf(unit)}, ${iri(D + vectorName(exponents))}, ${number(mult)}));`);
255
+ const powers = BASES.map((_, i) => resolved.reduce((sum, [r, e]) => sum + r.exponents[i] * e, 0));
256
+ const mult = exact(factor * resolved.reduce((product, [r, e, scale]) => product * scale * r.mult ** e, 1));
257
+ const dim = vectorName(powers);
258
+ if (usableMultiplier(mult) && vector(dim)) {
259
+ found = { exponents: powers, mult, offset: 0 };
260
+ derived.push(`fact(qu_derived(${iri(id)}, ${graphOf(unit)}, ${iri(D + dim)}, ${number(mult)}));`);
261
+ }
246
262
  }
247
263
  }
248
264
  }
@@ -253,7 +269,20 @@ export function qudtUnits(quads) {
253
269
  const subject = about.get(id)[0][0];
254
270
  if (['hasFactorUnit', 'scalingOf', 'hasDimensionVector'].some((p) => values(subject, p).length)) resolve(subject);
255
271
  }
256
- for (const quad of quads) if (quad[1].args?.[0] === Q + 'unit') resolve(quad[2]);
272
+ for (const [, predicate, unit] of quads) {
273
+ const p = predicate.args?.[0];
274
+ if (p === Q + 'unit' || p === TARGET_UNIT) resolve(unit);
275
+ }
276
+ // An alignment can be the only mention of a catalog unit, for example
277
+ // when a CDT literal uses a local symbol. OWL and SKOS can reverse it.
278
+ const resolveCatalog = (unit) => {
279
+ if (unit?.name === 'iri' && unit.args[0].startsWith(U)) resolve(unit);
280
+ };
281
+ for (const [subject, predicate, object] of quads) {
282
+ const p = predicate.args?.[0];
283
+ if (p === SAME_AS || p === EXACT_MATCH) resolveCatalog(subject);
284
+ if (p === SAME_AS || p === EXACT_MATCH || p === ALIGNED_UNIT) resolveCatalog(object);
285
+ }
257
286
  // The units of CDT literals by their UCUM codes.
258
287
  const tokens = [];
259
288
  for (const quad of quads) {
package/src/rdf-logic.js CHANGED
@@ -5,7 +5,7 @@ import { rdfDocument } from './rdf.js';
5
5
  import { Lettering, write } from './writer.js';
6
6
  import { owl2rlRules } from './owl2rl.js';
7
7
  import { skosRules } from './skos.js';
8
- import { qudtRules } from './qudt.js';
8
+ import { qudtRules, qudtUnits } from './qudt.js';
9
9
  import { compileShacl } from './shacl.js';
10
10
  import { NODE_FUNCTIONS } from './shacl-expr.js';
11
11
  import { executionContext } from './srl.js';
@@ -19,25 +19,31 @@ export const ENTAILMENT = 'https://eyereasoner.github.io/eyemind/entailment#';
19
19
  export const RDF_PROFILES = ['owl2rl', 'qudt', 'skos', 'shacl'];
20
20
 
21
21
  // wanted: rdf/4 patterns of the output contract, or null for every new triple.
22
- export function compileRdfLogic({ quads, prefixes, shapes = quads, wanted = null }, { profiles, source = '<input>', disallows, evaluate, context, stream = false }) {
22
+ export function compileRdfLogic({ quads, prefixes, shapes = quads, wanted = null }, {
23
+ profiles, source = '<input>', disallows, evaluate, context, stream = false, stableRuleIds = false,
24
+ }) {
23
25
  quads = [...new Map(quads.map((q) => [q.map((t) => write(t)).join(' '), q])).values()];
24
26
  const selected = new Set(profiles), needs = new Set();
25
27
  // SHACL node expressions may call SPARQL functions beyond the value rules.
26
28
  const shacl = selected.has('shacl') ? compileShacl(shapes, { disallows, needs, evaluate }) : '';
27
29
  const own = [...needs].filter((n) => NODE_FUNCTIONS[n]);
28
30
  const execution = ['srl_now', 'srl_uuid', 'sh_ne_rand'].some((n) => needs.has(n)) ? executionContext(context ?? null) : null;
31
+ const data = `facts_from({ text: ${JSON.stringify(rdfDocument(quads))} })\n` +
32
+ `facts_from({ text: ${JSON.stringify(rdfDocument(quads, 'ent_base'))} })\n`;
33
+ const defaultGraph = quads.length ? '' : "fact(ent_graph('default_graph'));\n";
34
+ // In a recompiled stream, the background's witnesses must keep the same
35
+ // clause numbers after a message adds RDF and catalog facts.
29
36
  const text = `// Generated by eyemind from ${String(source).replace(/[\r\n\u2028\u2029]/g, ' ')}, with ${profiles.map((p) => '--' + p).join(' ')}.\n` +
30
37
  '// rdf(S, P, O, G) is the working graph; result_rdf contains conclusions and reports.\n' +
31
- `facts_from({ text: ${JSON.stringify(rdfDocument(quads))} })\n` +
32
- `facts_from({ text: ${JSON.stringify(rdfDocument(quads, 'ent_base'))} })\n` + COMMON +
33
- (quads.length ? '' : "fact(ent_graph('default_graph'));\n") +
38
+ (stableRuleIds ? '' : data) + COMMON + (stableRuleIds ? '' : defaultGraph) +
34
39
  (profiles.some((p) => p !== 'skos') ? rdfValueRules([...needs].filter((n) => !NODE_FUNCTIONS[n])) : '') +
35
40
  own.map((n) => NODE_FUNCTIONS[n] + '\n').join('') +
36
41
  (execution ? `implied_by(srl_execution(${JSON.stringify(execution.now)}, ${JSON.stringify(execution.seed)}), 'true');\n` : '') +
37
42
  (selected.has('owl2rl') ? owl2rlRules : '') +
38
43
  (selected.has('skos') ? skosRules : '') +
39
- (selected.has('qudt') ? qudtRules(quads) : '') +
40
- shacl + (evaluate ? "query(sh_evaluation(R));\n" : REPORTS + (stream ? '' : wanted === null ? RESULT : contracted(wanted)));
44
+ (selected.has('qudt') ? qudtRules(stableRuleIds ? [] : quads) : '') +
45
+ shacl + (evaluate ? "query(sh_evaluation(R));\n" : REPORTS + (stream ? '' : wanted === null ? RESULT : contracted(wanted))) +
46
+ (stableRuleIds ? data + defaultGraph + (selected.has('qudt') ? qudtUnits(quads) : '') : '');
41
47
  return { kind: profiles[0], text, program: loadText(text, source),
42
48
  prefixes: { ...prefixes, ent: ENTAILMENT, ...(selected.has('skos') ? { skos: 'http://www.w3.org/2004/02/skos/core#' } : {}),
43
49
  ...(selected.has('qudt') ? { qconv: 'https://eyereasoner.github.io/eyemind/qudt#', qudt: 'http://qudt.org/schema/qudt/', unit: 'http://qudt.org/vocab/unit/' } : {}),
@@ -66,8 +72,10 @@ function shapePatterns(quads, name, input) {
66
72
  const value = (node, property) => values(node, property)[0];
67
73
  const list = (node) => {
68
74
  const items = [];
69
- for (let at = node, seen = new Set(); at && !(at.name === 'iri' && at.args[0] === RDF + 'nil') && !seen.has(identity(at)); at = value(at, RDF + 'rest')) {
70
- seen.add(identity(at));
75
+ for (let at = node, seen = new Set(); at && !(at.name === 'iri' && at.args[0] === RDF + 'nil'); at = value(at, RDF + 'rest')) {
76
+ const id = identity(at);
77
+ if (seen.has(id)) throw new EyemindError(`${name}: cyclic RDF list in SHACL shapes`);
78
+ seen.add(id);
71
79
  items.push(value(at, RDF + 'first'));
72
80
  }
73
81
  return items.filter(Boolean);
@@ -96,14 +104,20 @@ function shapePatterns(quads, name, input) {
96
104
  return [any()];
97
105
  };
98
106
  // The predicates of a path, and whether it is a predicate or its inverse.
107
+ const readingPath = new Set();
99
108
  const path = (node) => {
100
109
  if (named(node)) return { predicates: [named(node)], direct: true };
110
+ const id = identity(node);
111
+ if (readingPath.has(id)) throw new EyemindError(`${name}: cyclic SHACL path`);
101
112
  const inverse = value(node, SH + 'inversePath');
102
113
  if (named(inverse)) return { predicates: [named(inverse)], inverse: true };
103
114
  const parts = [inverse, ...values(node, SH + 'alternativePath').flatMap(list),
104
115
  ...['zeroOrMorePath', 'oneOrMorePath', 'zeroOrOnePath'].map((p) => value(node, SH + p)), ...list(node)].filter(Boolean);
105
116
  if (!parts.length) throw new EyemindError(`${name}: a SHACL path is a predicate, a list or one of the sh: path forms`);
106
- return { predicates: parts.flatMap((part) => path(part).predicates) };
117
+ readingPath.add(id);
118
+ const predicates = parts.flatMap((part) => path(part).predicates);
119
+ readingPath.delete(id);
120
+ return { predicates };
107
121
  };
108
122
  const owners = new Map();
109
123
  for (const quad of quads) {
@@ -261,12 +275,15 @@ export function planRules(program, quads, { input = null, output = null }) {
261
275
  classes: new Set([...background.classes, ...input.classes]) });
262
276
  selected = selected.filter((rule) => reached.has(rule));
263
277
  }
264
- if (output) {
278
+ if (output && !output.variable) {
265
279
  const desired = { predicates: new Set(output.predicates), classes: new Set(output.classes) };
266
280
  const needed = new Set();
267
- const wanted = (head) => (head.variable && desired.predicates.size && !desired.classes.size) ||
268
- [...head.predicates].some((p) => desired.predicates.has(p) && !(p === RDF_TYPE && desired.classes.size)) ||
269
- [...head.classes].some((c) => desired.classes.has(c));
281
+ const wanted = (head) => {
282
+ const anyClass = desired.predicates.has(RDF_TYPE);
283
+ return (head.variable && desired.predicates.size && (!desired.classes.size || anyClass)) ||
284
+ [...head.predicates].some((p) => desired.predicates.has(p)) ||
285
+ [...head.classes].some((c) => anyClass || desired.classes.has(c));
286
+ };
270
287
  for (let changed = true; changed;) {
271
288
  changed = false;
272
289
  for (const rule of selected) {
@@ -285,11 +302,12 @@ export function planRules(program, quads, { input = null, output = null }) {
285
302
 
286
303
  // The properties and classes of triple patterns.
287
304
  const vocabularyOf = (patterns) => {
288
- const into = { predicates: new Set(), classes: new Set() };
305
+ const into = { predicates: new Set(), classes: new Set(), variable: false };
289
306
  for (const pattern of patterns) {
290
- const p = pattern.args[1]?.name === 'iri' ? pattern.args[1].args[0] : null;
307
+ const p = pattern.args[1]?.name === 'iri' ? pattern.args[1].args[0] : undefined;
291
308
  if (p === RDF_TYPE && pattern.args[2]?.name === 'iri' && typeof pattern.args[2].args[0] === 'string') into.classes.add(pattern.args[2].args[0]);
292
- else if (p !== null) into.predicates.add(p);
309
+ else if (typeof p === 'string') into.predicates.add(p);
310
+ else into.variable = true;
293
311
  }
294
312
  return into;
295
313
  };
@@ -307,50 +325,55 @@ const vocabularyOf = (patterns) => {
307
325
  // that does not conform gets one of its own shape.
308
326
  export function messageReasoner({ quads, prefixes, wanted = null, expected = null, planned = false }, { profiles, source = '<input>', limits = {} }) {
309
327
  const options = { profiles, source };
310
- const background = compileRdfLogic({ quads, prefixes }, { ...options, stream: true });
328
+ const whole = { ...options, stableRuleIds: true };
329
+ // QUDT adds catalog facts during compilation from the units and metadata
330
+ // in the current message. Run that compiler on each combined graph.
331
+ const qudt = profiles.includes('qudt'), usePlan = planned && !qudt;
332
+ const background = compileRdfLogic({ quads, prefixes }, qudt ? whole : { ...options, stream: true });
311
333
  // Trusted SHACL shapes plan the rules first, as rdfjs-inference-engine does.
312
- const program = planned ? planRules(background.program, quads, { input: expected && vocabularyOf(expected.patterns),
334
+ const program = usePlan ? planRules(background.program, quads, { input: expected && vocabularyOf(expected.patterns),
313
335
  output: wanted && vocabularyOf(wanted) }) : background.program;
314
- const specializer = new Specializer(program, { quads: ['rdf/4', 'ent_base/4'], limits,
336
+ const specializer = qudt ? null : new Specializer(program, { quads: ['rdf/4', 'ent_base/4'], limits,
315
337
  wanted: wanted && wanted.flatMap((pattern) => [pattern, new Struct('ent_report', pattern.args)]) });
316
338
  // The program for the messages an input shape describes is made at once.
317
- if (expected) specializer.expect(expected.patterns.flatMap((pattern) => [pattern, new Struct('ent_base', pattern.args)]));
339
+ if (expected) specializer?.expect(expected.patterns.flatMap((pattern) => [pattern, new Struct('ent_base', pattern.args)]));
318
340
  let serial = 0;
319
- const kept = (quad) => wanted === null ||
320
- wanted.some((pattern) => unify(new Struct('rdf', quad), freshTerm(pattern, `w${++serial}`), new Env()));
341
+ const matches = (quad, patterns) => patterns.some((pattern) => unify(new Struct('rdf', quad), freshTerm(pattern, `w${++serial}`), new Env()));
342
+ const kept = (quad) => wanted === null || matches(quad, wanted);
321
343
  let alone = null;
322
344
  const answers = (program, limits) => run(program, limits).conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf');
323
345
  return {
324
346
  prefixes: background.prefixes,
325
- reason: specializer.reason,
347
+ reason: qudt ? 'QUDT resolves units from each message' : specializer.reason,
326
348
  specializer,
327
349
  // limits are run()'s bounds. The result has the added quads, whether
328
350
  // the rules were specialized, and the specialized program's sources the
329
351
  // first time a message has its shape; with input shapes, how many
330
352
  // triples were dropped and whether the rest conform.
331
- infer(message, limits = {}) {
353
+ infer(message, runLimits = limits) {
332
354
  const all = message;
333
355
  if (expected?.allowed) message = message.filter((quad) => quad[1].name === 'iri' && expected.allowed.has(quad[1].args[0]));
334
356
  const shaped = expected ? { dropped: all.length - message.length } : {};
335
357
  const facts = message.flatMap((q) => [new Struct('rdf', q), new Struct('ent_base', q)]);
336
- const special = specializer.specialize(facts);
358
+ const special = specializer?.specialize(facts) ?? null;
337
359
  if (special !== null) {
338
- const result = run(special.program, limits);
360
+ const result = run(special.program, runLimits);
339
361
  const added = result.derived.map((node) => node.goal).filter((t) => !special.old.has(identity(t)) &&
340
362
  (t.name === 'ent_report' || (t.name === 'rdf' && RESOURCES.has(t.args[0].name) && t.args[1].name === 'iri')));
341
363
  return { quads: added.map((t) => t.args).filter(kept), specialized: true, stats: result.stats, haltCode: result.haltCode,
342
364
  sources: special.fresh ? special.sources : null, ...(expected ? { ...shaped, conforms: special.conforms } : {}) };
343
365
  }
344
- if (planned) {
366
+ if (expected) shaped.conforms = message.every((quad) => matches(quad, expected.patterns));
367
+ if (usePlan) {
345
368
  // The planned rules run whole over the background and the message.
346
- alone ??= new Set(run(program, limits).derived.map((node) => identity(node.goal)));
347
- const result = run(program.withFacts(facts), limits);
369
+ alone ??= new Set(run(program, runLimits).derived.map((node) => identity(node.goal)));
370
+ const result = run(program.withFacts(facts), runLimits);
348
371
  const added = result.derived.map((node) => node.goal).filter((t) => !alone.has(identity(t)) &&
349
372
  (t.name === 'ent_report' || (t.name === 'rdf' && RESOURCES.has(t.args[0].name) && t.args[1].name === 'iri')));
350
373
  return { quads: added.map((t) => t.args).filter(kept), specialized: false, stats: result.stats, haltCode: result.haltCode, sources: null, ...shaped };
351
374
  }
352
- alone ??= new Set(answers(compileRdfLogic({ quads, prefixes }, options).program, limits).map(identity));
353
- const result = run(compileRdfLogic({ quads: [...quads, ...message], prefixes, shapes: quads }, options).program, limits);
375
+ alone ??= new Set(answers(qudt ? background.program : compileRdfLogic({ quads, prefixes }, whole).program, runLimits).map(identity));
376
+ const result = run(compileRdfLogic({ quads: [...quads, ...message], prefixes, shapes: quads }, whole).program, runLimits);
354
377
  const added = result.conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf' && !alone.has(identity(t)));
355
378
  return { quads: added.map((t) => t.args).filter(kept), specialized: false, stats: result.stats, haltCode: result.haltCode, sources: null, ...shaped };
356
379
  },
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.8.33';
2
+ export const VERSION = '0.8.35';