eyemind 0.8.46 → 0.8.48

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/LE-SPEC.md CHANGED
@@ -167,6 +167,21 @@ and division, then addition and subtraction. Binary operators associate left.
167
167
  They compile to `neg`, `add`, `sub`, `mul` and `div`. Only the value-of form
168
168
  binds its left variable; comparisons require their inputs beforehand.
169
169
 
170
+ An expression can also call an LS arithmetic function by name, with
171
+ expressions as its arguments, and use the constants `pi`, `e` and `tau`:
172
+
173
+ ```text
174
+ For every X and Y, if X is a number and Y is the value of exp(log(X) * 3) + gcd(12, 18) * cos(pi)
175
+ then Y is a result of X.
176
+ ```
177
+
178
+ The functions are those of [LS-SPEC Section 5.2](https://eyereasoner.github.io/eyemind/LS-SPEC#52-functions-and-arities),
179
+ such as `pow`, `floordiv`, `mod`, `gcd`, `lcm`, `sqrt`, `exp`, `log`, `sin`,
180
+ `cos`, `atan2`, `abs` and `hypot`, except `and`, `or` and `not`, which are LE
181
+ words. A call with an arity the function does not take is an error naming
182
+ its line. As in LS, `pow` and `floordiv` of integers stay exact, while
183
+ `exp`, `log` and the trigonometric functions give floats.
184
+
170
185
  ```text
171
186
  4 is an integer.
172
187
  For every X and Y, if X is an integer and Y is the value of X * X
@@ -316,9 +331,10 @@ These programs use the grammar above without additional syntax:
316
331
  | [Symbolic differentiation](https://eyereasoner.github.io/eyemind/examples/deck/symbolic-derivative-le) | Structural recursion over expression trees, constructed derivatives and evaluation at separate points. |
317
332
  | [British citizenship](https://eyereasoner.github.io/eyemind/examples/deck/british-citizenship-le) | Section 1 of the British Nationality Act 1981: alternative premises, a presumption that holds unless the contrary is shown, date comparisons and citizenship through a derived parent. |
318
333
  | [Library fines](https://eyereasoner.github.io/eyemind/examples/deck/library-fines-le) | Charges from alternative rules, then the sum, number and maximum per member over distinct combinations. |
334
+ | [The zeta function](https://eyereasoner.github.io/eyemind/examples/deck/zeta-le) | Exact Bernoulli numbers with `pow`, `floordiv`, `gcd` and `lcm`; zeta at the negative and even integers; Borwein's series with `exp`, `log`, `cos` and `sin` checking zeros on the critical line. |
319
335
  | [Election tally](https://eyereasoner.github.io/eyemind/examples/deck/election-tally-le) | Eligibility by alternatives, distinct choices, an absence test inside a count, winners by maximum with ties, and a quorum. |
320
- | [International data transfers](https://eyereasoner.github.io/eyemind/examples/deck/data-transfers-le) | GDPR Chapter V over ODRL, DPV, location and GDPR-extension names: alternative premises, a duty read from a policy, and a prohibition that wins. |
321
- | [Breach notification](https://eyereasoner.github.io/eyemind/examples/deck/breach-notification-le) | GDPR Articles 33 and 34 over DPV risk terms: deadlines in hours, an encryption exemption, a processor's ODRL duty and a sum. |
336
+ | [International data transfers](https://eyereasoner.github.io/eyemind/examples/deck/data-transfers-le) | An ODRL snapshot with rules: GDPR Chapter V observations derived with alternative premises and absence tests over DPV, location and GDPR-extension names, decided by one permission per basis and a prohibition that wins. |
337
+ | [Breach notification](https://eyereasoner.github.io/eyemind/examples/deck/breach-notification-le) | An ODRL snapshot with rules: GDPR Articles 33 and 34 as permissions and prohibitions, with requests, observations and a processor's duty evidence derived from breach records by comparisons over hours. |
322
338
 
323
339
  Their decks state the modeled assumptions and what the checked proofs establish.
324
340
  Bounds and finite expression domains are explicit in the programs.
@@ -367,9 +383,30 @@ evaluation has conflictStrategy prohibit.
367
383
  ```
368
384
 
369
385
  This directive must be the first sentence of one file. The remainder contains
370
- ground facts using the snapshot vocabulary, without rules or questions. The
371
- compiler maps those facts to RDF and includes the validation, evaluation and
372
- reporting LS of `src/odrl.js`. The same
386
+ facts using the snapshot vocabulary, and rules, but no questions: the report
387
+ is the answer. The compiler maps the facts to RDF and includes the
388
+ validation, evaluation and reporting LS of `src/odrl.js`.
389
+
390
+ A snapshot's rules derive more of its input: their class and property
391
+ statements, in premises and conclusions, are statements of the snapshot's
392
+ RDF graph, with names mapped as for facts. A rule typically derives a state's
393
+ observations or a request's duty evidence from other facts, so the
394
+ evaluator decides on what the rules establish:
395
+
396
+ ```text
397
+ For every S and P,
398
+ if S is a state and S has subject P and P has registeredIn civicDistrict
399
+ then S has residenceVerified true.
400
+ ```
401
+
402
+ Calculations, comparisons, absence tests and aggregates work as in ordinary
403
+ LE; an absence test asks whether the graph, with the rules' conclusions,
404
+ holds a statement. The rules precede the evaluator's own clauses, so they
405
+ cannot read its report, and a snapshot without rules compiles to the same
406
+ program as before. The evaluator validates what the rules derive as it
407
+ validates stated facts: a request or state still has one type, for
408
+ example. Derive an observation as both `true` and `false` where it matters,
409
+ since a missing observation leaves a constraint unknown. The same
373
410
  [snapshot profile](https://eyereasoner.github.io/eyemind/#odrl-snapshots) applies
374
411
  to Turtle and LE, including missing observations, unsupported policy features
375
412
  and conflict strategies. Vocabulary by itself does not enable evaluation.
@@ -475,8 +512,8 @@ The research snapshot demonstrates compound scope, two DPV hierarchies and
475
512
  request-local duty evidence; its Turtle twin, run with `--odrl`, reaches the
476
513
  same decisions. [Research snapshot](https://eyereasoner.github.io/eyemind/examples/deck/research-snapshot-le) · [Turtle twin](https://eyereasoner.github.io/eyemind/examples/deck/research-snapshot-odrl)
477
514
 
478
- Both ODRL directives take a single LE file and reject mixed-in ordinary LE
479
- rules or questions. `--goal` can query their compiled LS program. The
515
+ Both ODRL directives take a single LE file and reject questions; the
516
+ vocabulary directive also rejects rules. `--goal` can query their compiled LS program. The
480
517
  `--odrl` switch selects the Turtle snapshot compiler, which can also combine
481
518
  with `--owl2rl`, `--skos`, `--qudt` and `--shacl`; an LE run takes none of these
482
519
  switches, so an LE snapshot reads only the facts it states.
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.46
5
+ Version: eyemind 0.8.48
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/README.md CHANGED
@@ -13,7 +13,7 @@ program, a JavaScript library and a browser application.
13
13
  - [Playground](https://eyereasoner.github.io/eyemind/playground/): run any
14
14
  example or your own program in the browser, with its proof and check report.
15
15
  - [Examples](https://eyereasoner.github.io/eyemind/examples/): the
16
- 168 runnable programs, each with a card deck and saved conclusions; all but
16
+ 169 runnable programs, each with a card deck and saved conclusions; all but
17
17
  the two streamed examples also save proofs and check reports.
18
18
  - [Specification](https://eyereasoner.github.io/eyemind/LS-SPEC): the
19
19
  language, the proof format and how a proof is checked.
@@ -243,9 +243,12 @@ as LE, and proofs check the compiled LS, not the English-to-LS translation.
243
243
  There are no pronouns, disjunctive conclusions or implicit assumptions.
244
244
 
245
245
  A first sentence `Use ODRL snapshot logic with namespace "..."` turns a file of
246
- ground facts into an [ODRL snapshot](#odrl-snapshots) evaluation, with LE names
246
+ facts and rules into an [ODRL snapshot](#odrl-snapshots) evaluation, with LE names
247
247
  mapped to the `eval:` and `odrl:` vocabularies; see the
248
248
  [handicap-card LE deck](https://eyereasoner.github.io/eyemind/examples/deck/handicap-card-le).
249
+ The rules derive the snapshot's observations and duty evidence, and the
250
+ evaluator decides; see the
251
+ [data transfers deck](https://eyereasoner.github.io/eyemind/examples/deck/data-transfers-le).
249
252
  Ordinary LE can declare RDF prefixes with `Use prefix dpv with namespace "https://w3id.org/dpv#".`
250
253
  Qualified classes, properties and values work in facts, rules and questions.
251
254
  The research access example combines ODRL rules with DPV purpose and consent
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.8.46",
3
+ "version": "0.8.48",
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/arith.js CHANGED
@@ -365,6 +365,12 @@ const ARITIES = {
365
365
  };
366
366
  export const CONSTANTS = { pi: Math.PI, e: Math.E, tau: 2 * Math.PI };
367
367
 
368
+ // Whether name/arity is an arithmetic function, as apply selects one.
369
+ export function takes(name, arity) {
370
+ return arity === 2 && Object.hasOwn(BINARY, name) || arity === 1 && Object.hasOwn(UNARY, name) ||
371
+ Object.hasOwn(FUNCTIONS, name) && accepts(name, arity);
372
+ }
373
+
368
374
  function accepts(name, arity) {
369
375
  const allowed = ARITIES[name];
370
376
  if (allowed === undefined) return false;
package/src/le-odrl.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { compileOdrl, ODRL_EVAL } from './odrl.js';
4
4
  import { loadText } from './lang.js';
5
5
  import { DEFAULT_GRAPH, writeRdf } from './rdf.js';
6
- import { EyemindError, Struct, isGround, properListItems } from './terms.js';
6
+ import { EyemindError, Struct, Var, conjunction, flattenConjunction, isGround, properListItems } from './terms.js';
7
7
  import { readTerm } from './reader.js';
8
8
  import { write } from './writer.js';
9
9
 
@@ -98,11 +98,38 @@ function expandOperandLists(quads, namespace) {
98
98
  }
99
99
  }
100
100
 
101
- export function compileOdrlLe(statements, profile, source) {
101
+ // LS goals a snapshot rule keeps as they are: calculations, comparisons and
102
+ // the aggregation helpers of le.js.
103
+ const KEPT = new Set(['is', 'gt', 'lt', 'ge', 'le', 'eq', 'ne', 'le:distinct', 'le:count', 'le:sum', 'le:max', 'le:min']);
104
+
105
+ // A goal of a snapshot rule over the snapshot's input: class and property
106
+ // statements become odrl_input(S, P, O) with names mapped as for facts.
107
+ export function snapshotGoal(goal, namespace) {
108
+ const value = (term) => term instanceof Var ? term : rdfValue(term, namespace);
109
+ if (goal === 'true') return goal;
110
+ if (!(goal instanceof Struct)) throw new EyemindError('an LE ODRL rule needs class and property statements, calculations and absence tests');
111
+ if (goal.name === 'not' && goal.args.length === 1) return new Struct('not', [snapshotGoal(goal.args[0], namespace)]);
112
+ if (goal.name === 'findall_sorted') {
113
+ const [template, condition, result] = goal.args;
114
+ return new Struct('findall_sorted', [template, conjunction(flattenConjunction(condition).map((g) => snapshotGoal(g, namespace))), result]);
115
+ }
116
+ if (KEPT.has(goal.name)) return goal;
117
+ let s, p, o;
118
+ if (goal.name === 'rdf' && goal.args.length === 3) [s, p, o] = goal.args;
119
+ else if (goal.args.length === 1) [s, p, o] = [goal.args[0], iri(RDF + 'type'), iri(TYPES.get(goal.name) ?? namespace + goal.name)];
120
+ else if (goal.args.length === 2) [s, p, o] = [goal.args[0], iri(PROPERTIES.get(goal.name) ?? namespace + goal.name), goal.args[1]];
121
+ else throw new EyemindError('use class statements, binary properties or rdf(S, P, O) in LE ODRL rules');
122
+ return new Struct('odrl_input', [value(s), p, LIST_OPERANDS.has(p.args?.[0]) && properListItems(o) !== null ? o : value(o)]);
123
+ }
124
+
125
+ // statements: the snapshot's facts; rules: the LS text of its rules, which
126
+ // only a snapshot, not a vocabulary document, may have.
127
+ export function compileOdrlLe(statements, profile, source, rules = '') {
102
128
  const { namespace, evaluate } = profile;
103
129
  const quads = [];
130
+ if (rules && !evaluate) throw new EyemindError(`${source}: an LE ODRL vocabulary document contains ground facts, not rules`);
104
131
  for (const statement of statements) {
105
- if (statement.kind !== 'fact') throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL snapshot or report contains ground facts, not rules or questions`);
132
+ if (statement.kind !== 'fact') throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL snapshot has facts and rules, not questions; its report is the answer`);
106
133
  for (const head of statement.heads) {
107
134
  if (!(head instanceof Struct) || !isGround(head)) throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL fact needs a ground class or property statement`);
108
135
  let s, p, o;
@@ -142,7 +169,7 @@ export function compileOdrlLe(statements, profile, source) {
142
169
  writeRdf(quads, { format: 'n-triples' });
143
170
  const prefixes = { '': namespace, odrl: ODRL, eval: ODRL_EVAL };
144
171
  let loaded;
145
- if (evaluate) loaded = compileOdrl({ quads, prefixes }, { source });
172
+ if (evaluate) loaded = compileOdrl({ quads, prefixes }, { source, rules });
146
173
  else {
147
174
  const facts = quads.map(([s, p, o]) => write(new Struct('rdf', [s, p, o]))).join('\n');
148
175
  const text = `// RDF facts from an LE ODRL vocabulary document.\nfacts_from({ text: ${JSON.stringify(facts)} })\n`;
package/src/le.js CHANGED
@@ -5,9 +5,10 @@ import { CONTROL_KEYS, Program, RESERVED_KEYS, Source } from './program.js';
5
5
  import { readTerm } from './reader.js';
6
6
  import { EMPTY, EyemindError, Struct, Var, conjunction, flattenConjunction } from './terms.js';
7
7
  import { write } from './writer.js';
8
- import { compileOdrlLe, odrlLeReport } from './le-odrl.js';
8
+ import { compileOdrlLe, odrlLeReport, snapshotGoal } from './le-odrl.js';
9
9
  import { dpvRules } from './dpv.js';
10
10
  import { loadText } from './lang.js';
11
+ import { ARITHMETIC_NAMES, CONSTANTS, takes } from './arith.js';
11
12
 
12
13
  const st = (name, ...args) => new Struct(name, args);
13
14
  const VARIABLE = /^[A-Z][0-9]*$/;
@@ -19,6 +20,9 @@ const SENTENCE_WORDS = new Set(['every', 'for', 'if', 'find', 'there', 'it', 'co
19
20
  const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].map((key) => key.split('/')[0]));
20
21
  for (const name of ['true', 'false', 'fail']) RESERVED.add(name);
21
22
  const OPERATORS = { '+': ['add', 1], '-': ['sub', 1], '*': ['mul', 2], '/': ['div', 2] };
23
+ // LS arithmetic functions an expression can call, as exp(X) or gcd(A, B);
24
+ // and, or and not are LE words.
25
+ const CALLS = new Set([...ARITHMETIC_NAMES].filter((name) => !['and', 'or', 'not'].includes(name)));
22
26
  const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
23
27
  const cons = (head, tail) => st('.', head, tail);
24
28
  const AGGREGATES = { number: 'le:count', sum: 'le:sum', maximum: 'le:max', minimum: 'le:min' };
@@ -229,9 +233,19 @@ class Parser {
229
233
 
230
234
  expressionValue(min) {
231
235
  let left;
236
+ const token = this.token, next = this.tokens[this.at + 1];
232
237
  if (this.take('-')) left = st('neg', this.expression(3));
233
238
  else if (this.take('(')) { left = this.expression(); this.need(')'); }
234
- else {
239
+ else if (token.kind === 'word' && CALLS.has(token.value) && next?.value === '(') {
240
+ this.at += 2;
241
+ const args = [];
242
+ if (!this.take(')')) { do { args.push(this.expression()); } while (this.take(',')); this.need(')'); }
243
+ if (!takes(token.value, args.length)) this.error(`${token.value} does not take ${args.length} argument${args.length === 1 ? '' : 's'}`, token.line);
244
+ left = st(token.value, ...args);
245
+ } else if (token.kind === 'word' && Object.hasOwn(CONSTANTS, token.value)) {
246
+ this.at++;
247
+ left = token.value;
248
+ } else {
235
249
  left = this.term();
236
250
  if (!(left instanceof Var) && !['bigint', 'number'].includes(typeof left)) this.error('arithmetic operands must be numbers or declared variables');
237
251
  }
@@ -511,7 +525,23 @@ export function compileLe(inputs) {
511
525
  for (const [prefix, namespace] of parser.prefixes) prefixes.set(prefix, namespace);
512
526
  }
513
527
  if (profile) {
514
- const loaded = compileOdrlLe(statements, profile, inputs[0][1]);
528
+ // A snapshot's rules derive input triples for its evaluation, with the
529
+ // aggregation helpers they use; its facts remain RDF data.
530
+ const map = (goal) => snapshotGoal(goal, profile.namespace);
531
+ const rules = [];
532
+ for (const { kind, heads, body, line, file } of statements.filter((s) => s.kind === 'forward' || s.kind === 'contradiction')) {
533
+ rules.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
534
+ rules.push(kind === 'forward' ? `implies(${javascript(conjunction(body.map(map)))}, ${javascript(conjunction(heads.map(map)))})`
535
+ : `contradiction(${body.map(map).map(javascript).join(', ')})`);
536
+ }
537
+ for (const name of Object.keys(HELPERS).filter((key) => helpers.has(key))) {
538
+ for (const make of HELPERS[name]) {
539
+ const [head, body] = make();
540
+ rules.push(`implied_by(${javascript(head)}, ${body.length ? javascript(conjunction(body)) : "'true'"})`);
541
+ }
542
+ }
543
+ const loaded = compileOdrlLe(statements.filter((s) => s.kind !== 'forward' && s.kind !== 'contradiction'), profile, inputs[0][1],
544
+ rules.length ? rules.join('\n') + '\n' : '');
515
545
  return { ...loaded, prefixes: { ...loaded.prefixes, ...Object.fromEntries(prefixes) } };
516
546
  }
517
547
  // The helpers follow every stated clause, so a witness's rule number is
package/src/odrl.js CHANGED
@@ -22,13 +22,15 @@ export function checkOdrlInput(quads) {
22
22
  if (quads.some(([, , , graph]) => graph !== DEFAULT_GRAPH)) throw new EyemindError('an ODRL snapshot needs one default graph');
23
23
  }
24
24
 
25
- export function compileOdrl({ quads, prefixes }, { source = '<input>' } = {}) {
25
+ // rules: LS clauses that derive further odrl_input triples, as an LE
26
+ // snapshot's own rules; they precede the snapshot's clauses.
27
+ export function compileOdrl({ quads, prefixes }, { source = '<input>', rules = '' } = {}) {
26
28
  checkOdrlInput(quads);
27
29
  // RDF graphs are sets; repeated statements must not violate cardinalities.
28
30
  const facts = [...new Set(quads.map(([s, p, o]) => write(new Struct('odrl_input', [s, p, o]))))].join('\n');
29
31
  const text = `// Generated by eyemind from ${String(source).replace(/[\r\n\u2028\u2029]/g, ' ')}, an ODRL snapshot.\n` +
30
32
  '// Input triples are odrl_input(S, P, O); report triples are rdf(S, P, O).\n' +
31
- `facts_from({ text: ${JSON.stringify(facts)} })\n${RULES}`;
33
+ `facts_from({ text: ${JSON.stringify(facts)} })\n${rules}${RULES}`;
32
34
  return { kind: 'odrl', text, program: loadText(text, source), prefixes: { ...prefixes, eval: ODRL_EVAL }, compiled: null };
33
35
  }
34
36
 
@@ -342,7 +344,8 @@ implies(odrl_rule_condition(E, Q, R, C, 'unknown', Why, Left), [
342
344
  rdf(Issue, e('property'), Left), rdf(Issue, e('reason'), Why),
343
345
  ]);
344
346
  implies(odrl_unmet_duty(E, Q, R, D), rdf(Q, e('unmetDuty'), D));
345
- implies(odrl_unknown_duty(E, Q, R, D, Why), [
347
+ // Missing duty evidence matters only to a rule its constraints do not fail.
348
+ implies([odrl_unknown_duty(E, Q, R, D, Why), not(odrl_failed(E, Q, R))], [
346
349
  rdf(Q, e('uncertainty'), Issue), rdf(Issue, rdfType, e('Uncertainty')),
347
350
  rdf(Issue, e('duty'), D), rdf(Issue, e('rule'), R), rdf(Issue, e('reason'), Why),
348
351
  ]);
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.46';
2
+ export const VERSION = '0.8.48';