Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Open Ontologies: try it here</title>
<meta name="description" content="Drop one spreadsheet. Get one ontology, one shape, and the evidence for every line, from the same engine you would download. Then break a cell and watch the shape catch it.">
<style>
:root{--bg:#020617;--bg2:#070d20;--panel:#0b1428;--ink:#e2e8f0;--muted:#94a3b8;--dim:#64748b;--line:#1e3a5f;--code:#060e20;--accent:#7dd3fc;--ok:#34d399;--bad:#fb3b53;--warn:#fbbf24;--focus:#fbbf24;--tool:#f0abfc;--asserted:#475569;
--sans:ui-sans-serif,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;--mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
*{box-sizing:border-box}html,body{margin:0;color:var(--ink);font:15px/1.55 var(--sans)}
/* Tell the browser the page is dark BEFORE it styles a control of its own.
Without this a <button> and a <textarea> that name no colour are painted
with the UA's `buttontext` and `fieldtext`, which is BLACK, and the sample
buttons and the paste box came out black on #0b1428 at 1.18:1 and 1.10:1.
The rules below also name the colour outright, because a UA default is a
thing to stop depending on, not a thing to re-aim. This also hands the
scrollbars inside the code panes to the dark scheme. */
html{background:var(--bg);color-scheme:dark}
body{background:linear-gradient(135deg,var(--bg),var(--bg2));background-attachment:fixed;min-height:100vh}
a{color:var(--accent)}code,pre,textarea.code{font-family:var(--mono);font-size:12.5px}
header{border-bottom:1px solid var(--line);background:var(--panel)}
.wrap{max-width:1120px;margin:0 auto;padding:0 20px}
header .wrap{display:flex;align-items:baseline;gap:18px;padding:14px 20px}
header h1{font-size:17px;margin:0;font-weight:800;letter-spacing:.2px}header h1 span{color:var(--muted);font-weight:500}
header nav{margin-left:auto;font-size:13px;color:var(--muted)}header nav a{margin-left:14px}
main{padding:26px 0 60px}
h2{font-size:15px;margin:0 0 10px;letter-spacing:.4px;text-transform:uppercase;color:var(--muted)}
.lede{font-size:18px;max-width:820px;margin:0 0 6px}.lede b{font-weight:800}
.sub{color:var(--muted);max-width:820px;margin:0 0 22px}
.grid{display:grid;grid-template-columns:1fr;gap:18px}
.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:16px 18px}
.drop{display:block;border:2px dashed var(--line);border-radius:10px;padding:22px;text-align:center;color:var(--muted);cursor:pointer;transition:.15s}
.drop.on{border-color:var(--accent);background:rgba(125,211,252,.10);color:var(--ink)}
.drop input{display:none}
.samples{display:flex;gap:8px;flex-wrap:wrap;margin-top:12px}
button{font:inherit;color:var(--ink);border:1px solid var(--line);background:var(--panel);border-radius:8px;padding:7px 12px;cursor:pointer}
button:hover{border-color:var(--dim)}button.primary{background:var(--accent);color:#020617;border-color:var(--accent);font-weight:700}
button:disabled{opacity:.5;cursor:default}button:focus-visible,.drop:focus-visible{outline:3px solid var(--focus);outline-offset:2px}
input,select,textarea{font:inherit;background:var(--code);color:var(--ink);border:1px solid var(--line);border-radius:6px;padding:4px 6px}
input::placeholder,textarea::placeholder{color:var(--dim)}
input[type=file]{color:var(--muted)}
textarea.code{width:100%;min-height:150px;border:1px solid var(--line);border-radius:8px;padding:10px;background:var(--code);resize:vertical}
.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:10px}
.status{font-size:13px;color:var(--muted)}.status.err{color:var(--bad)}
.tabs{display:flex;gap:4px;border-bottom:1px solid var(--line);margin:14px 0 10px;flex-wrap:wrap}
.tabs button{border:0;border-bottom:2px solid transparent;border-radius:0;padding:6px 10px;background:none;color:var(--muted)}
.tabs button.on{color:var(--ink);border-bottom-color:var(--accent);font-weight:700}
pre{background:var(--code);border:1px solid var(--line);border-radius:8px;padding:12px;overflow:auto;max-height:520px;margin:0;white-space:pre}
table{border-collapse:collapse;width:100%;font-size:13px;table-layout:fixed}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}
.ev th:nth-child(1){width:11%}.ev th:nth-child(2){width:12%}.ev th:nth-child(3){width:9%}.ev th:nth-child(4),.ev th:nth-child(5),.ev th:nth-child(6){width:5.5%}.ev th:nth-child(7){width:15%}.ev td:last-child{font-size:12px;color:var(--muted)}
.gridwrap table{table-layout:auto}
th{font-size:11.5px;letter-spacing:.5px;text-transform:uppercase;color:var(--muted)}td.mono{font-family:var(--mono);font-size:12px}
.pill{display:inline-block;border-radius:999px;padding:1px 8px;font-size:11.5px;font-weight:700;letter-spacing:.3px}
.pill.ok{background:rgba(52,211,153,.14);color:var(--ok)}.pill.bad{background:rgba(251,59,83,.14);color:var(--bad)}.pill.warn{background:rgba(251,191,36,.14);color:var(--warn)}.pill.dim{background:rgba(148,163,184,.14);color:var(--muted)}
.summary{font-size:16px;margin:0 0 4px}.summary b{font-weight:800}
.means{font-size:13px;color:var(--muted);border-left:3px solid var(--line);padding:6px 12px;margin:10px 0 0}
.gridwrap{overflow:auto;max-height:420px;border:1px solid var(--line);border-radius:8px}
.gridwrap td[contenteditable]{outline:none;font-family:var(--mono);font-size:12px;min-width:60px}
.gridwrap td[contenteditable]:focus{background:rgba(251,191,36,.10)}.gridwrap td.changed{background:rgba(251,191,36,.14)}
/* A WHITE slab carrying the page's own light ink: 1.32:1, measured on
production. This box holds the sentence the whole demo is built to reach,
the validator naming the cell it caught, and it was the least readable
thing on the page. The tint is `.pill.bad`'s, so the violation reads as the
same red event in both places. */
.viol{border-left:3px solid var(--bad);padding:6px 10px;margin:8px 0;background:rgba(251,59,83,.10);border-radius:0 6px 6px 0;font-size:13px}
.viol code{background:var(--code);padding:1px 4px;border-radius:4px}
footer{border-top:1px solid var(--line);color:var(--muted);font-size:13px;padding:18px 0 40px}
.hidden{display:none}
.kv{display:grid;grid-template-columns:max-content 1fr;gap:4px 14px;font-size:13px;margin:8px 0}
.kv dt{color:var(--muted)}.kv dd{margin:0}
</style>
</head>
<body>
<header><div class="wrap">
<h1>open-ontologies <span id="i-tag">· try it here</span></h1>
<nav><a href="https://github.com/fabio-rovai/open-ontologies" id="i-nav0">repository</a><a href="https://github.com/fabio-rovai/open-ontologies/blob/main/docs/tool-reference.md" id="i-nav1">tool reference</a><a href="#what" id="i-nav2">what this is</a><a href="#" id="i-lang">简体中文</a></nav>
</div></header>
<main class="wrap">
<p class="lede"><b id="i-lede1">One sheet in, one ontology out</b><span id="i-lede2">, with the evidence for every line.</span></p>
<p class="sub" id="i-sub">Engine <span id="engine">…</span>.</p>
<div class="grid">
<section class="card">
<h2 id="i-step1">1 · A sheet</h2>
<div style="display:grid;grid-template-columns:minmax(220px,1fr) 2fr;gap:14px"><div><label class="drop" id="drop" tabindex="0"><span id="i-drop">Drop a CSV here, or click to choose one (up to 1 MB)</span><input type="file" id="file" accept=".csv,text/csv,.json,.ndjson"></label>
<div class="samples" id="samples"><span class="status">loading samples…</span></div></div>
<textarea class="code" id="csv" spellcheck="false" placeholder="…or paste CSV with a header row" id="csv-ta" style="min-height:190px"></textarea></div>
<div class="row">
<button class="primary" id="go">Induce the ontology</button>
<label class="status"><span id="i-cls">class name</span> <input id="cls" placeholder="from the file name" style="font:inherit;padding:4px 6px;border:1px solid var(--line);border-radius:6px;width:150px"></label>
<span class="status" id="st1"></span>
</div>
</section>
<section class="card" id="out" hidden>
<h2 id="i-step2">2 · What the engine induced</h2>
<p class="summary" id="summary"></p>
<dl class="kv" id="kv"></dl>
<div class="tabs" id="tabs">
<button data-t="evidence" class="on">Evidence</button><button data-t="ontology">Ontology (Turtle)</button><button data-t="shapes">Shapes (Turtle)</button><button data-t="mapping">Mapping</button><button data-t="engine">Engine output</button>
</div>
<p class="status" id="i-verbatim" hidden style="margin:0 0 6px"></p>
<div id="t-evidence"></div>
<pre id="t-ontology" class="hidden"></pre>
<pre id="t-shapes" class="hidden"></pre>
<pre id="t-mapping" class="hidden"></pre>
<pre id="t-engine" class="hidden"></pre>
<p class="means" id="means"></p>
</section>
</div>
<section class="card" id="graphcard" hidden style="margin-top:18px">
<h2 id="i-stepg">Your sheet, drawn</h2>
<div id="graphwrap">
<p class="sub" style="margin:0 0 8px" id="i-graphp"></p>
<div id="graph" style="background:#030a1c;border:1px solid #1e3a5f;border-radius:10px;overflow:hidden"></div>
<p class="status" id="graphnote" style="margin:8px 0 0" hidden></p>
</div>
</section>
<section class="card" id="play" hidden style="margin-top:18px">
<h2 id="i-step3">3 · Break it</h2>
<p class="sub" style="margin-bottom:8px" id="i-step3p"></p>
<div class="gridwrap" id="gridwrap"></div>
<div class="row">
<button class="primary" id="recheck">Re-check the edited rows</button>
<button id="reset">Reset rows</button>
<span class="status" id="st2"></span>
</div>
<div id="viols"></div>
</section>
<section class="card" id="plan" hidden style="margin-top:18px">
<h2 id="i-step4">4 · Add one line, and get a proof</h2>
<p class="sub" style="margin-bottom:8px" id="i-step4p"></p>
<div class="row" style="align-items:flex-start">
<textarea class="code" id="axiom" spellcheck="false" style="flex:1;min-height:56px"></textarea>
<button class="primary" id="goplan"></button>
</div>
<div class="row"><span class="status" id="st3"></span></div>
<div id="planout"></div>
</section>
<section id="what" style="margin-top:26px">
<h2 id="i-what">What this is, and is not</h2>
<p class="sub" style="margin-bottom:8px" id="i-what1"></p>
<p class="sub" id="i-what2"></p>
</section>
</main>
<footer><div class="wrap"><span id="i-foot"></span> <a href="https://github.com/fabio-rovai/open-ontologies">fabio-rovai/open-ontologies</a>, MIT.</div></footer>
<script>
// Every visible string, in each language the page is published in. The page
// follows the writing rules of ASD-STE100 Simplified Technical English: one
// idea for each sentence, the active voice, simple tenses, and a maximum of 25
// words in a descriptive sentence. The approved-word dictionary is a licensed
// document this project does not hold, so the page claims the writing rules and
// not approved-word compliance, exactly as the README does.
//
// NUMBERS are not in this table. Each number on this page comes from the engine
// run and is formatted into these sentences, so a translation cannot state a
// count the run did not produce.
const STR = {
en: {
tag: '· try it here',
nav: ['repository', 'tool reference', 'what this is'],
lede1: 'One sheet in, one ontology out', lede2: ', with the evidence for each line. Then change one cell, and see the shape find the error.',
sub: 'The engine does the work. This page runs it in batch mode on the server: <code>induce</code>, then <code>shacl</code>, then <code>reason owl-rl</code>. The page draws the answer. The page does not decide it. Engine <span id="engine">…</span>.',
step1: '1 · A sheet',
drop: 'Put a CSV file here, or click to choose one. The limit is 1 MB.',
samples: 'samples:',
samples_hint: 'Each one runs the whole loop: induce, then reason, then a certificate the Lean checker accepts, then one conclusion forged and refused by that same checker.',
paste: '…or paste a CSV file with a header row',
go: 'Induce the ontology', cls: 'class name', clsph: 'from the file name',
step2: '2 · What the engine induced',
tabs: ['Evidence', 'Ontology (Turtle)', 'Shapes (Turtle)', 'Mapping', 'Engine output'],
k_id: 'identifier', k_shape: 'the shape over its own rows', k_rl: 'owl-rl closure', k_loaded: 'loaded',
rowsyn: 'row number: no column was filled and unique',
conforms: 'conforms', violations: 'violations', undetermined: 'undetermined',
focus: 'focus nodes. This is expected: the rows satisfy the shape by construction.',
inferred: 'inferred triples over', asserted: 'asserted', notrun: 'not run',
schema: 'schema triples and', instance: 'instance triples',
th: ['property', 'columns', 'type', 'filled', 'distinct', 'per row', 'decision', 'evidence'],
p_object: 'object →', p_in: 'in', p_group: 'group of', p_min: 'minCount 1', p_max: 'maxCount',
observed: '; observed', notconstrained: '(reported, and not constrained)',
engine_says: 'The engine says: ',
step4: '4 · Add one line, and get a proof',
step4p: 'An induced ontology is flat, so a reasoner derives nothing from it. That is measured, not assumed: 0 derivations under rdfs and under owl-rl, because the mapping already gives each row its class. So add one line. This is the front page\u2019s own argument: plan a change to an ontology, and see every consequence before you apply it. The engine writes a certificate for what follows, the Lean checker accepts it, and then the page forges one conclusion and hands the same checker the same premises.',
goplan: 'Add the line and reason',
p_new: 'consequences that were not there before',
p_cert: 'The certificate', p_acc: 'The checker accepted it', p_ref: 'The checker refused the forged one',
p_theorem: 'theorem', p_exit: 'exit', p_rule: 'rule', p_absent: 'This release carries no checker, so nothing was checked here.',
p_nothing: 'That line derives nothing. Try a subClassOf over the induced class.',
p_forgedline: 'One conclusion was changed, and both premises were left exactly as they were:',
stepg: 'Your sheet, drawn',
graphp: 'Your sheet, drawn the way the front page draws ies-core. Grey is what you asserted. Green is what the engine derived and the checker accepted. Red is the line that was forged and refused. Literals, blank nodes and list cells are not drawn, because a node for each of them hides the shape.',
graphp_flat: 'Your sheet, drawn the way the front page draws ies-core. Every edge is grey, and grey is what a person asserted. Nothing is green yet, because an induced ontology is flat and a reasoner derives nothing from it. Step 4 below is where the engine writes a certificate, the Lean checker accepts it, and one forged line is refused: watch this picture gain a green layer and one red edge. Literals, blank nodes and list cells are not drawn, because a node for each of them hides the shape.',
g_empty: 'This run drew no edges: nothing was asserted, derived or refused over a term this picture can name. The tables above are the answer; the picture is only a way of looking at it.',
g_missing: 'This run returned no picture. The induced ontology and its evidence above are unaffected.',
g_repainted: 'The picture above now carries all three colours:',
g_asserted: 'ASSERTED', g_certified: 'CERTIFIED', g_rejected: 'REJECTED', g_more: 'edges drawn, of',
g_drawn: 'Drawn:', g_of: 'of', g_undrawn: 'Not drawn:',
g_lit: 'with a literal at one end', g_plumb: 'a blank node or a list cell',
g_dup: 'a repeat of an edge already drawn', g_budget: 'past the drawing budget for its kind',
summary: '{c}: {r} rows → 1 class, {p} {pw}{obj}{grp}{enu}.',
prop1: 'property', propn: 'properties', obj: ' object', grp: ' numbered group merged', grpn: ' numbered groups merged', enu: ' enumeration', enun: ' enumerations',
verbatim: '',
step3: '3 · Change it',
step3p: 'The rows satisfy their own induced shape <i>by construction</i>. Thus the clean report above shows nothing. The shape constrains the <b>next</b> row. Change any cell below, and check the rows again. Put a word where a number was. Put a value outside an enumeration. Empty a cell that each row filled. The violation comes from the SHACL validator of the engine. It does not come from a rule in this page.',
recheck: 'Check the changed rows again', reset: 'Reset the rows',
showing: 'The table shows 40 rows of', showing2: '. The check uses each row.',
stillok: 'The changed rows still satisfy the induced shape. Try a word in a numeric column, or a value outside an enumeration.',
found: 'The SHACL validator of the engine reports:', violation: 'violation', violations_n: 'violations',
andmore: '…and', more: 'more',
what: 'What this is, and what it is not',
what1: 'An induced ontology is a <b>hypothesis about the sheet</b>. It is not a truth about the domain. Three choices are deliberate. First, cardinality becomes a <i>shape</i>, and never an <code>owl:FunctionalProperty</code>: under OWL RL a functional property with two values does not reject the second row, it makes the two objects the same (<code>prp-fp</code>). Second, the page reports an observed numeric range, and it never makes that range a <code>sh:minInclusive</code>. Third, numbered columns (<code>topping1…topping7</code>) become one property with many values, and the page reports the group, so that a wrong merge is visible. Remove each line that your domain does not support. The evidence column tells you what each line rests on.',
what2: 'The same work from an MCP client, on your own files: <code>onto_induce {"path": "sheet.csv"}</code>. From a shell: <code>open-ontologies batch</code> with <code>induce sheet.csv --out ./induced</code>.',
foot: 'This page keeps nothing that you send. Each request runs in a new scratch directory, and the page deletes that directory when it sends the response. The limits are 1 MB for each sheet and 40 seconds for each run.',
err_big: 'That file is larger than 1 MB. Run the engine on your own machine for a file of that size.',
err_first: 'Paste a sheet first, or choose one.',
running: 'the engine is running…', done: 'done in', loaded_s: 'loaded',
lang_other: '简体中文', lang_code: 'zh',
},
zh: {
tag: '· 在这里试一试',
nav: ['代码仓库', '工具参考', '这是什么'],
lede1: '放入一张表格,得到一个本体', lede2: ',并且每一行都有证据。然后改动一个单元格,看形状把错误找出来。',
sub: '工作由引擎完成。本页面在服务器上以批处理方式运行它:<code>induce</code>,然后 <code>shacl</code>,然后 <code>reason owl-rl</code>。页面只负责把答案画出来。页面不作判断。引擎 <span id="engine">…</span>。',
step1: '1 · 一张表格',
drop: '把 CSV 文件拖到这里,或者点击选择一个。上限是 1 MB。',
samples: '示例:',
samples_hint: '每一个都会跑完整条链路:先归纳,再推理,然后生成一份 Lean 检查器接受的证书,最后伪造一条结论并由同一个检查器将其拒绝。',
paste: '……或者粘贴一个带表头行的 CSV 文件',
go: '归纳出本体', cls: '类名', clsph: '来自文件名',
step2: '2 · 引擎归纳出了什么',
tabs: ['证据', '本体(Turtle)', '形状(Turtle)', '映射', '引擎输出'],
k_id: '标识列', k_shape: '形状作用于它自己的数据行', k_rl: 'owl-rl 闭包', k_loaded: '已载入',
rowsyn: '行号:没有任何一列既填满又唯一',
conforms: '符合', violations: '存在违规', undetermined: '无法判定',
focus: '个焦点节点。这是预期结果:这些数据行按构造就满足该形状。',
inferred: '条推论,基于', asserted: '条断言', notrun: '未运行',
schema: '条模式三元组与', instance: '条实例三元组',
th: ['属性', '列', '类型', '已填充', '不同值', '每行个数', '判定', '证据'],
p_object: '对象属性 →', p_in: '取值集合', p_group: '合并了', p_min: 'minCount 1', p_max: 'maxCount',
observed: ';观察到', notconstrained: '(只报告,不作为约束)',
engine_says: '引擎说:',
step4: '4 · 加一行,然后得到一份证明',
step4p: '归纳出的本体是扁平的,推理机从它推不出东西。这是测得的,不是假设的:在 rdfs 和 owl-rl 下都是 0 条推论,因为映射已经给每一行赋予了类。所以请加一行。这正是首页自己的论点:为本体规划一次变更,在应用之前看清每一项后果。引擎为随之而来的结论写一份证书,Lean 检查器接受它;随后页面伪造一条结论,把同样的前提交给同一个检查器。',
goplan: '加上这一行并推理',
p_new: '条此前不存在的后果',
p_cert: '证书', p_acc: '检查器接受了它', p_ref: '检查器拒绝了伪造的那一份',
p_theorem: '定理', p_exit: '退出码', p_rule: '规则', p_absent: '本次发布不含检查器,因此这里没有检查任何东西。',
p_nothing: '这一行推不出任何东西。试试在归纳出的类上写一条 subClassOf。',
p_forgedline: '一条结论被改动,两条前提原样保留:',
stepg: '你的表格,画出来',
graphp: '你的表格,用首页绘制 ies-core 的同一种方式画出来。灰色是你断言的,绿色是引擎推导并被检查器接受的,红色是被伪造并遭拒绝的那一行。字面量、空节点和列表单元都不绘制,因为给它们每一个都配一个节点会掩盖结构。',
graphp_flat: '你的表格,用首页绘制 ies-core 的同一种方式画出来。现在每条边都是灰色的,灰色就是人断言的部分。还没有绿色,因为归纳出的本体是扁平的,推理机从它推不出东西。下面的第 4 步才是引擎写出证书、Lean 检查器接受它、并有一条被伪造的结论遭到拒绝的地方:请看这幅图长出绿色的一层和一条红边。字面量、空节点和列表单元都不绘制,因为给它们每一个都配一个节点会掩盖结构。',
g_empty: '这次运行没有画出任何边:没有任何断言、推论或拒绝落在这幅图能命名的词项上。上面的表格才是答案,图只是看它的一种方式。',
g_missing: '这次运行没有返回图。上面归纳出的本体及其证据不受影响。',
g_repainted: '上面那幅图现在带着全部三种颜色:',
g_asserted: '断言', g_certified: '已认证', g_rejected: '被拒绝', g_more: '条边已绘制,共',
g_drawn: '已绘制:', g_of: '/', g_undrawn: '未绘制:',
g_lit: '有一端是字面量', g_plumb: '是空节点或列表单元',
g_dup: '与已绘制的某条边重复', g_budget: '超出该类别的绘制上限',
summary: '{c}:{r} 行 → 1 个类,{p} 个{pw}{obj}{grp}{enu}。',
prop1: '属性', propn: '属性', obj: '(其中 1 个是对象属性)', grp: '(合并了 1 组编号列)', grpn: '(合并了多组编号列)', enu: '(含取值集合)', enun: '(含取值集合)',
verbatim: '下表“证据”列与上面“引擎说”的句子,是引擎自己的输出,原样显示,未经翻译。本页面不改写引擎的措辞。',
step3: '3 · 改动它',
step3p: '这些数据行按构造就满足它们自己归纳出的形状。因此上面那份干净的报告什么也说明不了。形状约束的是<b>下一行</b>。改动下面任意一个单元格,然后重新检查。在数字列里放一个词。放一个不在取值集合里的值。把每行都填了的单元格清空。违规来自引擎的 SHACL 校验器。它不来自本页面里的规则。',
recheck: '重新检查改动后的数据行', reset: '重置数据行',
showing: '表格显示 40 行,共', showing2: ' 行。检查使用全部数据行。',
stillok: '改动后的数据行仍然满足归纳出的形状。试试在数字列里放一个词,或者放一个不在取值集合里的值。',
found: '引擎的 SHACL 校验器报告:', violation: '条违规', violations_n: '条违规',
andmore: '……还有', more: '条',
what: '这是什么,不是什么',
what1: '归纳出的本体是<b>关于这张表格的一个假设</b>。它不是关于该领域的真理。有三个选择是刻意的。第一,基数变成<i>形状</i>,绝不变成 <code>owl:FunctionalProperty</code>:在 OWL RL 下,一个有两个值的函数性属性不会拒绝第二行,而是把这两个对象判为同一个(<code>prp-fp</code>)。第二,页面报告观察到的数值范围,并且绝不把该范围变成 <code>sh:minInclusive</code>。第三,带编号的列(<code>topping1…topping7</code>)合并成一个多值属性,页面会报告这个分组,好让错误的合并可见。请删掉你的领域不支持的每一行。证据列会告诉你每一行依据什么。',
what2: '在 MCP 客户端中对你自己的文件做同样的事:<code>onto_induce {"path": "sheet.csv"}</code>。在 shell 中:<code>open-ontologies batch</code>,命令为 <code>induce sheet.csv --out ./induced</code>。',
foot: '本页面不保留你发送的任何内容。每个请求都在一个新的临时目录中运行,页面在发送响应时删除该目录。上限是每张表格 1 MB,每次运行 40 秒。',
err_big: '该文件大于 1 MB。这种大小的文件请在你自己的机器上运行引擎。',
err_first: '请先粘贴一张表格,或者选择一张。',
running: '引擎正在运行……', done: '用时', loaded_s: '已载入',
lang_other: 'English', lang_code: 'en',
},
};
const LANG = (new URLSearchParams(location.search).get('lang') === 'zh') ? 'zh' : 'en';
const L = STR[LANG];
document.documentElement.lang = (LANG === 'zh') ? 'zh-CN' : 'en';
const $=s=>document.querySelector(s);
// One paint, at load. Every string above comes from the table, so a language is
// a table entry and not a second copy of the page.
function paint(){
const set=(id,v,html)=>{const e=document.getElementById(id); if(e){ if(html) e.innerHTML=v; else e.textContent=v; }};
set('i-tag', L.tag); L.nav.forEach((t,i)=>set('i-nav'+i, t));
set('i-lede1', L.lede1); set('i-lede2', L.lede2);
const sub=document.getElementById('i-sub'); if(sub) sub.innerHTML = L.sub;
set('i-step1', L.step1); set('i-drop', L.drop); set('i-cls', L.cls);
set('i-step2', L.step2); set('i-step3', L.step3); set('i-step3p', L.step3p, true);
set('i-step4', L.step4); set('i-step4p', L.step4p); set('i-stepg', L.stepg); set('i-graphp', L.graphp);
const gp=document.getElementById('goplan'); if(gp) gp.textContent=L.goplan;
set('i-what', L.what); set('i-what1', L.what1, true); set('i-what2', L.what2, true);
set('i-foot', L.foot);
const ta=document.getElementById('csv-ta'); if(ta) ta.placeholder=L.paste;
const cls=document.getElementById('cls'); if(cls) cls.placeholder=L.clsph;
$('#go').textContent=L.go; $('#recheck').textContent=L.recheck; $('#reset').textContent=L.reset;
[...$('#tabs').children].forEach((b,i)=>{ if(L.tabs[i]) b.textContent=L.tabs[i]; });
const sw=document.getElementById('i-lang');
if(sw){ sw.textContent=L.lang_other;
const q=new URLSearchParams(location.search); q.set('lang', L.lang_code); sw.href='?'+q.toString(); }
document.title = (LANG==='zh') ? 'Open Ontologies:在这里试一试' : 'Open Ontologies: try it here';
}
paint();
const api=(p,opt)=>fetch('/api/'+p,opt).then(async r=>{const j=await r.json().catch(()=>({error:'not JSON: '+r.status}));if(!r.ok&&!j.error)j.error='HTTP '+r.status;return j});
let current={name:'sheet.csv',csv:'',induced:null,mapping:null,rows:[],headers:[]};
api('engine').then(j=>{$('#engine').textContent=j.tag?`${j.tag}, sha256 ${String(j.sha256).slice(0,12)}…`:'unavailable'}).catch(()=>{$('#engine').textContent='unavailable'});
api('samples').then(j=>{const box=$('#samples');box.innerHTML='<span class="status">'+L.samples+'</span>';(j.samples||[]).forEach(s=>{const b=document.createElement('button');b.textContent=`${s.name} (${s.rows} rows)`;b.onclick=()=>{$('#csv').value=s.csv;current.name=s.name;$('#cls').value='';$('#st1').textContent=`${L.loaded_s} ${s.name}`;
// A prefilled example runs the WHOLE loop, not just induce. Induce alone
// leaves the picture entirely grey and the checker unrun, so the page's own
// argument -- a certificate, a checker that accepts it, and the same checker
// refusing a forged line -- was behind a button most readers never reached.
current.autoplan=true;$('#go').click()};box.appendChild(b)});
// Say what the button does before it is pressed. A control that runs a
// forty-second pipeline should not look like one that fills a text box.
const hint=document.createElement('span');hint.className='status';hint.style.flexBasis='100%';hint.textContent=L.samples_hint;box.appendChild(hint);
// ?sample=epc-sample.csv&auto=1 loads a bundled sheet and runs it, so a link can carry a worked example.
const q=new URLSearchParams(location.search),want=q.get('sample');const hit=(j.samples||[]).find(s=>s.name===want);if(hit){$('#csv').value=hit.csv;current.name=hit.name;$('#st1').textContent=`${L.loaded_s} ${hit.name}`;
// `&auto=1` now carries the WHOLE loop: induce, then add the line and
// reason, so a reader arriving from the README's badge sees the
// certificate, the checker's acceptance and the refusal of the forged line
// without touching anything. `&plan=0` opts out and stops after induce.
// This reverses the old default, where the loop needed `&plan=1` and the
// badge link therefore showed a grey picture and no checker at all.
if(q.get('auto')==='1'){ current.autoplan = q.get('plan')!=='0'; $('#go').click(); }}});
const drop=$('#drop'),file=$('#file');
drop.onclick=()=>file.click();drop.onkeydown=e=>{if(e.key==='Enter'||e.key===' ')file.click()};
['dragenter','dragover'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.add('on')}));
['dragleave','drop'].forEach(ev=>drop.addEventListener(ev,e=>{e.preventDefault();drop.classList.remove('on')}));
drop.addEventListener('drop',e=>{const f=e.dataTransfer.files[0];if(f)readFile(f)});
file.onchange=()=>{if(file.files[0])readFile(file.files[0])};
function readFile(f){if(f.size>1_000_000){$('#st1').textContent=L.err_big;$('#st1').className='status err';return}
const r=new FileReader();r.onload=()=>{$('#csv').value=r.result;current.name=f.name;$('#st1').className='status';$('#st1').textContent=`${L.loaded_s} ${f.name}`};r.readAsText(f)}
// A small CSV parser for the editable grid only; the ENGINE parses the sheet it is sent.
function parseCsv(t){const rows=[];let row=[],cell='',q=false;for(let i=0;i<t.length;i++){const c=t[i];if(q){if(c==='"'){if(t[i+1]==='"'){cell+='"';i++}else q=false}else cell+=c}
else if(c==='"')q=true;else if(c===','){row.push(cell);cell=''}else if(c==='\n'){row.push(cell);rows.push(row);row=[];cell=''}else if(c!=='\r')cell+=c}
if(cell.length||row.length){row.push(cell);rows.push(row)}return rows.filter(r=>r.length>1||(r.length===1&&r[0]!==''))}
function toCsv(headers,rows){const esc=v=>/[",\n]/.test(v)?'"'+v.replace(/"/g,'""')+'"':v;return [headers,...rows].map(r=>r.map(esc).join(',')).join('\n')+'\n'}
$('#tabs').onclick=e=>{const b=e.target.closest('button');if(!b)return;[...$('#tabs').children].forEach(x=>x.classList.toggle('on',x===b));['evidence','ontology','shapes','mapping','engine'].forEach(t=>$('#t-'+t).classList.toggle('hidden',t!==b.dataset.t))};
$('#go').onclick=async()=>{const csv=$('#csv').value;if(!csv.trim()){$('#st1').textContent=L.err_first;return}
current.csv=csv;$('#go').disabled=true;$('#st1').className='status';$('#st1').textContent=L.running;
const j=await api('induce',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:current.name,csv,class:$('#cls').value})});
$('#go').disabled=false;
if(j.error){$('#st1').className='status err';$('#st1').textContent=j.error;if(j.engine)console.log(j.engine);return}
$('#st1').textContent=`${L.done} ${j.meta?.seconds ?? '?'} s`;render(j)};
function render(j){const ind=j.induced;current.induced=ind;current.mapping=j.mapping_json||JSON.stringify(ind.mapping);
$('#out').hidden=false;$('#play').hidden=false;
// The picture is drawn HERE, on induce, and not only after step 4. Until
// this it existed solely in the step-4 handler, so a reader who induced a
// sheet and stopped never learned the page could draw one at all.
drawGraph(j.graph);
const props=ind.columns.length,obj=ind.columns.filter(c=>c.refers_to).length,enums=ind.columns.filter(c=>c.values).length,groups=ind.columns.filter(c=>c.columns.length>1).length;
$('#summary').innerHTML = L.summary
.replace('{c}', `<b>${esc(ind.class)}</b>`)
.replace('{r}', ind.rows)
.replace('{p}', props)
.replace('{pw}', props === 1 ? L.prop1 : L.propn)
.replace('{obj}', obj ? (LANG === 'zh' ? L.obj : ` (${obj} object)`) : '')
.replace('{grp}', groups ? (LANG === 'zh' ? (groups > 1 ? L.grpn : L.grp) : `, ${groups} numbered group${groups > 1 ? 's' : ''} merged`) : '')
.replace('{enu}', enums ? (LANG === 'zh' ? L.enu : `, ${enums} enumeration${enums > 1 ? 's' : ''}`) : '');
// The evidence column and `means` below are the ENGINE's own sentences,
// shown verbatim. The page does not paraphrase the engine, so in a
// translated page they stay in English and the page says why.
const vb = document.getElementById('i-verbatim');
if (vb) { vb.textContent = L.verbatim; vb.hidden = !L.verbatim; }
const sh=j.shacl||{},rs=j.reason||{};
const conf=sh.conforms===true?`<span class="pill ok">${L.conforms}</span>`:sh.conforms===false?`<span class="pill bad">${L.violations}</span>`:`<span class="pill warn">${L.undetermined}</span>`;
$('#kv').innerHTML=`<dt>${L.k_id}</dt><dd><code>${esc(ind.id_column)}</code>${ind.id_synthesised?` <span class="pill dim">${L.rowsyn}</span>`:''}</dd>
<dt>${L.k_shape}</dt><dd>${conf} ${sh.violation_count??0} ${sh.violation_count===1?L.violation:L.violations_n}, ${sh.focus_nodes??'?'} ${L.focus}</dd>
<dt>${L.k_rl}</dt><dd>${rs.inferred_count!=null?`${rs.inferred_count} ${L.inferred} ${rs.initial_triples??'?'} ${L.asserted}`:(rs.error||L.notrun)}</dd>
<dt>${L.k_loaded}</dt><dd>${ind.loaded?`${ind.loaded.schema_triples} ${L.schema} ${ind.loaded.instance_triples} ${L.instance}`:'—'}</dd>`;
let t='<table class="ev"><thead><tr>'+L.th.map(h=>`<th>${h}</th>`).join('')+'</tr></thead><tbody>';
ind.columns.forEach(c=>{const dec=[];if(c.refers_to)dec.push(`<span class="pill ok">${L.p_object} ${esc(c.refers_to)}</span>`);if(c.values)dec.push(`<span class="pill warn">${L.p_in} (${c.values.length})</span>`);if(c.columns.length>1)dec.push(`<span class="pill dim">${L.p_group} ${c.columns.length}</span>`);if(c.filled===c.rows)dec.push(`<span class="pill dim">${L.p_min}</span>`);dec.push(`<span class="pill dim">${L.p_max} ${Math.max(1,c.max_per_row)}</span>`);
t+=`<tr><td class="mono">${esc(c.property)}</td><td class="mono">${esc(c.columns.join(', '))}</td><td class="mono">${c.refers_to?'IRI':'xsd:'+esc(c.datatype)}</td><td>${c.filled}/${c.rows}</td><td>${c.distinct}</td><td>${c.max_per_row}</td><td>${dec.join(' ')}</td><td style="color:var(--muted)">${esc(c.evidence)}${Object.keys(c.observed||{}).length?L.observed+' '+esc(Object.entries(c.observed).map(([k,v])=>k+' '+v).join(', '))+' '+L.notconstrained:''}</td></tr>`});
$('#t-evidence').innerHTML=t+'</tbody></table>';
$('#t-ontology').textContent=ind.ontology_ttl;$('#t-shapes').textContent=ind.shapes_ttl;$('#t-mapping').textContent=pretty(current.mapping);
$('#t-engine').textContent=JSON.stringify({induce:{...ind,ontology_ttl:'(see tab)',shapes_ttl:'(see tab)',mapping:'(see tab)'},shacl:j.shacl,reason:j.reason,stats:j.stats,meta:j.meta},null,1);
$('#means').textContent=L.engine_says+ind.means;
const rows=parseCsv(current.csv);current.headers=rows[0]||[];current.rows=rows.slice(1);grid();
// The one line, prefilled with the class the engine just induced.
$('#plan').hidden=false;
$('#axiom').value=`:${ind.class} rdfs:subClassOf :Thing${'\n'}:Thing a owl:Class .`.replace(':Thing\n', ':Thing .\n');
$('#planout').innerHTML='';$('#st3').textContent='';
if(current.autoplan){current.autoplan=false;setTimeout(()=>$('#goplan').click(),60)}}
function grid(){const h=current.headers,rows=current.rows.slice(0,40);let t='<table><thead><tr><th>#</th>'+h.map(x=>`<th>${esc(x)}</th>`).join('')+'</tr></thead><tbody>';
rows.forEach((r,i)=>{t+=`<tr><td style="color:var(--dim)">${i+1}</td>`+h.map((_,k)=>`<td contenteditable data-r="${i}" data-c="${k}">${esc(r[k]??'')}</td>`).join('')+'</tr>'});
$('#gridwrap').innerHTML=t+'</tbody></table>'+(current.rows.length>40?`<div class="status" style="padding:6px 8px">${L.showing} ${current.rows.length}${L.showing2}</div>`:'');
$('#gridwrap').oninput=e=>{const td=e.target.closest('td[contenteditable]');if(!td)return;const r=+td.dataset.r,c=+td.dataset.c;current.rows[r][c]=td.textContent;td.classList.add('changed')};$('#viols').innerHTML='';$('#st2').textContent=''}
$('#reset').onclick=()=>{const rows=parseCsv(current.csv);current.rows=rows.slice(1);grid()};
$('#recheck').onclick=async()=>{if(!current.induced)return;$('#recheck').disabled=true;$('#st2').className='status';$('#st2').textContent=L.running;
const csv=toCsv(current.headers,current.rows);
const j=await api('check',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:current.name,csv,ontology_ttl:current.induced.ontology_ttl,shapes_ttl:current.induced.shapes_ttl,mapping:current.mapping})});
$('#recheck').disabled=false;if(j.error){$('#st2').className='status err';$('#st2').textContent=j.error;return}
const sh=j.shacl||{};$('#st2').textContent=`${j.meta?.seconds??'?'} s · ${j.ingest?.triples_loaded??'?'} triples loaded`;
const v=sh.violations||[];let html=sh.conforms===true?`<p class="status"><span class="pill ok">${L.conforms}</span> ${L.stillok}</p>`:sh.conforms===false?`<p class="status"><span class="pill bad">${v.length} ${v.length===1?L.violation:L.violations_n}</span> ${L.found}</p>`:`<p class="status"><span class="pill warn">${L.undetermined}</span> ${esc(JSON.stringify(sh.skipped_constraints||sh))}</p>`;
v.slice(0,50).forEach(x=>{html+=`<div class="viol"><code>${esc(short(x.focus_node))}</code> · <code>${esc(short(x.result_path||x.path||''))}</code> · ${esc(short(x.source_constraint_component||x.constraint||''))}<br>${esc(x.message||'')}</div>`});
if(v.length>50)html+=`<p class="status">${L.andmore} ${v.length-50} ${L.more}</p>`;$('#viols').innerHTML=html};
$('#goplan').onclick=async()=>{
if(!current.induced)return;
$('#goplan').disabled=true;$('#st3').className='status';$('#st3').textContent=L.running;
const j=await api('plan',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({
name:current.name,csv:current.csv,ontology_ttl:current.induced.ontology_ttl,mapping:current.mapping,axiom:$('#axiom').value})});
$('#goplan').disabled=false;
if(j.error){$('#st3').className='status err';$('#st3').textContent=j.error;return}
$('#st3').textContent=`${L.done} ${j.meta?.seconds??'?'} s`;
const c=j.certificate||{},a=j.accepted||{},f=j.forged;
const n=c.derivations??0;
let h=`<p class="summary" style="margin-top:10px"><b>${n}</b> ${L.p_new}.</p>`;
if(!n){h+=`<p class="status">${L.p_nothing}</p>`;}
else{
h+=`<dl class="kv"><dt>${L.p_cert}</dt><dd><code>${esc(c.asserted)} asserted, ${esc(c.derivations)} derivations</code> · ${esc(JSON.stringify(c.by_rule||{}))}</dd>`;
if(a.absent){h+=`<dt>${L.p_acc}</dt><dd><span class="pill warn">${L.p_absent}</span></dd>`;}
else{
h+=`<dt>${L.p_acc}</dt><dd><span class="pill ${a.ok?'ok':'bad'}">${L.p_exit} ${esc(a.exit)}</span> ${a.theorem?`${L.p_theorem} <code>${esc(a.theorem)}</code>`:''}</dd>`;
if(f)h+=`<dt>${L.p_ref}</dt><dd><span class="pill ${f.ok?'bad':'ok'}">${L.p_exit} ${esc(f.exit)}</span> ${f.rule?`${L.p_rule} <code>${esc(f.rule)}</code>`:''}</dd>`;
}
h+='</dl>';
if(f&&f.line_before)h+=`<p class="status">${L.p_forgedline}</p><pre>${esc(f.line_before)}\n${esc(f.line_after)}</pre>`;
}
$('#planout').innerHTML=h;
drawGraph(j.graph);
// The picture sits ABOVE this button, so a repaint is off screen from where
// the reader just clicked. Say what changed, and say it with the run's own
// counts rather than a sentence that would still read well if they were 0.
const gc=(j.graph||{}).counts;
if(gc){const n=document.createElement('p');n.className='status';n.style.marginTop='8px';
n.textContent=`${L.g_repainted} ${gc.asserted??0} ${L.g_asserted.toLowerCase()}, ${gc.certified??0} ${L.g_certified.toLowerCase()}, ${gc.rejected??0} ${L.g_rejected.toLowerCase()}.`;
$('#planout').appendChild(n)}
};
// A force layout small enough to read. The palette is the front page's, so a
// visitor who scrolled past those figures meets the same three colours meaning
// the same three things on their own data.
const GC={asserted:'#475569',certified:'#34d399',rejected:'#fb3b53'};
// TEXT is not a line, and the asserted slate does not survive being set as
// type. Measured against this panel's #030a1c: #475569 gives 2.78:1, which
// fails WCAG AA for the 11px legend and reads on screen as a word that is
// almost not there, while the green and the red clear 7:1 beside it, so the
// key looked like two entries and a smudge. #94a3b8 is the page's own --muted
// and gives 7.71:1 on the same ground. The EDGES keep #475569: a line at 0.55
// opacity is a texture behind the argument, and the point of the grey is that
// it stays subordinate to the green.
const GT={asserted:'#94a3b8',certified:'#34d399',rejected:'#fb3b53'};
function drawGraph(g){
const card=$('#graphcard'), note=$('#graphnote'), svg=$('#graph'), cap=$('#i-graphp');
// An empty picture used to hide the whole section, which made "the run drew
// nothing" and "this page never had a picture" look exactly the same to a
// reader. Now the card stays, the box goes, and the note says which of the
// two happened.
if(!g||!g.edges||!g.edges.length){
card.hidden=false; svg.innerHTML=''; svg.style.display='none';
cap.textContent=''; note.hidden=false; note.textContent=g?L.g_empty:L.g_missing;
return;
}
card.hidden=false; svg.style.display=''; note.hidden=true;
// The caption states the picture's ACTUAL state. Before step 4 every edge is
// grey, and a caption that promised green and red beside a grey hairball
// would be describing a different run.
const proved=((g.counts||{}).certified||0)+((g.counts||{}).rejected||0)>0;
cap.textContent=proved?L.graphp:L.graphp_flat;
// A reader who asked the system for less motion gets the still picture. It
// loses the direction of travel and nothing else: every edge, colour, count
// and label below is drawn either way.
const still=!!(window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches);
const W=1040,H=440,PAD=26;
const idx=new Map(g.nodes.map((n,i)=>[n,i]));
const N=g.nodes.length;
// deterministic start, so the same sheet draws the same picture twice
let seed=N*2654435761%2147483647;
const rnd=()=>((seed=seed*16807%2147483647)/2147483647);
const px=[],py=[];
for(let i=0;i<N;i++){const a=2*Math.PI*i/N+rnd()*0.4;const r=(0.25+0.75*rnd())*Math.min(W,H)*0.42;
px.push(W/2+r*Math.cos(a));py.push(H/2+r*Math.sin(a));}
const E=g.edges.map(e=>[idx.get(e.s),idx.get(e.o)]).filter(([a,b])=>a!=null&&b!=null);
const K=Math.sqrt(W*H/Math.max(1,N))*0.62;
for(let step=0;step<260;step++){
const t=1-step/260, dx=new Float64Array(N), dy=new Float64Array(N);
for(let a=0;a<N;a++)for(let b=a+1;b<N;b++){
let ux=px[a]-px[b],uy=py[a]-py[b];let d2=ux*ux+uy*uy;
if(d2<0.01){ux=rnd()-0.5;uy=rnd()-0.5;d2=0.01}
const f=K*K/d2; dx[a]+=ux*f;dy[a]+=uy*f;dx[b]-=ux*f;dy[b]-=uy*f;
}
for(const [a,b] of E){
const ux=px[a]-px[b],uy=py[a]-py[b];const d=Math.hypot(ux,uy)||1;const f=d*d/K/18;
dx[a]-=ux/d*f;dy[a]-=uy/d*f;dx[b]+=ux/d*f;dy[b]+=uy/d*f;
}
for(let i=0;i<N;i++){
dx[i]+=(W/2-px[i])*0.012; dy[i]+=(H/2-py[i])*0.012;
const m=Math.hypot(dx[i],dy[i])||1, s=Math.min(m,20*t);
px[i]+=dx[i]/m*s; py[i]+=dy[i]/m*s;
}
}
// Fit to the BAND the nodes occupy, not to their extremes. A couple of
// loosely attached nodes drift far out, and scaling to min/max let them
// stretch the frame until everything else collapsed into one corner, which is
// what the first version drew. The front-page generator bands at 2/98 for the
// same reason; anything outside the band is clamped to the edge rather than
// dropped, because a node that exists should be visible.
// Frame the nodes that are actually together, and clamp the stragglers to the
// edge. Two earlier attempts failed for the same underlying reason: a handful
// of loosely attached nodes drift far from everything else, and any framing
// that includes them shrinks the real cluster to a corner. A 2/98 percentile
// excludes nothing below fifty nodes, and an interquartile band is generous
// on a star, where most nodes sit almost on top of the hub.
//
// So: take the centroid, take the MEDIAN distance to it, and frame what lies
// within 2.5 of those. That is scale free and it targets the actual problem.
const cx0=px.reduce((a,b)=>a+b,0)/N, cy0=py.reduce((a,b)=>a+b,0)/N;
const dist=px.map((_,i)=>Math.hypot(px[i]-cx0, py[i]-cy0)).sort((a,b)=>a-b);
const med=dist[Math.floor(dist.length/2)] || 1;
const keep=[...Array(N).keys()].filter(i=>Math.hypot(px[i]-cx0,py[i]-cy0) <= 2.5*med);
const inn = keep.length >= 3 ? keep : [...Array(N).keys()];
const x0=Math.min(...inn.map(i=>px[i])), x1=Math.max(...inn.map(i=>px[i]));
const y0=Math.min(...inn.map(i=>py[i])), y1=Math.max(...inn.map(i=>py[i]));
const sc=Math.min((W-2*PAD)/Math.max(1,x1-x0),(H-2*PAD-20)/Math.max(1,y1-y0));
const cl=(v,a,b)=>Math.max(a,Math.min(b,v));
const rawX=i=>cl(PAD+(px[i]-x0)*sc, PAD, W-PAD), rawY=i=>cl(PAD+(py[i]-y0)*sc, PAD, H-PAD-18);
// Then CENTRE what was actually drawn. Framing to the band and clamping the
// stragglers is right, but it leaves the content wherever the band happened
// to sit: the induced sheet drew from x=80 to x=760 of 1040 and left a third
// of the canvas empty beside it. This is a pure translation of the finished
// coordinates. It moves nothing relative to anything else, it cannot push a
// point out of the frame because the content already fitted, and the band
// framing above still decides the SCALE.
const RX=g.nodes.map((_,i)=>rawX(i)), RY=g.nodes.map((_,i)=>rawY(i));
const offX=(W-(Math.max(...RX)+Math.min(...RX)))/2;
const offY=((H-18)-(Math.max(...RY)+Math.min(...RY)))/2;
const FX=RX.map(v=>v+offX), FY=RY.map(v=>v+offY);
const X=i=>FX[i], Y=i=>FY[i];
const deg=new Array(N).fill(0); for(const [a,b] of E){deg[a]++;deg[b]++}
const order={asserted:0,certified:1,rejected:2};
const lines=g.edges.map((e,i)=>({e,i})).sort((a,b)=>order[a.e.kind]-order[b.e.kind])
.map(({e})=>{const a=idx.get(e.s),b=idx.get(e.o); if(a==null||b==null)return '';
const w=e.kind==='rejected'?2.6:(e.kind==='certified'?1.1:0.6);
// 0.34 put the grey layer at roughly (26,36,54) against this panel,
// which is a web you cannot see rather than a web drawn faintly. The
// README figure pulses its asserted edges between 0.45 and 0.95, so 0.55
// sits inside that band and is a step TOWARDS the front page, not away.
const o=e.kind==='asserted'?0.55:0.9;
const head=`<line x1="${X(a).toFixed(1)}" y1="${Y(a).toFixed(1)}" x2="${X(b).toFixed(1)}" y2="${Y(b).toFixed(1)}" stroke="${GC[e.kind]}" stroke-width="${w}" opacity="${o}"`;
// The refused line marches, at the figure's own 0.9s and 0;-24.
return e.kind==='rejected'&&!still
? head+' stroke-dasharray="7 5"><animate attributeName="stroke-dashoffset" dur="0.9s" repeatCount="indefinite" values="0;-24"/></line>'
: head+(e.kind==='rejected'?' stroke-dasharray="7 5"':'')+'/>'}).join('');
// The motion is the front page figure's, not a new one: one particle along a
// certified link, six along a rejected one, none along an asserted one, at
// 3.4s and 1.5s. Those numbers are `Graph3D.tsx`'s, by way of
// docs/assets/knowledge-graph.py, which draws the same three things for
// ies-core. A particle carries the DIRECTION of a claim, which a line cannot,
// and direction is the whole difference between a premise and a conclusion.
const PARTS={asserted:0,certified:1,rejected:6};
// A particle per certified edge is 130 elements on the sample sheet, against
// the 265 the README figure already carries, so the common case needs no
// thinning. A big sheet does: past the budget the certified particles drop
// to every Nth edge, and the six rejected ones always stay, because the
// refused line is what this section exists to show.
const nc=g.edges.reduce((n,e)=>n+(e.kind==='certified'?1:0),0);
const stride=Math.max(1,Math.ceil(nc/240));
let ci=0;
const parts=still?'':g.edges.map(e=>{
const n=PARTS[e.kind]||0; if(!n)return '';
if(e.kind==='certified'&&(ci++%stride))return '';
const a=idx.get(e.s),b=idx.get(e.o); if(a==null||b==null)return '';
const dur=e.kind==='certified'?3.4:1.5, r=e.kind==='rejected'?1.8:1.2;
const p=`M${X(a).toFixed(1)},${Y(a).toFixed(1)} L${X(b).toFixed(1)},${Y(b).toFixed(1)}`;
let s='';
for(let q=0;q<n;q++)s+=`<circle r="${r}" fill="${GC[e.kind]}" opacity="0.9"><animateMotion dur="${dur}s" repeatCount="indefinite" begin="-${(q*dur/n).toFixed(2)}s" path="${p}"/></circle>`;
return s}).join('');
const dots=g.nodes.map((n,i)=>`<circle cx="${X(i).toFixed(1)}" cy="${Y(i).toFixed(1)}" r="${(2.2+Math.min(4.4,deg[i]*0.26)).toFixed(1)}" fill="#7dd3fc" opacity="0.85"><title>${esc(n)}</title></circle>`).join('');
// Label only the busiest few, or the picture becomes a word cloud. And
// never two on top of each other: two labels in the same place do not give
// a reader two names, they give a reader neither, and the one underneath is
// hidden by the one that was drawn second. The front-page figures have a
// test for exactly this; this is the same rule in the page.
//
// Busiest first, then four candidate positions each, then give up on that
// label rather than stack it. A hub with no room beside it keeps its circle
// and its hover title, which is more than a smear of overlapping glyphs.
const top=[...g.nodes.keys()].sort((a,b)=>deg[b]-deg[a]).slice(0,7);
// MEASURED, not guessed. At font-size 10.5 in the page's own stack, Chrome
// reports these maxima per character class: narrow lowercase 3.50, wide
// lowercase (m, w) 8.17, other lowercase 5.25, uppercase 9.91 (that is W),
// digits 5.25, punctuation 5.25. A single average would have been wrong in
// both directions: I first used 5.60 for everything, which under-reserves a
// capital by nearly half and over-reserves an `i` by 80%.
//
// The UPPER BOUND is used on purpose. Over-reserving can drop a label, which
// is visible and harmless; under-reserving lets two labels overlap, which is
// the defect this exists to prevent and which hides both of them.
const cw=c=>'ijltfr'.includes(c)?3.5:'mw'.includes(c)?8.2
:(c>='A'&&c<='Z')?9.9:5.3;
const wof=t=>[...t].reduce((a,c)=>a+cw(c),0);
// The vertical extent, also measured: a rendered box is 12.3 tall and sits
// from about 10 above the baseline to about 3 below it. My first version
// modelled it as [y-12, y], which forgot the DESCENDER, and two baselines
// exactly 12 apart passed the check and then overlapped by a third of a
// pixel on screen. Ascent and descent are named because they are two
// different measurements and averaging them is how that bug happened.
const ASC=10, DESC=3, GAP=4; // GAP, not PAD: the layout already owns PAD
const placed=[];
const hits=(x,y,w,p)=>x<p.x+p.w+GAP && p.x<x+w+GAP && y-ASC<p.y+DESC && p.y-ASC<y+DESC;
const free=(x,y,w)=>x>3 && x+w<W-3 && y>ASC+2 && y<H-30 && !placed.some(p=>hits(x,y,w,p));
const labels=top.map(i=>{
const t=g.nodes[i], w=wof(t), x=X(i), y=Y(i);
const spot=[[x+7,y+4],[x-7-w,y+4],[x-w/2,y-9],[x-w/2,y+17]].find(([a,b])=>free(a,b,w));
if(!spot) return '';
placed.push({x:spot[0],y:spot[1],w});
return `<text x="${spot[0].toFixed(1)}" y="${spot[1].toFixed(1)}" font-size="10.5" fill="#cbd5e1">${esc(t)}</text>`;
}).join('');
const c=g.counts||{};
const key=[['asserted',L.g_asserted],['certified',L.g_certified],['rejected',L.g_rejected]]
.map(([k,lab],m)=>`<rect x="${20+m*186}" y="${H-24}" width="20" height="3" fill="${GT[k]}"/><text x="${48+m*186}" y="${H-20}" font-size="11" font-weight="700" fill="${GT[k]}">${lab}</text><text x="${130+m*186}" y="${H-20}" font-size="11" fill="#94a3b8" text-anchor="end">${c[k]??0}</text>`).join('');
$('#graph').innerHTML=`<svg viewBox="0 0 ${W} ${H}" width="100%" role="img" aria-label="${esc(proved?L.graphp:L.graphp_flat)}">${lines}${parts}${dots}${labels}${key}</svg>`;
// The legend prints what was DRAWN. On the EPC sample that is 170 of 3,607
// asserted, so a reader who takes the legend for the run's own count is out
// by a factor of twenty. The API already counted the difference and named a
// reason for every missing edge; this is the line that says so. The numbers
// come from the run, and the reasons are only listed when they are non-zero,
// so the sentence cannot claim a category that did not happen.
const t=g.total||{}, d=g.drawn||{}, sk=g.skipped||{};
const n=v=>Number(v||0).toLocaleString();
const drawn=['asserted','certified','rejected']
.filter(k=>(t[k]||0)>0)
.map(k=>`${n(d[k])} ${L.g_of} ${n(t[k])} ${L[k==='asserted'?'g_asserted':k==='certified'?'g_certified':'g_rejected'].toLowerCase()}`)
.join(', ');
const why=[['literal',L.g_lit],['plumbing',L.g_plumb],['duplicate',L.g_dup],['over_budget',L.g_budget]]
.filter(([k])=>(sk[k]||0)>0).map(([k,lab])=>`${n(sk[k])} ${lab}`).join(', ');
note.hidden=false;
note.textContent=`${L.g_drawn} ${drawn}.` + (why?` ${L.g_undrawn} ${why}.`:'');
}
function esc(s){return String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]))}
function short(s){s=String(s||'');const i=Math.max(s.lastIndexOf('#'),s.lastIndexOf('/'));return i>=0&&i<s.length-1?s.slice(i+1):s}
function pretty(s){try{return JSON.stringify(typeof s==='string'?JSON.parse(s):s,null,1)}catch{return String(s)}}
</script>
</body>
</html>