@casadi/casadi-viz 0.1.0-dev.0

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/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/NOTICE ADDED
@@ -0,0 +1,3 @@
1
+ Viewer source derived from CasADi, copyright 2010-2026 the CasADi authors.
2
+ Distributed under LGPL-3.0-or-later.
3
+ The renderer is @viz-js/viz, including Graphviz. See dist/licenses.
package/README.md ADDED
@@ -0,0 +1,169 @@
1
+ # @casadi/casadi-viz
2
+
3
+ An embeddable viewer for CasADi expressions and Functions. It displays graph
4
+ bundles produced by CasADi's C++ exporter, with matrix previews, nested-function
5
+ navigation and optional evaluation trace replay.
6
+
7
+ This is a working development prototype. The npm name is prepared; the package
8
+ has not been published. The browser playground requires a CasADi WASM build
9
+ containing `Function.export_graph`; the published 3.8.0 runtime predates this API.
10
+
11
+ ## Embed a viewer
12
+
13
+ After publication, the intended installation is `npm install @casadi/casadi-viz`.
14
+ For now, install a tarball made with `npm pack`, or run the examples below.
15
+
16
+ ```js
17
+ import {createGraphViewer} from '@casadi/casadi-viz';
18
+
19
+ const viewer = createGraphViewer(document.querySelector('#graph'));
20
+ await viewer.setGraph(JSON.parse(f.export_graph()));
21
+ ```
22
+
23
+ Give the host element a height, for example `height: 650px`. Each instance owns
24
+ its shadow DOM, interaction state and layout worker. It does not change the
25
+ page's styles, title or global event handlers. The viewer has no dependency on
26
+ `@casadi/casadi-wasm` and never evaluates CasADi expressions itself.
27
+
28
+ `setGraph` also accepts a JSON string. The same API can display a `.casadi_viz`
29
+ file loaded with `File.text()` or a bundle generated on a server. No fetch of
30
+ graph data occurs inside the viewer.
31
+
32
+ ```js
33
+ await viewer.setGraph(await file.text());
34
+ await viewer.loadTrace(traceFile); // Blob/File or JSONL string
35
+ viewer.setView('expression'); // or 'function'
36
+ viewer.destroy(); // release timers, workers and DOM
37
+ ```
38
+
39
+ `setGraph` resolves when the first layout is installed. Replacing a graph cancels
40
+ its pending layout and clears selection, breadcrumb and trace state. An invalid
41
+ bundle is rejected before replacing the current graph. Superseded pending
42
+ `setGraph` calls reject with `AbortError`.
43
+
44
+ Trace controls remain hidden until the user activates **Trace**, even when a
45
+ trace has been loaded programmatically. Both matrix toggles start enabled.
46
+
47
+ ## Browser and bundler distributions
48
+
49
+ `dist/index.js` is an ES module, with TypeScript declarations. A classic-script
50
+ build exposes `CasadiViz.createGraphViewer` in `dist/casadi-viz.global.js`.
51
+ `dist/viz-global.js` is the pinned Viz.js renderer, including its WASM payload.
52
+ Keep it next to `index.js`, or supply its URL explicitly when your bundler moves
53
+ assets:
54
+
55
+ ```js
56
+ const viewer = createGraphViewer(host, {
57
+ runtime: {url: '/assets/viz-global.js'}
58
+ });
59
+ ```
60
+
61
+ `runtime: {source: rendererSource}` embeds the renderer in the worker instead,
62
+ which is also how a fully offline native HTML export works. Browser deployments
63
+ must allow the component's blob worker and the configured renderer location.
64
+ Serve the module-based examples over HTTP; native standalone exports can be
65
+ opened directly as `file://` pages with an embedded renderer.
66
+
67
+ ## Run the prototypes
68
+
69
+ ```sh
70
+ npm ci
71
+ npm run build
72
+ npm run dev
73
+ ```
74
+
75
+ Open http://127.0.0.1:8766/examples/bundles.html for the independent bundle viewer.
76
+ It has sparse SX/MX examples and nested calls, and accepts uploaded bundles.
77
+
78
+ The expression playground at `/examples/index.html` additionally needs a local
79
+ CasADi WASM runtime:
80
+
81
+ ```sh
82
+ node scripts/stage-runtime.mjs /path/to/casadi/build-viz-wasm/swig/wasm-js
83
+ ```
84
+
85
+ It runs edited JavaScript in a dedicated worker, constructs the expression,
86
+ exports the graph through C++, and evaluates or optimizes it with `sqpmethod`
87
+ and `qrqp`. An optional `g` defines equality constraints (`g = 0`). The example
88
+ is a small smooth optimization playground; it is not a general-purpose solver
89
+ configuration interface.
90
+
91
+ Each run uses a fresh computation worker, and releases it after evaluation. A
92
+ cancel button can terminate a long-running solve. Graph layout uses a separate
93
+ worker. Optional traces record the displayed Function's evaluation at the
94
+ selected point or solution, not every solver-internal evaluation. Expressions
95
+ are JavaScript written by the page's user; do not automatically run third-party
96
+ code with this demo.
97
+
98
+ The runtime and solver plugins are not part of this npm package or its Git
99
+ repository. See `toolchain/README.md` for the tested source-build recipe.
100
+
101
+ ## Native HTML export uses this same viewer
102
+
103
+ ```sh
104
+ npm run build
105
+ node scripts/vendor-casadi.mjs /path/to/casadi-worktree
106
+ ```
107
+
108
+ This copies `dist/standalone.html` into CasADi's embedded resource and records its
109
+ package version and SHA-256. Rebuild CasADi afterwards. The template has exactly
110
+ two placeholders: `@@GRAPH_DATA@@` and `@@VIZ_CONFIG@@`; C++ fills these without
111
+ executing JavaScript or contacting npm.
112
+
113
+ The template is generated from the same component used by the npm entry point.
114
+ It contains the viewer code and CSS. CasADi's `viz_js` option additionally embeds
115
+ the Viz.js runtime; otherwise the existing pinned CDN configuration applies.
116
+ No JavaScript toolchain is required for ordinary CasADi builds using the vendored
117
+ asset. Maintain viewer source here, regenerate the artifact, and vendor an
118
+ explicit version when updating CasADi.
119
+
120
+ C++ remains responsible for graph extraction, JSON serialization and standalone
121
+ DOT generation. Interactive DOT assembly and rendering live in this repository.
122
+
123
+ ## Bundle contract
124
+
125
+ The package accepts `format: "casadi_viz", version: 1`. The root Function is
126
+ index 0; `functions[i]` is index `i+1`. Call nodes' `callee` fields index that
127
+ registry. `include_functions: false` exports keep calls but omit their internals.
128
+ Sparsities are compressed-column arrays; constants are strings in nonzero order.
129
+ Instruction IDs match CasADi `dump_trace` records. TypeScript declarations describe
130
+ the fields. Full mathematical metadata remains available independently of the
131
+ viewer-specific presentation.
132
+
133
+ A bundle is a graph description, not a serialized executable CasADi Function.
134
+ Changing values needs CasADi evaluation; changing expressions produces a new
135
+ bundle. A matching trace must be supplied for each graph revision.
136
+
137
+ ## Validation and release preparation
138
+
139
+ ```sh
140
+ npm test
141
+ npx playwright install chromium
142
+ # In another terminal: npm run dev
143
+ npm run test:browser
144
+ VIZ_TEST_WASM=1 npm run test:browser # requires the staged runtime
145
+ npm pack --dry-run
146
+ ```
147
+
148
+ Browser tests cover independent instances, navigation, toggles and lifecycle.
149
+ The optional WASM tests cover real C++ graph export, optimization, trace replay,
150
+ expression edits and recovery from an editor error. Native CasADi's Python tests
151
+ check JSON/file equivalence and overload dispatch.
152
+
153
+ The GitHub workflow builds and tests from source, then packs exactly those built
154
+ files into the downloadable `casadi-viz-package` artifact. Published npm packages
155
+ come from this CI artifact; the publish job does not rebuild or run lifecycle
156
+ scripts. Pushes and pull requests build artifacts without publishing to npm.
157
+
158
+ To release, update the version in `package.json` and `package-lock.json`, commit,
159
+ and publish a GitHub release with the matching `v<version>` tag. That release
160
+ runs the build and tests before publishing its artifact to npm. Prereleases use
161
+ npm's `next` tag; stable versions use `latest`. Version and prerelease mismatches
162
+ fail before packaging.
163
+
164
+ The release job uses npm trusted publishing (OIDC), with provenance. Before the
165
+ first npm release, arrange package access and configure npm's trusted publisher
166
+ for GitHub organization `casadi`, repository `casadi-viz`, workflow `test.yml`,
167
+ with direct publishing allowed and no environment restriction. This registry-side
168
+ configuration has not been performed by the repository setup. See
169
+ [npm trusted publishing](https://docs.npmjs.com/trusted-publishers/).
@@ -0,0 +1,25 @@
1
+ const __casadiVizScriptURL=document.currentScript?.src || document.baseURI;
2
+ var CasadiViz=(()=>{var he=Object.defineProperty;var De=Object.getOwnPropertyDescriptor;var Be=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var Ie=(E,N)=>{for(var R in N)he(E,R,{get:N[R],enumerable:!0})},je=(E,N,R,g)=>{if(N&&typeof N=="object"||typeof N=="function")for(let L of Be(N))!Me.call(E,L)&&L!==R&&he(E,L,{get:()=>N[L],enumerable:!(g=De(N,L))||g.enumerable});return E};var Pe=E=>je(he({},"__esModule",{value:!0}),E);var $e={};Ie($e,{createGraphViewer:()=>Ge});var Ee=`
3
+ :host{font:14px Arial,Helvetica,sans-serif;color:#222;background:white;--accent:#b00000;--blue:#34658b;--line:#e8e8e8}
4
+ *{box-sizing:border-box}[hidden]{display:none!important}.viewer{margin:0;height:100%;display:flex;flex-direction:column}
5
+ header{padding:16px 24px;border-bottom:1px solid var(--line);display:flex;gap:20px;align-items:center;justify-content:space-between;flex-wrap:wrap}
6
+ .brand{font-size:19px;font-weight:700;letter-spacing:-.04em}.brand span{color:var(--accent)}h1{font-size:18px;margin:0;font-weight:400}#meta{color:#888;font-size:12px;margin-top:5px}.identity{display:flex;gap:24px;align-items:center;min-width:0}#breadcrumbs{display:flex;gap:7px;align-items:center;flex-wrap:wrap}#breadcrumbs button{border:0;padding:2px 0;font-size:17px;color:#34658b;background:none}#breadcrumbs button:disabled{opacity:1;color:#222;cursor:default}#breadcrumbs span{color:#aaa}.toggle{display:flex;align-items:center;gap:7px;font-size:12px;cursor:pointer;white-space:nowrap}.toggle input{appearance:none;position:relative;width:28px;height:16px;border-radius:12px;background:#ccc;margin:0;cursor:pointer;flex-shrink:0}.toggle input:checked{background:var(--accent)}.toggle input::after{content:"";position:absolute;top:2px;left:2px;width:12px;height:12px;border-radius:50%;background:white;transition:transform .12s}.toggle input:checked::after{transform:translateX(12px)}.toggle input:focus-visible{outline:2px solid #34658b;outline-offset:2px}
7
+ button,.upload{font:inherit;background:white;border:1px solid #ddd;border-radius:4px;padding:7px 11px;cursor:pointer;white-space:nowrap;color:inherit}button:hover,.upload:hover{background:#f6f6f6}button:disabled{opacity:.35;cursor:default}button[aria-pressed=true]{border-color:var(--accent);color:var(--accent);background:#fff6f6}.upload{display:inline-block}.upload:focus-within{outline:2px solid var(--blue)}.upload input{position:absolute;width:1px;height:1px;opacity:0}
8
+ #toolbar{display:flex;gap:8px;align-items:center;padding:10px 24px;border-bottom:1px solid var(--line);flex-wrap:wrap;background:#fafafa}#timeline{flex:1;min-width:100px;accent-color:var(--accent)}#step-label{min-width:100px;font-variant-numeric:tabular-nums;color:#777;font-size:12px}select{font:inherit;border:1px solid #ddd;border-radius:4px;padding:6px;background:white}
9
+ main{display:flex;flex:1;min-height:0}#canvas{flex:1;position:relative;overflow:hidden;background:white}#canvas svg{width:100%;height:100%;display:block;touch-action:none}#canvas .node,#canvas .io-node,#canvas .value-node{cursor:pointer}#canvas .node text,#canvas .io-node text,#canvas .value-node text{pointer-events:none}#canvas .io-node.active>ellipse,#canvas .node.active>ellipse,#canvas .node.active>polygon,#canvas .node.active>path{stroke:#222;stroke-width:2.5}#canvas .io-node.executed>ellipse,#canvas .node.executed>ellipse,#canvas .node.executed>polygon,#canvas .node.executed>path{stroke:var(--blue);stroke-width:2.5}#canvas .node.failed>ellipse,#canvas .node.failed>polygon,#canvas .node.failed>path{stroke:#e18c24;stroke-width:3}#canvas .value-node.active>polygon{stroke:var(--blue);stroke-width:1.5}#canvas .trace-value{font:11px ui-monospace,monospace;fill:var(--blue);paint-order:stroke;stroke:white;stroke-width:4px;stroke-linejoin:round}#canvas .edge path{stroke:var(--blue)}#canvas .edge polygon{fill:var(--blue);stroke:var(--blue)}
10
+ #loading{position:absolute;inset:0;display:grid;place-content:center;text-align:center;color:#777;gap:12px;background:#fffffff2}#loading p{max-width:420px;margin:0;padding:0 20px}#loading button{justify-self:center}
11
+ aside{width:340px;max-width:42vw;background:white;border-left:1px solid var(--line);padding:20px;overflow:auto}.selection-header{display:flex;align-items:center;justify-content:space-between;gap:12px}aside h2{font-size:18px;font-weight:400;margin:0}aside h3{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#888;margin:22px 0 8px}#close-inspector{border:0;font-size:20px;padding:0 5px}pre{font:12px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#f7f7f7;padding:10px;margin:14px 0 0}.hint{font-size:12px;line-height:1.6;color:#888}.port{border-top:1px solid #eee;padding:10px 0}.port-title{font:12px ui-monospace,monospace;color:#666;margin-bottom:8px}.port-value{font:12px/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.matrix{border-collapse:collapse;margin:8px 0;font:11px ui-monospace,monospace}.matrix td{border:1px solid #ddd;padding:5px;text-align:center;white-space:nowrap}.matrix td.nz{background:#eee}.matrix td.zero{color:#aaa}.matrix td.spy{width:16px;height:16px;padding:3px;background:white;border:0}.matrix td.nz.spy::after{content:"";display:block;background:#111;width:9px;height:9px}.matrix:has(.spy){border:1px solid #ddd}.matrix-wrap{overflow:auto}.state{font-size:12px;color:var(--blue);margin:14px 0}details{font-size:12px;color:#666;margin-top:10px}summary{cursor:pointer}
12
+ footer{padding:8px 24px;border-top:1px solid var(--line);display:flex;justify-content:space-between;gap:16px;font-size:11px;color:#888}#status.error{color:#b00000}#status.warning{color:#936015}#trace-name{max-width:50%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.right-tools{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.legend{display:flex;gap:14px;align-items:center}.legend span::before{content:"";display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px;background:var(--accent)}.legend .symbol::before{background:#34658b}.legend .constant::before{background:#38754d}
13
+ @media(max-width:700px){header{padding:12px}.identity{gap:12px}.brand{font-size:16px}#toolbar{padding:10px}aside{width:240px;padding:12px}footer{padding:8px}}
14
+ `;var Le=`<div class="viewer">
15
+ <header><div class="identity"><div class="brand">Cas<span>AD</span>i</div><div><nav id="breadcrumbs" aria-label="Function navigation"></nav><div id="meta"></div></div></div><div class="right-tools"><select id="view-mode" aria-label="Graph view"><option value="expression">Expression view</option><option value="function">Function view</option></select><label class="toggle"><input id="detail-toggle" type="checkbox" role="switch" checked>Show matrix contents</label><label class="toggle"><input id="size-toggle" type="checkbox" role="switch" checked>Show matrix sizes</label><button id="fit">Fit graph</button><button id="trace-toggle" aria-pressed="false" aria-controls="toolbar">Trace</button></div></header>
16
+ <div id="toolbar" hidden><label class="upload">Load trace<input id="trace-file" type="file" accept=".jsonl,.json,.txt" aria-label="Load evaluation trace"></label><button id="start" title="Rewind" disabled>&#8612;</button><button id="back" title="Previous instruction" disabled>&#8592;</button><button id="play" disabled>Play</button><button id="next" title="Next instruction" disabled>&#8594;</button><button id="end" title="Last instruction" disabled>&#8614;</button><input id="timeline" type="range" min="0" max="0" value="0" disabled aria-label="Evaluation position"><span id="step-label">No trace loaded</span><select id="speed" aria-label="Playback speed"><option value="800">Slow</option><option value="350" selected>Normal</option><option value="80">Fast</option></select></div>
17
+ <main><div id="canvas"><div id="loading"><p id="loading-text">Laying out the graph&#8230;</p><button id="cancel-layout">Cancel layout</button></div></div><aside id="details" hidden><div class="selection-header"><h2 id="selection-title"></h2><button id="close-inspector" aria-label="Close inspector">&#215;</button></div><div id="inspector"></div></aside></main>
18
+ <footer><span id="status" role="status">Preparing graph&#8230;</span><div class="right-tools"><span id="trace-name" hidden></span><div class="legend" aria-label="Node colors"><span class="symbol">Symbols</span><span class="constant">Constants</span><span>Operations</span></div></div></footer>
19
+ </div>`;function Te(E){if(!E||E.format!=="casadi_viz"||E.version!==1)throw new Error("Expected a casadi_viz bundle (version 1)");if(!Array.isArray(E.functions))throw Error("Expected a functions array");let N=[E,...E.functions];for(let R of N){for(let g of["nodes","edges","inputs","outputs"])if(!Array.isArray(R[g]))throw Error("Missing graph array: "+g);R.nodes.forEach((g,L)=>{if(g.id!==L)throw Error("Instruction IDs must be consecutive");if(g.callee!==void 0&&(!Number.isInteger(g.callee)||!N[g.callee]))throw Error("Invalid callee reference");for(let V of["inputs","outputs","input_names","output_names","constants"])if(!Array.isArray(g[V]))throw Error("Missing instruction array: "+V)});for(let g of R.edges)if(!Number.isInteger(g.from)||!Number.isInteger(g.to)||!R.nodes[g.from]||!R.nodes[g.to]||!Number.isInteger(g.input)||!Number.isInteger(g.output)||g.input<0||g.input>=R.nodes[g.to].inputs.length||g.output<0||g.output>=R.nodes[g.from].outputs.length)throw Error("Invalid dependency edge")}return E}function Ge(E,N={}){if(!E||typeof E.attachShadow!="function")throw new TypeError("Expected a host element");let R=E.shadowRoot||E.attachShadow({mode:"open"}),g=N.runtime||{url:new URL("./viz-global.js",__casadiVizScriptURL).href},L=null,V=!1;return{async setGraph($){if(V)throw Error("Viewer has been destroyed");let z=Te(typeof $=="string"?JSON.parse($):$);return L?.destroy(),R.innerHTML="<style>"+Ee+"</style>"+Le,L=Ve(R,z,g),L.ready},async loadTrace($){if(!L||V)throw Error("Load a graph before loading a trace");return L.loadTrace($)},setView($){if(!L||V)throw Error("Load a graph before selecting a view");L.setView($)},destroy(){L?.destroy(),L=null,V=!0,R.replaceChildren()}}}function Ve(E,N,R){let g,L,V=new Promise((e,i)=>{g=e,L=i}),$=[N,...N.functions||[]],z=N,l=e=>E.querySelector("#"+e),W=(e,i="")=>{l("status").textContent=e,l("status").className=i},w=null,me=null,f=null,y=0,A=null,te=null,j=!1,le=!0,ue=!0,G=N.view||"function",P=[{model:z,viewMode:G,trace:null,cursor:0,selected:null,traceName:""}],Q=new Map,X=new Map,ne=null,ge=e=>typeof e=="number"?Object.is(e,-0)?"-0":Number(e.toPrecision(7)).toString():e,be=e=>e.map(i=>i===null?"unused":"["+i.slice(0,3).map(ge).join(", ")+(i.length>3?", \u2026":"")+"]").join(" ; ");function B(){clearInterval(te),te=null,l("play").textContent="Play"}function pe(){let e=f?f.count:0;l("start").disabled=l("back").disabled=!f||y===0,l("next").disabled=l("end").disabled=!f||y===e,l("play").disabled=!f||e===0,l("timeline").disabled=!f,l("timeline").max=e,l("timeline").value=y,l("step-label").textContent=f?`${y.toLocaleString()} / ${e.toLocaleString()}`:"No trace loaded"}function xe(e,i,s,r,d=!1){let t=document.createElement("section"),c=document.createElement("h3");if(c.textContent=e,t.append(c),!i.length){let o=document.createElement("div");o.className="hint",o.textContent="None",t.append(o)}return i.forEach((o,u)=>{let p=document.createElement("div");p.className="port";let b=document.createElement("div");b.className="port-title",b.textContent=`${r[u]}${ue?" \xB7 "+o.shape.join("-by-"):""} \xB7 ${o.row.length} nonzeros`;let k=document.createElement("div");if(k.className="port-value",k.textContent=s===void 0?j?"Not evaluated":"":s[u]===null?"Unused / absent buffer":"["+s[u].map(M=>Object.is(M,-0)?"-0":String(M)).join(", ")+"]",p.append(b,k),le&&o.shape[0]*o.shape[1]!==1&&p.append(Ce(o,s?.[u],d)),o.row.length!==o.shape[0]*o.shape[1]){let M=document.createElement("details"),T=document.createElement("summary"),I=document.createElement("pre");T.textContent="Sparsity",I.textContent="colind: "+JSON.stringify(o.colind)+`
20
+ row: `+JSON.stringify(o.row),M.append(T,I),p.append(M)}t.append(p)}),t}function Ce(e,i,s){let r=document.createElement("div");r.className="matrix-wrap";let d=document.createElement("table");d.className="matrix";let t=new Map;for(let c=0;c<Math.min(8,e.shape[1]);c++)for(let o=e.colind[c];o<e.colind[c+1];o++)e.row[o]<8&&t.set(e.row[o]+","+c,o);for(let c=0;c<Math.min(8,e.shape[0]);c++){let o=d.insertRow();for(let u=0;u<Math.min(8,e.shape[1]);u++){let p=o.insertCell(),b=t.get(c+","+u);p.className=b===void 0?"zero":"nz",s||p.classList.add("spy"),p.textContent=s?b===void 0?".":String(i[b]):"",p.title=b===void 0?"Structural zero":`Row ${c}, column ${u}, nonzero ${b}`}}if(r.append(d),e.shape.some(c=>c>8)){let c=document.createElement("div");c.className="hint",c.textContent="Showing the first 8 rows / columns. Full sparsity below.",r.append(c)}return r}function U(){if(A===null)return;let e=z.nodes[A],i=j&&f&&A<y;l("selection-title").textContent=G==="expression"&&e.kind==="input"?e.symbol:G==="function"&&["input","output"].includes(e.kind)?z[e.kind+"s"][e.io_index].name:e.display;let s=l("inspector");if(s.replaceChildren(),j){let o=document.createElement("div");o.className="state",o.textContent=i?f.after[A]===void 0?"Interrupted":"Evaluated":"Not evaluated",s.append(o)}let r=document.createElement("pre");if(r.textContent=e.formula,e.callee!==void 0){let o=document.createElement("button");o.id="enter-function",o.textContent="Step into "+e.display,o.onclick=()=>ke(e.id),s.append(o)}else if(e.kind==="call"){let o=document.createElement("p");o.className="hint",o.textContent="No internal graph was included for this "+e.callee_type+".",s.append(o)}if(s.append(r,xe("Inputs",e.inputs,i?f.before[A]:void 0,e.input_names),xe("Outputs",e.outputs,i?f.after[A]:e.kind==="constant"?[e.constants]:void 0,e.output_names,e.kind==="constant")),e.mapping){let o=document.createElement("h3"),u=document.createElement("pre");o.textContent="Nonzero mapping",u.textContent=e.mapping.map((p,b)=>`${b}: ${p}`).join(", "),s.append(o,u)}let d=document.createElement("details"),t=document.createElement("summary"),c=document.createElement("pre");t.textContent="Evaluator expression",c.textContent=e.expression,d.append(t,c),s.append(d)}function oe(e){if(A!==null){Q.get(A)?.classList.remove("active");for(let i of X.get(A)||[])i.element.classList.remove("active")}A=e,Q.get(e)?.classList.add("active");for(let i of X.get(e)||[])i.element.classList.add("active");l("details").hidden=!1,U()}l("close-inspector").onclick=()=>{Q.get(A)?.classList.remove("active");for(let e of X.get(A)||[])e.element.classList.remove("active");A=null,l("details").hidden=!0};function ie(e){let i=Q.get(e),s=j&&f&&e<y,r=s&&f.after[e]!==void 0;i?.classList.toggle("executed",!!r),i?.classList.toggle("failed",!!s&&!r);let d=i?.querySelector(".trace-value");if(i&&!d){d=document.createElementNS("http://www.w3.org/2000/svg","text"),d.classList.add("trace-value");let o=i.getBBox();d.setAttribute("x",o.x+o.width/2),d.setAttribute("y",o.y+o.height+14),d.setAttribute("text-anchor","middle"),i.append(d)}let t=s?z.nodes[e].kind==="output"?f.before[e]:f.after[e]:void 0,c=t===void 0?"":be(t);d&&(d.textContent=c.length>36?c.slice(0,35)+"\u2026":c);for(let o of X.get(e)||[]){if(o.boundary){Se(o.boundary);continue}let u=t?.[o.port];for(let p of o.cells)p.element.textContent=le&&u?ge(u[p.index]):p.label}}function Se(e){let i=Array(Math.min(4,e.sp.row.length)).fill("?"),s=!1;for(let r of e.owners){if(!j||!f||r.node>=y)continue;let d=(e.boundaryKind==="input"?f.after[r.node]:f.before[r.node])?.[0];if(d){s=!0;for(let t=0;t<d.length&&r.offset+t<i.length;t++)i[r.offset+t]=d[t]}}e.traceLabel.textContent=s?be([i]):"",e.traceLabel.parentNode.classList.toggle("executed",!!s&&e.owners.every(r=>r.node<y&&f.after[r.node]!==void 0))}l("trace-toggle").onclick=()=>{j=!j,B(),l("trace-toggle").setAttribute("aria-pressed",String(j)),l("toolbar").hidden=!j,l("trace-name").hidden=!j;for(let e=0;e<y;e++)ie(e);U(),W(j?f?"Trace loaded. Step through the evaluation.":"Load a trace file to replay an evaluation. Files stay in your browser.":"Select a node to inspect it. Scroll to zoom; drag to pan.")};function Y(e,i=!0){let s=y;y=Math.max(0,Math.min(f?f.count:0,e));for(let r=Math.min(s,y);r<Math.max(s,y);r++)ie(r);if(i&&y>0){let r=y-1;G==="expression"&&z.nodes[r].kind==="output"&&(r=z.edges.find(d=>d.to===r)?.from??r),oe(r)}else U();pe(),f&&y===f.count&&B()}l("start").onclick=()=>{B(),Y(0)},l("back").onclick=()=>{B(),Y(y-1)},l("next").onclick=()=>{B(),Y(y+1)},l("end").onclick=()=>{B(),Y(f.count)},l("timeline").oninput=()=>{B(),Y(Number(l("timeline").value))},l("play").onclick=()=>{if(te){B();return}y===f.count&&Y(0),l("play").textContent="Pause",te=setInterval(()=>Y(y+1),Number(l("speed").value))},l("speed").onchange=()=>{te&&(B(),l("play").click())};function ce(e,i,s){if(!Array.isArray(e)||e.length!==i.length)throw Error(s+": wrong number of values");e.forEach((r,d)=>{if(r!==null){if(!Array.isArray(r)||r.length!==i[d].row.length)throw Error(s+": nonzero count does not match the graph");for(let t of r)if(!(typeof t=="number"&&Number.isFinite(t))&&!["nan","inf","-inf"].includes(t))throw Error(s+": invalid numerical value")}})}async function Ne(e,i=z){let s={before:[],after:[],count:0,ended:!1,status:null},r=!1,d=!1,t=!1,c=!1,o=!1,u=0,p=0;function b(I){if(!I.trim())return;p++;let m=JSON.parse(I);if(!m||typeof m!="object"||Array.isArray(m))throw Error("Expected a trace record");if(c)throw Error("Unexpected data after trace end");if(!r){if(m.event!=="header"||m.format!=="casadi_trace"||m.version!==1)throw Error("Expected a dump_trace JSONL file (version 1)");if(m.function!==i.name||m.type!==i.type)throw Error("This trace belongs to a different function");r=!0;return}if(!d){if(m.event!=="inputs")throw Error("Missing function inputs");ce(m.values,i.inputs.map(_=>_.sparsity),"Function inputs"),d=!0;return}if(m.event==="error"){c=!0,s.status="error";return}if(m.event==="outputs"){if(o||u!==i.nodes.length||t)throw Error("Unexpected function outputs");ce(m.values,i.outputs.map(_=>_.sparsity),"Function outputs"),t=!0;return}if(m.event==="end"){if(!Number.isInteger(m.status))throw Error("Invalid evaluation status");if(m.status===0&&(!t||o||u!==i.nodes.length))throw Error("Successful trace is missing instructions");s.ended=!0,s.status=m.status,c=!0;return}let O=m.instruction;if(t||!Number.isInteger(O)||O!==u||O>=i.nodes.length||m.op!==i.nodes[O].op)throw Error("Instruction sequence does not match this graph");if(m.phase==="inputs"&&!o)ce(m.values,i.nodes[O].inputs,"Instruction "+O+" inputs"),s.before[O]=m.values,s.count=O+1,o=!0;else if(m.phase==="outputs"&&o)ce(m.values,i.nodes[O].outputs,"Instruction "+O+" outputs"),s.after[O]=m.values,o=!1,u++;else throw Error("Unexpected instruction phase")}let k=e.stream().getReader(),M=new TextDecoder,T="";try{for(;;){let{done:I,value:m}=await k.read();if(I)break;T+=M.decode(m,{stream:!0});let O=0,_;for(;(_=T.indexOf(`
21
+ `,O))!==-1;)b(T.slice(O,_)),O=_+1;T=T.slice(O)}if(T+=M.decode(),T.trim()&&b(T),!r||!d)throw Error("Incomplete trace header")}catch(I){throw await k.cancel(),Error(`Line ${p}: ${I.message}`)}finally{k.releaseLock()}return s}let re=0;async function we(e){if(typeof e=="string"&&(e=new File([e],"evaluation.trace.jsonl")),!e)return;let i=++re;B(),W("Reading trace\u2026");try{let s=await Ne(e);if(i!==re)return;let r=y;f=s,y=0;for(let d=0;d<r;d++)ie(d);pe(),U(),l("trace-name").textContent=e.name,W(s.ended&&s.status===0?"Trace loaded. Step through the evaluation.":"Partial or failed evaluation. Recorded instructions are available.",s.ended&&s.status===0?"":"warning")}catch(s){throw i===re&&W(s.message,"error"),s}l("trace-file").value=""}l("trace-file").onchange=()=>we(l("trace-file").files[0]).catch(()=>{});function fe(){l("view-mode").value=G;let e=l("breadcrumbs");e.replaceChildren(),P.forEach((i,s)=>{if(s){let d=document.createElement("span");d.textContent="/",e.append(d)}let r=document.createElement("button");r.textContent=i.model.name,r.disabled=s===P.length-1,r.disabled&&(r.id="name",r.setAttribute("aria-current","page")),r.onclick=()=>Re(s),e.append(r)}),l("meta").textContent=`${z.type} \xB7 ${z.nodes.length.toLocaleString()} instructions \xB7 ${z.edges.length.toLocaleString()} connections`}function ve(){Object.assign(P[P.length-1],{viewMode:G,trace:f,cursor:y,selected:A,traceName:l("trace-name").textContent})}function ye(){B(),++re,{model:z,viewMode:G,trace:f,cursor:y,selected:A}=P[P.length-1],l("trace-name").textContent=P[P.length-1].traceName,l("details").hidden=A===null,fe(),pe(),U(),ee(),W(f?"Trace restored. Step through the evaluation.":"Select a node to inspect it. Double-click a function to step inside.")}function ke(e){let i=z.nodes[e].callee;i!==void 0&&(ve(),P.push({model:$[i],viewMode:"function",trace:null,cursor:0,selected:null,traceName:""}),ye())}function Re(e){ve(),P=P.slice(0,e+1),ye()}function Ae(){self.onmessage=async({data:e})=>{try{let I=function(n,a,x){let q="value-"+n.id+"-"+x,H=[],J=new Map;for(let C=0;C<Math.min(8,a.shape[1]);C++)for(let S=a.colind[C];S<a.colind[C+1];S++)a.row[S]<8&&J.set(a.row[S]+","+C,S);let D=Math.max(1,Math.min(8,a.shape[1])),v='<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="3" COLOR="#cccccc">',h=[n.boundary?n.display:n.kind==="call"?n.output_names[x]:"",e.showSizes?a.shape.join("-by-"):""].filter(Boolean).join(" : ");h&&(v+='<TR><TD COLSPAN="'+D+'" BGCOLOR="white"><FONT COLOR="'+(n.role==="input"?"#34658b":n.role==="output"?"#b00000":"#666666")+'">'+s(h)+"</FONT></TD></TR>");for(let C=0;C<Math.min(8,a.shape[0]);C++){v+="<TR>";for(let S=0;S<Math.min(8,a.shape[1]);S++){let F=J.get(C+","+S),Z=n.kind==="constant"?F===void 0?".":n.constants[F]:"";F!==void 0&&H.push({label:Z,index:F}),v+="<TD"+(F===void 0?"":' PORT="nz'+F+'"')+' BGCOLOR="white">',n.kind==="constant"?v+=s(Z):v+='<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0"><TR><TD FIXEDSIZE="TRUE" WIDTH="9" HEIGHT="9" BGCOLOR="'+(F===void 0?"white":"#111111")+'"></TD></TR></TABLE>',v+="</TD>"}a.shape[1]===0&&(v+="<TD>empty</TD>"),v+="</TR>"}return a.shape.some(C=>C>8)&&(v+='<TR><TD COLSPAN="'+D+'">...</TD></TR>'),!h&&!a.shape[0]&&(v+="<TR><TD>empty</TD></TR>"),v+="</TABLE>",T.push("v"+n.id+"_"+x+' [id="'+q+'", shape=plain, fontcolor="#666666", fontsize=10, label=<'+v+">];"),n.boundary||T.push("n"+n.id+(n.kind==="call"?":out"+x:"")+" -> v"+n.id+"_"+x+" [arrowsize=0.5];"),t.set(n.id+":"+x,"v"+n.id+"_"+x),d.push({id:q,node:n.id,port:x,cells:H}),d[d.length-1]};e.url&&importScripts(e.url);let i=n=>JSON.stringify(n),s=n=>String(n).replace(/[&<>"]/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[a]),r=e.model,d=[],t=new Map,c=new Map,o=new Set,u=n=>n.shape[0]*n.shape[1]!==1,p=(n,a)=>u(a)&&(n.kind==="call"||n.mapping||!n.inputs.length||!n.inputs.every(x=>JSON.stringify(x)===JSON.stringify(a))),b=n=>n.ordered&&!n.binary||n.kind==="call",k=e.viewMode==="function",M=k?"TB":r.direction;for(let n of r.nodes)(n.kind==="output"||k&&n.kind==="input")&&o.add(n.id);let T=["digraph G {","graph [rankdir="+M+', bgcolor="white", pad="0.4", nodesep="0.55", ranksep="0.65"];','node [shape=ellipse, style=filled, color="#b00000", fillcolor="#b00000", fontcolor="white", fontname="Helvetica", fontsize=14, margin="0.15,0.08", width=0.5, height=0.5];','edge [color="#34658b", penwidth=1.5, arrowsize=0.65];'];for(let n of r.nodes){let a=!k&&n.kind==="input"?{...n,display:n.symbol}:n;if(o.has(a.id))continue;let x=a.outputs[0]||a.inputs[0],q=e.showSizes&&x&&u(x)&&!(e.showContents&&a.outputs.some(v=>p(a,v)))?`
22
+ `+x.shape.join("-by-"):"",H=i(a.display+q),J="ellipse";if(b(a)){J="plain";let v=(C,S)=>"<TR>"+C.map((F,Z)=>'<TD PORT="'+S+Z+'"><FONT POINT-SIZE="10">'+s(F+(e.showSizes&&(S==="in"?a.inputs:a.outputs)[Z]&&u((S==="in"?a.inputs:a.outputs)[Z])?" "+(S==="in"?a.inputs:a.outputs)[Z].shape.join("-by-"):""))+"</FONT></TD>").join("")+"</TR>",h='<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="6" BGCOLOR="#b00000">';a.input_names.length&&(h+='<TR><TD><TABLE BORDER="0" CELLBORDER="1" COLOR="#d26666" CELLSPACING="0">'+v(a.input_names,"in")+"</TABLE></TD></TR>"),h+="<TR><TD>"+s(a.display)+"</TD></TR>",a.kind==="call"&&a.output_names.length&&(h+='<TR><TD><TABLE BORDER="0" CELLBORDER="1" COLOR="#d26666" CELLSPACING="0">'+v(a.output_names,"out")+"</TABLE></TD></TR>"),H="<"+h+"</TABLE>>"}let D=a.kind==="input"||a.kind==="symbol"?"#34658b":a.kind==="constant"?"#38754d":"#b00000";T.push("n"+a.id+' [id="instruction-'+a.id+'", shape='+J+", color="+i(D)+", fillcolor="+i(D)+", label="+H+"];"),a.outputs.forEach((v,h)=>{e.showContents&&p(a,v)&&I(a,v,h)})}let m={input:[],output:[]};for(let n of["input","output"])r[n+"s"].forEach((a,x)=>{let q=!k&&n==="output"&&r.type==="SXFunction"&&e.showContents&&u(a.sparsity);if(!k&&!q)return;let H={id:"boundary_"+n+"_"+x,kind:"boundary",boundary:!0,role:k?n:"",display:k?a.name:""},J=r.nodes.filter(h=>h.kind===n&&h.io_index===x).map(h=>({node:h.id,offset:h.io_offset,count:(n==="input"?h.outputs:h.inputs)[0].row.length})),D,v;if(e.showContents&&u(a.sparsity))D=I(H,a.sparsity,0),v="v"+H.id+"_0",D.cells=D.cells.flatMap(h=>{let C=J.find(S=>h.index>=S.offset&&h.index<S.offset+S.count);return C?[{...h,node:C.node,index:h.index-C.offset}]:[]});else{v="b"+n+"_"+x;let h=n==="input"?"#34658b":"#b00000",C=a.name+(e.showSizes&&u(a.sparsity)?`
23
+ `+a.sparsity.shape.join("-by-"):"");T.push(v+' [id="boundary-'+n+"-"+x+'", label='+i(C)+", color="+i(h)+", fillcolor="+i(h)+"];"),D={id:"boundary-"+n+"-"+x,node:null,port:0,cells:[],render:"io"},d.push(D)}Object.assign(D,{node:null,boundary:!0,boundaryKind:n,sp:a.sparsity,owners:J});for(let h of J){let C=D.cells.some(F=>F.node===h.node),S=v+(r.type==="SXFunction"&&C?":nz"+h.offset:"");n==="input"?t.set(h.node+":0",S):c.set(h.node,S)}k&&m[n].push(v)});if(k)for(let n of["input","output"]){let a=m[n];if(a.length){T.push("{ rank="+(n==="input"?"source":"sink")+"; "+a.join("; ")+"; }");for(let x=1;x<a.length;x++)T.push(a[x-1]+" -> "+a[x]+" [style=invis, weight=100];")}}for(let n of r.edges){if(o.has(n.to)&&!c.has(n.to))continue;let a=t.get(n.from+":"+n.output)||"n"+n.from+(r.nodes[n.from].kind==="call"?":out"+n.output:""),x=r.nodes[n.to],q=c.get(n.to)||"n"+n.to+(b(x)?":in"+n.input:"");x.binary&&(q+=n.input===0?":w":":e"),T.push(a+" -> "+q+";")}T.push("}");let O=await Viz.instance(),_=O.render(T.join(`
24
+ `),{engine:"dot",format:"svg"});if(_.status!=="success")throw Error(_.errors.map(n=>n.message).join("; "));self.postMessage({svg:_.output,details:d,hidden:Array.from(o)})}catch(i){self.postMessage({error:i.message||String(i)})}}}let Oe="("+Ae.toString()+")();",K=null,ae=null;function de(){K&&K.terminate(),K=null,ae&&URL.revokeObjectURL(ae),ae=null}function se(e){L(new Error(e)),de(),l("loading-text").textContent=e,l("cancel-layout").hidden=!0,W(e,"error")}function ze(e,i,s){let r=new DOMParser().parseFromString(e,"image/svg+xml");if(r.querySelector("parsererror")||r.documentElement.localName!=="svg")throw Error("Viz.js returned invalid SVG");w=document.importNode(r.documentElement,!0),w.setAttribute("role","img"),w.setAttribute("aria-label","Function instruction graph"),w.removeAttribute("width"),w.removeAttribute("height"),l("canvas").prepend(w),me=w.getAttribute("viewBox");for(let t of i){let c=w.getElementById(t.id);c.classList.remove("node"),c.classList.add(t.render==="io"?"io-node":"value-node"),c.onclick=()=>{let p=t.node??t.cells[0]?.node??t.owners?.[0]?.node;p!==void 0&&oe(p)};let o=Array.from(c.querySelectorAll("text")),u=new Map;if(t.boundary){for(let k of t.owners)u.set(k.node,[]);let p=document.createElementNS("http://www.w3.org/2000/svg","text"),b=c.getBBox();p.classList.add("trace-value"),p.setAttribute("x",b.x+b.width/2),p.setAttribute("y",b.y+b.height+14),p.setAttribute("text-anchor","middle"),c.append(p),t.traceLabel=p}for(let p of t.cells){let b=o.findIndex(M=>M.textContent===p.label),k=p.node??t.node;u.has(k)||u.set(k,[]),b>=0&&u.get(k).push({...p,element:o.splice(b,1)[0]})}t.node!==null&&!u.has(t.node)&&u.set(t.node,[]);for(let[p,b]of u)X.has(p)||X.set(p,[]),X.get(p).push({element:c,port:t.port,cells:b,boundary:t.boundary?t:null})}for(let t of z.nodes){let c=w.getElementById("instruction-"+t.id);if(!c){if(s.includes(t.id)){ie(t.id);continue}throw Error("Missing graph node "+t.id)}Q.set(t.id,c),c.onclick=()=>oe(t.id),t.callee!==void 0&&(c.onclick=()=>{clearTimeout(ne),ne=setTimeout(()=>oe(t.id),400)},c.ondblclick=()=>{clearTimeout(ne),ke(t.id)},c.querySelector("title").textContent="Double-click to step into "+t.display),ie(t.id)}A!==null&&oe(A),w.addEventListener("wheel",t=>{t.preventDefault();let c=w.viewBox.baseVal,o=Math.exp(Math.max(-1,Math.min(1,t.deltaY*.001))),u=new DOMPoint(t.clientX,t.clientY).matrixTransform(w.getScreenCTM().inverse());w.setAttribute("viewBox",[u.x+(c.x-u.x)*o,u.y+(c.y-u.y)*o,c.width*o,c.height*o].join(" "))},{passive:!1});let d=null;w.onpointerdown=t=>{t.button!==0||t.target.closest(".node,.io-node,.value-node")||(d={x:t.clientX,y:t.clientY,view:w.getAttribute("viewBox").split(/\s+/).map(Number)},w.setPointerCapture(t.pointerId))},w.onpointermove=t=>{if(!d)return;let c=w.getScreenCTM(),[o,u,p,b]=d.view;w.setAttribute("viewBox",[o-(t.clientX-d.x)/c.a,u-(t.clientY-d.y)/c.d,p,b].join(" "))},w.onpointerup=w.onpointercancel=()=>{d=null},g(),l("loading").hidden=!0,f||W("Select a node to inspect it. Scroll to zoom; drag to pan.")}l("fit").onclick=()=>{w&&w.setAttribute("viewBox",me)},l("cancel-layout").onclick=()=>se("Layout cancelled. Reopen the file to try again.");function ee(){clearTimeout(ne),de(),w&&w.remove(),w=null,Q.clear(),X.clear(),l("loading").hidden=!1,l("loading-text").textContent="Laying out the graph\u2026",l("cancel-layout").hidden=!1;try{ae=URL.createObjectURL(new Blob([R.source||"",`
25
+ `,Oe],{type:"text/javascript"})),K=new Worker(ae),K.onmessage=({data:e})=>{if(e.error){se("Layout failed: "+e.error);return}de();try{ze(e.svg,e.details,e.hidden)}catch(i){se(i.message)}},K.onerror=e=>se("Could not load Viz.js. Check connectivity, or export with the viz_js option for offline use."),K.postMessage({url:R.url,model:z,viewMode:G,showContents:le,showSizes:ue})}catch(e){se(e.message)}}return l("view-mode").onchange=()=>{G=l("view-mode").value,U(),ee()},l("detail-toggle").onchange=()=>{le=l("detail-toggle").checked,U(),ee()},l("size-toggle").onchange=()=>{ue=l("size-toggle").checked,U(),ee()},fe(),ee(),{ready:V,loadTrace:we,destroy(){B(),clearTimeout(ne),++re,de(),L(new DOMException("Viewer replaced or destroyed","AbortError"))},setView(e){if(!["function","expression"].includes(e))throw Error("Unknown graph view: "+e);G=e,fe(),U(),ee()}}}return Pe($e);})();
@@ -0,0 +1,25 @@
1
+ export interface Sparsity {shape:[number,number];colind:number[];row:number[];}
2
+ export interface GraphPort {name:string;sparsity:Sparsity;}
3
+ export interface GraphNode {
4
+ id:number;op:number;kind:string;display:string;label:string;expression:string;formula:string;
5
+ binary:boolean;ordered:boolean;inputs:Sparsity[];outputs:Sparsity[];
6
+ input_names:string[];output_names:string[];constants:string[];
7
+ callee?:number;callee_type?:string;io_index?:number;io_offset?:number;symbol?:string;mapping?:number[];
8
+ }
9
+ export interface FunctionGraph {
10
+ version:1;name:string;type:string;direction:'TB'|'BT'|'LR'|'RL';
11
+ inputs:GraphPort[];outputs:GraphPort[];nodes:GraphNode[];
12
+ edges:{from:number;output:number;to:number;input:number}[];
13
+ }
14
+ export interface GraphBundle extends FunctionGraph {
15
+ format:'casadi_viz';view:'function'|'expression';functions:FunctionGraph[];
16
+ }
17
+ export interface Viewer {
18
+ setGraph(bundle:GraphBundle|string):Promise<void>;
19
+ loadTrace(trace:Blob|string):Promise<void>;
20
+ setView(view:'function'|'expression'):void;
21
+ destroy():void;
22
+ }
23
+ export function createGraphViewer(host:HTMLElement,options?:{
24
+ runtime?:{url:string;source?:never}|{source:string;url?:never};
25
+ }):Viewer;
package/dist/index.js ADDED
@@ -0,0 +1,24 @@
1
+ var ke=`
2
+ :host{font:14px Arial,Helvetica,sans-serif;color:#222;background:white;--accent:#b00000;--blue:#34658b;--line:#e8e8e8}
3
+ *{box-sizing:border-box}[hidden]{display:none!important}.viewer{margin:0;height:100%;display:flex;flex-direction:column}
4
+ header{padding:16px 24px;border-bottom:1px solid var(--line);display:flex;gap:20px;align-items:center;justify-content:space-between;flex-wrap:wrap}
5
+ .brand{font-size:19px;font-weight:700;letter-spacing:-.04em}.brand span{color:var(--accent)}h1{font-size:18px;margin:0;font-weight:400}#meta{color:#888;font-size:12px;margin-top:5px}.identity{display:flex;gap:24px;align-items:center;min-width:0}#breadcrumbs{display:flex;gap:7px;align-items:center;flex-wrap:wrap}#breadcrumbs button{border:0;padding:2px 0;font-size:17px;color:#34658b;background:none}#breadcrumbs button:disabled{opacity:1;color:#222;cursor:default}#breadcrumbs span{color:#aaa}.toggle{display:flex;align-items:center;gap:7px;font-size:12px;cursor:pointer;white-space:nowrap}.toggle input{appearance:none;position:relative;width:28px;height:16px;border-radius:12px;background:#ccc;margin:0;cursor:pointer;flex-shrink:0}.toggle input:checked{background:var(--accent)}.toggle input::after{content:"";position:absolute;top:2px;left:2px;width:12px;height:12px;border-radius:50%;background:white;transition:transform .12s}.toggle input:checked::after{transform:translateX(12px)}.toggle input:focus-visible{outline:2px solid #34658b;outline-offset:2px}
6
+ button,.upload{font:inherit;background:white;border:1px solid #ddd;border-radius:4px;padding:7px 11px;cursor:pointer;white-space:nowrap;color:inherit}button:hover,.upload:hover{background:#f6f6f6}button:disabled{opacity:.35;cursor:default}button[aria-pressed=true]{border-color:var(--accent);color:var(--accent);background:#fff6f6}.upload{display:inline-block}.upload:focus-within{outline:2px solid var(--blue)}.upload input{position:absolute;width:1px;height:1px;opacity:0}
7
+ #toolbar{display:flex;gap:8px;align-items:center;padding:10px 24px;border-bottom:1px solid var(--line);flex-wrap:wrap;background:#fafafa}#timeline{flex:1;min-width:100px;accent-color:var(--accent)}#step-label{min-width:100px;font-variant-numeric:tabular-nums;color:#777;font-size:12px}select{font:inherit;border:1px solid #ddd;border-radius:4px;padding:6px;background:white}
8
+ main{display:flex;flex:1;min-height:0}#canvas{flex:1;position:relative;overflow:hidden;background:white}#canvas svg{width:100%;height:100%;display:block;touch-action:none}#canvas .node,#canvas .io-node,#canvas .value-node{cursor:pointer}#canvas .node text,#canvas .io-node text,#canvas .value-node text{pointer-events:none}#canvas .io-node.active>ellipse,#canvas .node.active>ellipse,#canvas .node.active>polygon,#canvas .node.active>path{stroke:#222;stroke-width:2.5}#canvas .io-node.executed>ellipse,#canvas .node.executed>ellipse,#canvas .node.executed>polygon,#canvas .node.executed>path{stroke:var(--blue);stroke-width:2.5}#canvas .node.failed>ellipse,#canvas .node.failed>polygon,#canvas .node.failed>path{stroke:#e18c24;stroke-width:3}#canvas .value-node.active>polygon{stroke:var(--blue);stroke-width:1.5}#canvas .trace-value{font:11px ui-monospace,monospace;fill:var(--blue);paint-order:stroke;stroke:white;stroke-width:4px;stroke-linejoin:round}#canvas .edge path{stroke:var(--blue)}#canvas .edge polygon{fill:var(--blue);stroke:var(--blue)}
9
+ #loading{position:absolute;inset:0;display:grid;place-content:center;text-align:center;color:#777;gap:12px;background:#fffffff2}#loading p{max-width:420px;margin:0;padding:0 20px}#loading button{justify-self:center}
10
+ aside{width:340px;max-width:42vw;background:white;border-left:1px solid var(--line);padding:20px;overflow:auto}.selection-header{display:flex;align-items:center;justify-content:space-between;gap:12px}aside h2{font-size:18px;font-weight:400;margin:0}aside h3{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#888;margin:22px 0 8px}#close-inspector{border:0;font-size:20px;padding:0 5px}pre{font:12px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#f7f7f7;padding:10px;margin:14px 0 0}.hint{font-size:12px;line-height:1.6;color:#888}.port{border-top:1px solid #eee;padding:10px 0}.port-title{font:12px ui-monospace,monospace;color:#666;margin-bottom:8px}.port-value{font:12px/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.matrix{border-collapse:collapse;margin:8px 0;font:11px ui-monospace,monospace}.matrix td{border:1px solid #ddd;padding:5px;text-align:center;white-space:nowrap}.matrix td.nz{background:#eee}.matrix td.zero{color:#aaa}.matrix td.spy{width:16px;height:16px;padding:3px;background:white;border:0}.matrix td.nz.spy::after{content:"";display:block;background:#111;width:9px;height:9px}.matrix:has(.spy){border:1px solid #ddd}.matrix-wrap{overflow:auto}.state{font-size:12px;color:var(--blue);margin:14px 0}details{font-size:12px;color:#666;margin-top:10px}summary{cursor:pointer}
11
+ footer{padding:8px 24px;border-top:1px solid var(--line);display:flex;justify-content:space-between;gap:16px;font-size:11px;color:#888}#status.error{color:#b00000}#status.warning{color:#936015}#trace-name{max-width:50%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.right-tools{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.legend{display:flex;gap:14px;align-items:center}.legend span::before{content:"";display:inline-block;width:7px;height:7px;border-radius:50%;margin-right:5px;background:var(--accent)}.legend .symbol::before{background:#34658b}.legend .constant::before{background:#38754d}
12
+ @media(max-width:700px){header{padding:12px}.identity{gap:12px}.brand{font-size:16px}#toolbar{padding:10px}aside{width:240px;padding:12px}footer{padding:8px}}
13
+ `;var Ee=`<div class="viewer">
14
+ <header><div class="identity"><div class="brand">Cas<span>AD</span>i</div><div><nav id="breadcrumbs" aria-label="Function navigation"></nav><div id="meta"></div></div></div><div class="right-tools"><select id="view-mode" aria-label="Graph view"><option value="expression">Expression view</option><option value="function">Function view</option></select><label class="toggle"><input id="detail-toggle" type="checkbox" role="switch" checked>Show matrix contents</label><label class="toggle"><input id="size-toggle" type="checkbox" role="switch" checked>Show matrix sizes</label><button id="fit">Fit graph</button><button id="trace-toggle" aria-pressed="false" aria-controls="toolbar">Trace</button></div></header>
15
+ <div id="toolbar" hidden><label class="upload">Load trace<input id="trace-file" type="file" accept=".jsonl,.json,.txt" aria-label="Load evaluation trace"></label><button id="start" title="Rewind" disabled>&#8612;</button><button id="back" title="Previous instruction" disabled>&#8592;</button><button id="play" disabled>Play</button><button id="next" title="Next instruction" disabled>&#8594;</button><button id="end" title="Last instruction" disabled>&#8614;</button><input id="timeline" type="range" min="0" max="0" value="0" disabled aria-label="Evaluation position"><span id="step-label">No trace loaded</span><select id="speed" aria-label="Playback speed"><option value="800">Slow</option><option value="350" selected>Normal</option><option value="80">Fast</option></select></div>
16
+ <main><div id="canvas"><div id="loading"><p id="loading-text">Laying out the graph&#8230;</p><button id="cancel-layout">Cancel layout</button></div></div><aside id="details" hidden><div class="selection-header"><h2 id="selection-title"></h2><button id="close-inspector" aria-label="Close inspector">&#215;</button></div><div id="inspector"></div></aside></main>
17
+ <footer><span id="status" role="status">Preparing graph&#8230;</span><div class="right-tools"><span id="trace-name" hidden></span><div class="legend" aria-label="Node colors"><span class="symbol">Symbols</span><span class="constant">Constants</span><span>Operations</span></div></div></footer>
18
+ </div>`;function Le(A){if(!A||A.format!=="casadi_viz"||A.version!==1)throw new Error("Expected a casadi_viz bundle (version 1)");if(!Array.isArray(A.functions))throw Error("Expected a functions array");let G=[A,...A.functions];for(let O of G){for(let x of["nodes","edges","inputs","outputs"])if(!Array.isArray(O[x]))throw Error("Missing graph array: "+x);O.nodes.forEach((x,R)=>{if(x.id!==R)throw Error("Instruction IDs must be consecutive");if(x.callee!==void 0&&(!Number.isInteger(x.callee)||!G[x.callee]))throw Error("Invalid callee reference");for(let V of["inputs","outputs","input_names","output_names","constants"])if(!Array.isArray(x[V]))throw Error("Missing instruction array: "+V)});for(let x of O.edges)if(!Number.isInteger(x.from)||!Number.isInteger(x.to)||!O.nodes[x.from]||!O.nodes[x.to]||!Number.isInteger(x.input)||!Number.isInteger(x.output)||x.input<0||x.input>=O.nodes[x.to].inputs.length||x.output<0||x.output>=O.nodes[x.from].outputs.length)throw Error("Invalid dependency edge")}return A}function Ge(A,G={}){if(!A||typeof A.attachShadow!="function")throw new TypeError("Expected a host element");let O=A.shadowRoot||A.attachShadow({mode:"open"}),x=G.runtime||{url:new URL("./viz-global.js",import.meta.url).href},R=null,V=!1;return{async setGraph($){if(V)throw Error("Viewer has been destroyed");let N=Le(typeof $=="string"?JSON.parse($):$);return R?.destroy(),O.innerHTML="<style>"+ke+"</style>"+Ee,R=Be(O,N,x),R.ready},async loadTrace($){if(!R||V)throw Error("Load a graph before loading a trace");return R.loadTrace($)},setView($){if(!R||V)throw Error("Load a graph before selecting a view");R.setView($)},destroy(){R?.destroy(),R=null,V=!0,O.replaceChildren()}}}function Be(A,G,O){let x,R,V=new Promise((e,i)=>{x=e,R=i}),$=[G,...G.functions||[]],N=G,l=e=>A.querySelector("#"+e),W=(e,i="")=>{l("status").textContent=e,l("status").className=i},w=null,he=null,f=null,y=0,C=null,te=null,I=!1,le=!0,ue=!0,F=G.view||"function",j=[{model:N,viewMode:F,trace:null,cursor:0,selected:null,traceName:""}],Q=new Map,X=new Map,ne=null,me=e=>typeof e=="number"?Object.is(e,-0)?"-0":Number(e.toPrecision(7)).toString():e,ge=e=>e.map(i=>i===null?"unused":"["+i.slice(0,3).map(me).join(", ")+(i.length>3?", \u2026":"")+"]").join(" ; ");function D(){clearInterval(te),te=null,l("play").textContent="Play"}function pe(){let e=f?f.count:0;l("start").disabled=l("back").disabled=!f||y===0,l("next").disabled=l("end").disabled=!f||y===e,l("play").disabled=!f||e===0,l("timeline").disabled=!f,l("timeline").max=e,l("timeline").value=y,l("step-label").textContent=f?`${y.toLocaleString()} / ${e.toLocaleString()}`:"No trace loaded"}function be(e,i,s,r,d=!1){let t=document.createElement("section"),c=document.createElement("h3");if(c.textContent=e,t.append(c),!i.length){let o=document.createElement("div");o.className="hint",o.textContent="None",t.append(o)}return i.forEach((o,u)=>{let p=document.createElement("div");p.className="port";let g=document.createElement("div");g.className="port-title",g.textContent=`${r[u]}${ue?" \xB7 "+o.shape.join("-by-"):""} \xB7 ${o.row.length} nonzeros`;let k=document.createElement("div");if(k.className="port-value",k.textContent=s===void 0?I?"Not evaluated":"":s[u]===null?"Unused / absent buffer":"["+s[u].map(B=>Object.is(B,-0)?"-0":String(B)).join(", ")+"]",p.append(g,k),le&&o.shape[0]*o.shape[1]!==1&&p.append(Te(o,s?.[u],d)),o.row.length!==o.shape[0]*o.shape[1]){let B=document.createElement("details"),E=document.createElement("summary"),M=document.createElement("pre");E.textContent="Sparsity",M.textContent="colind: "+JSON.stringify(o.colind)+`
19
+ row: `+JSON.stringify(o.row),B.append(E,M),p.append(B)}t.append(p)}),t}function Te(e,i,s){let r=document.createElement("div");r.className="matrix-wrap";let d=document.createElement("table");d.className="matrix";let t=new Map;for(let c=0;c<Math.min(8,e.shape[1]);c++)for(let o=e.colind[c];o<e.colind[c+1];o++)e.row[o]<8&&t.set(e.row[o]+","+c,o);for(let c=0;c<Math.min(8,e.shape[0]);c++){let o=d.insertRow();for(let u=0;u<Math.min(8,e.shape[1]);u++){let p=o.insertCell(),g=t.get(c+","+u);p.className=g===void 0?"zero":"nz",s||p.classList.add("spy"),p.textContent=s?g===void 0?".":String(i[g]):"",p.title=g===void 0?"Structural zero":`Row ${c}, column ${u}, nonzero ${g}`}}if(r.append(d),e.shape.some(c=>c>8)){let c=document.createElement("div");c.className="hint",c.textContent="Showing the first 8 rows / columns. Full sparsity below.",r.append(c)}return r}function U(){if(C===null)return;let e=N.nodes[C],i=I&&f&&C<y;l("selection-title").textContent=F==="expression"&&e.kind==="input"?e.symbol:F==="function"&&["input","output"].includes(e.kind)?N[e.kind+"s"][e.io_index].name:e.display;let s=l("inspector");if(s.replaceChildren(),I){let o=document.createElement("div");o.className="state",o.textContent=i?f.after[C]===void 0?"Interrupted":"Evaluated":"Not evaluated",s.append(o)}let r=document.createElement("pre");if(r.textContent=e.formula,e.callee!==void 0){let o=document.createElement("button");o.id="enter-function",o.textContent="Step into "+e.display,o.onclick=()=>ye(e.id),s.append(o)}else if(e.kind==="call"){let o=document.createElement("p");o.className="hint",o.textContent="No internal graph was included for this "+e.callee_type+".",s.append(o)}if(s.append(r,be("Inputs",e.inputs,i?f.before[C]:void 0,e.input_names),be("Outputs",e.outputs,i?f.after[C]:e.kind==="constant"?[e.constants]:void 0,e.output_names,e.kind==="constant")),e.mapping){let o=document.createElement("h3"),u=document.createElement("pre");o.textContent="Nonzero mapping",u.textContent=e.mapping.map((p,g)=>`${g}: ${p}`).join(", "),s.append(o,u)}let d=document.createElement("details"),t=document.createElement("summary"),c=document.createElement("pre");t.textContent="Evaluator expression",c.textContent=e.expression,d.append(t,c),s.append(d)}function oe(e){if(C!==null){Q.get(C)?.classList.remove("active");for(let i of X.get(C)||[])i.element.classList.remove("active")}C=e,Q.get(e)?.classList.add("active");for(let i of X.get(e)||[])i.element.classList.add("active");l("details").hidden=!1,U()}l("close-inspector").onclick=()=>{Q.get(C)?.classList.remove("active");for(let e of X.get(C)||[])e.element.classList.remove("active");C=null,l("details").hidden=!0};function ie(e){let i=Q.get(e),s=I&&f&&e<y,r=s&&f.after[e]!==void 0;i?.classList.toggle("executed",!!r),i?.classList.toggle("failed",!!s&&!r);let d=i?.querySelector(".trace-value");if(i&&!d){d=document.createElementNS("http://www.w3.org/2000/svg","text"),d.classList.add("trace-value");let o=i.getBBox();d.setAttribute("x",o.x+o.width/2),d.setAttribute("y",o.y+o.height+14),d.setAttribute("text-anchor","middle"),i.append(d)}let t=s?N.nodes[e].kind==="output"?f.before[e]:f.after[e]:void 0,c=t===void 0?"":ge(t);d&&(d.textContent=c.length>36?c.slice(0,35)+"\u2026":c);for(let o of X.get(e)||[]){if(o.boundary){Ce(o.boundary);continue}let u=t?.[o.port];for(let p of o.cells)p.element.textContent=le&&u?me(u[p.index]):p.label}}function Ce(e){let i=Array(Math.min(4,e.sp.row.length)).fill("?"),s=!1;for(let r of e.owners){if(!I||!f||r.node>=y)continue;let d=(e.boundaryKind==="input"?f.after[r.node]:f.before[r.node])?.[0];if(d){s=!0;for(let t=0;t<d.length&&r.offset+t<i.length;t++)i[r.offset+t]=d[t]}}e.traceLabel.textContent=s?ge([i]):"",e.traceLabel.parentNode.classList.toggle("executed",!!s&&e.owners.every(r=>r.node<y&&f.after[r.node]!==void 0))}l("trace-toggle").onclick=()=>{I=!I,D(),l("trace-toggle").setAttribute("aria-pressed",String(I)),l("toolbar").hidden=!I,l("trace-name").hidden=!I;for(let e=0;e<y;e++)ie(e);U(),W(I?f?"Trace loaded. Step through the evaluation.":"Load a trace file to replay an evaluation. Files stay in your browser.":"Select a node to inspect it. Scroll to zoom; drag to pan.")};function Y(e,i=!0){let s=y;y=Math.max(0,Math.min(f?f.count:0,e));for(let r=Math.min(s,y);r<Math.max(s,y);r++)ie(r);if(i&&y>0){let r=y-1;F==="expression"&&N.nodes[r].kind==="output"&&(r=N.edges.find(d=>d.to===r)?.from??r),oe(r)}else U();pe(),f&&y===f.count&&D()}l("start").onclick=()=>{D(),Y(0)},l("back").onclick=()=>{D(),Y(y-1)},l("next").onclick=()=>{D(),Y(y+1)},l("end").onclick=()=>{D(),Y(f.count)},l("timeline").oninput=()=>{D(),Y(Number(l("timeline").value))},l("play").onclick=()=>{if(te){D();return}y===f.count&&Y(0),l("play").textContent="Pause",te=setInterval(()=>Y(y+1),Number(l("speed").value))},l("speed").onchange=()=>{te&&(D(),l("play").click())};function ce(e,i,s){if(!Array.isArray(e)||e.length!==i.length)throw Error(s+": wrong number of values");e.forEach((r,d)=>{if(r!==null){if(!Array.isArray(r)||r.length!==i[d].row.length)throw Error(s+": nonzero count does not match the graph");for(let t of r)if(!(typeof t=="number"&&Number.isFinite(t))&&!["nan","inf","-inf"].includes(t))throw Error(s+": invalid numerical value")}})}async function Se(e,i=N){let s={before:[],after:[],count:0,ended:!1,status:null},r=!1,d=!1,t=!1,c=!1,o=!1,u=0,p=0;function g(M){if(!M.trim())return;p++;let m=JSON.parse(M);if(!m||typeof m!="object"||Array.isArray(m))throw Error("Expected a trace record");if(c)throw Error("Unexpected data after trace end");if(!r){if(m.event!=="header"||m.format!=="casadi_trace"||m.version!==1)throw Error("Expected a dump_trace JSONL file (version 1)");if(m.function!==i.name||m.type!==i.type)throw Error("This trace belongs to a different function");r=!0;return}if(!d){if(m.event!=="inputs")throw Error("Missing function inputs");ce(m.values,i.inputs.map(P=>P.sparsity),"Function inputs"),d=!0;return}if(m.event==="error"){c=!0,s.status="error";return}if(m.event==="outputs"){if(o||u!==i.nodes.length||t)throw Error("Unexpected function outputs");ce(m.values,i.outputs.map(P=>P.sparsity),"Function outputs"),t=!0;return}if(m.event==="end"){if(!Number.isInteger(m.status))throw Error("Invalid evaluation status");if(m.status===0&&(!t||o||u!==i.nodes.length))throw Error("Successful trace is missing instructions");s.ended=!0,s.status=m.status,c=!0;return}let S=m.instruction;if(t||!Number.isInteger(S)||S!==u||S>=i.nodes.length||m.op!==i.nodes[S].op)throw Error("Instruction sequence does not match this graph");if(m.phase==="inputs"&&!o)ce(m.values,i.nodes[S].inputs,"Instruction "+S+" inputs"),s.before[S]=m.values,s.count=S+1,o=!0;else if(m.phase==="outputs"&&o)ce(m.values,i.nodes[S].outputs,"Instruction "+S+" outputs"),s.after[S]=m.values,o=!1,u++;else throw Error("Unexpected instruction phase")}let k=e.stream().getReader(),B=new TextDecoder,E="";try{for(;;){let{done:M,value:m}=await k.read();if(M)break;E+=B.decode(m,{stream:!0});let S=0,P;for(;(P=E.indexOf(`
20
+ `,S))!==-1;)g(E.slice(S,P)),S=P+1;E=E.slice(S)}if(E+=B.decode(),E.trim()&&g(E),!r||!d)throw Error("Incomplete trace header")}catch(M){throw await k.cancel(),Error(`Line ${p}: ${M.message}`)}finally{k.releaseLock()}return s}let re=0;async function xe(e){if(typeof e=="string"&&(e=new File([e],"evaluation.trace.jsonl")),!e)return;let i=++re;D(),W("Reading trace\u2026");try{let s=await Se(e);if(i!==re)return;let r=y;f=s,y=0;for(let d=0;d<r;d++)ie(d);pe(),U(),l("trace-name").textContent=e.name,W(s.ended&&s.status===0?"Trace loaded. Step through the evaluation.":"Partial or failed evaluation. Recorded instructions are available.",s.ended&&s.status===0?"":"warning")}catch(s){throw i===re&&W(s.message,"error"),s}l("trace-file").value=""}l("trace-file").onchange=()=>xe(l("trace-file").files[0]).catch(()=>{});function fe(){l("view-mode").value=F;let e=l("breadcrumbs");e.replaceChildren(),j.forEach((i,s)=>{if(s){let d=document.createElement("span");d.textContent="/",e.append(d)}let r=document.createElement("button");r.textContent=i.model.name,r.disabled=s===j.length-1,r.disabled&&(r.id="name",r.setAttribute("aria-current","page")),r.onclick=()=>Ne(s),e.append(r)}),l("meta").textContent=`${N.type} \xB7 ${N.nodes.length.toLocaleString()} instructions \xB7 ${N.edges.length.toLocaleString()} connections`}function we(){Object.assign(j[j.length-1],{viewMode:F,trace:f,cursor:y,selected:C,traceName:l("trace-name").textContent})}function ve(){D(),++re,{model:N,viewMode:F,trace:f,cursor:y,selected:C}=j[j.length-1],l("trace-name").textContent=j[j.length-1].traceName,l("details").hidden=C===null,fe(),pe(),U(),ee(),W(f?"Trace restored. Step through the evaluation.":"Select a node to inspect it. Double-click a function to step inside.")}function ye(e){let i=N.nodes[e].callee;i!==void 0&&(we(),j.push({model:$[i],viewMode:"function",trace:null,cursor:0,selected:null,traceName:""}),ve())}function Ne(e){we(),j=j.slice(0,e+1),ve()}function Re(){self.onmessage=async({data:e})=>{try{let M=function(n,a,b){let q="value-"+n.id+"-"+b,H=[],J=new Map;for(let L=0;L<Math.min(8,a.shape[1]);L++)for(let T=a.colind[L];T<a.colind[L+1];T++)a.row[T]<8&&J.set(a.row[T]+","+L,T);let z=Math.max(1,Math.min(8,a.shape[1])),v='<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="3" COLOR="#cccccc">',h=[n.boundary?n.display:n.kind==="call"?n.output_names[b]:"",e.showSizes?a.shape.join("-by-"):""].filter(Boolean).join(" : ");h&&(v+='<TR><TD COLSPAN="'+z+'" BGCOLOR="white"><FONT COLOR="'+(n.role==="input"?"#34658b":n.role==="output"?"#b00000":"#666666")+'">'+s(h)+"</FONT></TD></TR>");for(let L=0;L<Math.min(8,a.shape[0]);L++){v+="<TR>";for(let T=0;T<Math.min(8,a.shape[1]);T++){let _=J.get(L+","+T),Z=n.kind==="constant"?_===void 0?".":n.constants[_]:"";_!==void 0&&H.push({label:Z,index:_}),v+="<TD"+(_===void 0?"":' PORT="nz'+_+'"')+' BGCOLOR="white">',n.kind==="constant"?v+=s(Z):v+='<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="0"><TR><TD FIXEDSIZE="TRUE" WIDTH="9" HEIGHT="9" BGCOLOR="'+(_===void 0?"white":"#111111")+'"></TD></TR></TABLE>',v+="</TD>"}a.shape[1]===0&&(v+="<TD>empty</TD>"),v+="</TR>"}return a.shape.some(L=>L>8)&&(v+='<TR><TD COLSPAN="'+z+'">...</TD></TR>'),!h&&!a.shape[0]&&(v+="<TR><TD>empty</TD></TR>"),v+="</TABLE>",E.push("v"+n.id+"_"+b+' [id="'+q+'", shape=plain, fontcolor="#666666", fontsize=10, label=<'+v+">];"),n.boundary||E.push("n"+n.id+(n.kind==="call"?":out"+b:"")+" -> v"+n.id+"_"+b+" [arrowsize=0.5];"),t.set(n.id+":"+b,"v"+n.id+"_"+b),d.push({id:q,node:n.id,port:b,cells:H}),d[d.length-1]};e.url&&importScripts(e.url);let i=n=>JSON.stringify(n),s=n=>String(n).replace(/[&<>"]/g,a=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[a]),r=e.model,d=[],t=new Map,c=new Map,o=new Set,u=n=>n.shape[0]*n.shape[1]!==1,p=(n,a)=>u(a)&&(n.kind==="call"||n.mapping||!n.inputs.length||!n.inputs.every(b=>JSON.stringify(b)===JSON.stringify(a))),g=n=>n.ordered&&!n.binary||n.kind==="call",k=e.viewMode==="function",B=k?"TB":r.direction;for(let n of r.nodes)(n.kind==="output"||k&&n.kind==="input")&&o.add(n.id);let E=["digraph G {","graph [rankdir="+B+', bgcolor="white", pad="0.4", nodesep="0.55", ranksep="0.65"];','node [shape=ellipse, style=filled, color="#b00000", fillcolor="#b00000", fontcolor="white", fontname="Helvetica", fontsize=14, margin="0.15,0.08", width=0.5, height=0.5];','edge [color="#34658b", penwidth=1.5, arrowsize=0.65];'];for(let n of r.nodes){let a=!k&&n.kind==="input"?{...n,display:n.symbol}:n;if(o.has(a.id))continue;let b=a.outputs[0]||a.inputs[0],q=e.showSizes&&b&&u(b)&&!(e.showContents&&a.outputs.some(v=>p(a,v)))?`
21
+ `+b.shape.join("-by-"):"",H=i(a.display+q),J="ellipse";if(g(a)){J="plain";let v=(L,T)=>"<TR>"+L.map((_,Z)=>'<TD PORT="'+T+Z+'"><FONT POINT-SIZE="10">'+s(_+(e.showSizes&&(T==="in"?a.inputs:a.outputs)[Z]&&u((T==="in"?a.inputs:a.outputs)[Z])?" "+(T==="in"?a.inputs:a.outputs)[Z].shape.join("-by-"):""))+"</FONT></TD>").join("")+"</TR>",h='<TABLE BORDER="0" CELLBORDER="0" CELLSPACING="0" CELLPADDING="6" BGCOLOR="#b00000">';a.input_names.length&&(h+='<TR><TD><TABLE BORDER="0" CELLBORDER="1" COLOR="#d26666" CELLSPACING="0">'+v(a.input_names,"in")+"</TABLE></TD></TR>"),h+="<TR><TD>"+s(a.display)+"</TD></TR>",a.kind==="call"&&a.output_names.length&&(h+='<TR><TD><TABLE BORDER="0" CELLBORDER="1" COLOR="#d26666" CELLSPACING="0">'+v(a.output_names,"out")+"</TABLE></TD></TR>"),H="<"+h+"</TABLE>>"}let z=a.kind==="input"||a.kind==="symbol"?"#34658b":a.kind==="constant"?"#38754d":"#b00000";E.push("n"+a.id+' [id="instruction-'+a.id+'", shape='+J+", color="+i(z)+", fillcolor="+i(z)+", label="+H+"];"),a.outputs.forEach((v,h)=>{e.showContents&&p(a,v)&&M(a,v,h)})}let m={input:[],output:[]};for(let n of["input","output"])r[n+"s"].forEach((a,b)=>{let q=!k&&n==="output"&&r.type==="SXFunction"&&e.showContents&&u(a.sparsity);if(!k&&!q)return;let H={id:"boundary_"+n+"_"+b,kind:"boundary",boundary:!0,role:k?n:"",display:k?a.name:""},J=r.nodes.filter(h=>h.kind===n&&h.io_index===b).map(h=>({node:h.id,offset:h.io_offset,count:(n==="input"?h.outputs:h.inputs)[0].row.length})),z,v;if(e.showContents&&u(a.sparsity))z=M(H,a.sparsity,0),v="v"+H.id+"_0",z.cells=z.cells.flatMap(h=>{let L=J.find(T=>h.index>=T.offset&&h.index<T.offset+T.count);return L?[{...h,node:L.node,index:h.index-L.offset}]:[]});else{v="b"+n+"_"+b;let h=n==="input"?"#34658b":"#b00000",L=a.name+(e.showSizes&&u(a.sparsity)?`
22
+ `+a.sparsity.shape.join("-by-"):"");E.push(v+' [id="boundary-'+n+"-"+b+'", label='+i(L)+", color="+i(h)+", fillcolor="+i(h)+"];"),z={id:"boundary-"+n+"-"+b,node:null,port:0,cells:[],render:"io"},d.push(z)}Object.assign(z,{node:null,boundary:!0,boundaryKind:n,sp:a.sparsity,owners:J});for(let h of J){let L=z.cells.some(_=>_.node===h.node),T=v+(r.type==="SXFunction"&&L?":nz"+h.offset:"");n==="input"?t.set(h.node+":0",T):c.set(h.node,T)}k&&m[n].push(v)});if(k)for(let n of["input","output"]){let a=m[n];if(a.length){E.push("{ rank="+(n==="input"?"source":"sink")+"; "+a.join("; ")+"; }");for(let b=1;b<a.length;b++)E.push(a[b-1]+" -> "+a[b]+" [style=invis, weight=100];")}}for(let n of r.edges){if(o.has(n.to)&&!c.has(n.to))continue;let a=t.get(n.from+":"+n.output)||"n"+n.from+(r.nodes[n.from].kind==="call"?":out"+n.output:""),b=r.nodes[n.to],q=c.get(n.to)||"n"+n.to+(g(b)?":in"+n.input:"");b.binary&&(q+=n.input===0?":w":":e"),E.push(a+" -> "+q+";")}E.push("}");let S=await Viz.instance(),P=S.render(E.join(`
23
+ `),{engine:"dot",format:"svg"});if(P.status!=="success")throw Error(P.errors.map(n=>n.message).join("; "));self.postMessage({svg:P.output,details:d,hidden:Array.from(o)})}catch(i){self.postMessage({error:i.message||String(i)})}}}let Ae="("+Re.toString()+")();",K=null,ae=null;function de(){K&&K.terminate(),K=null,ae&&URL.revokeObjectURL(ae),ae=null}function se(e){R(new Error(e)),de(),l("loading-text").textContent=e,l("cancel-layout").hidden=!0,W(e,"error")}function Oe(e,i,s){let r=new DOMParser().parseFromString(e,"image/svg+xml");if(r.querySelector("parsererror")||r.documentElement.localName!=="svg")throw Error("Viz.js returned invalid SVG");w=document.importNode(r.documentElement,!0),w.setAttribute("role","img"),w.setAttribute("aria-label","Function instruction graph"),w.removeAttribute("width"),w.removeAttribute("height"),l("canvas").prepend(w),he=w.getAttribute("viewBox");for(let t of i){let c=w.getElementById(t.id);c.classList.remove("node"),c.classList.add(t.render==="io"?"io-node":"value-node"),c.onclick=()=>{let p=t.node??t.cells[0]?.node??t.owners?.[0]?.node;p!==void 0&&oe(p)};let o=Array.from(c.querySelectorAll("text")),u=new Map;if(t.boundary){for(let k of t.owners)u.set(k.node,[]);let p=document.createElementNS("http://www.w3.org/2000/svg","text"),g=c.getBBox();p.classList.add("trace-value"),p.setAttribute("x",g.x+g.width/2),p.setAttribute("y",g.y+g.height+14),p.setAttribute("text-anchor","middle"),c.append(p),t.traceLabel=p}for(let p of t.cells){let g=o.findIndex(B=>B.textContent===p.label),k=p.node??t.node;u.has(k)||u.set(k,[]),g>=0&&u.get(k).push({...p,element:o.splice(g,1)[0]})}t.node!==null&&!u.has(t.node)&&u.set(t.node,[]);for(let[p,g]of u)X.has(p)||X.set(p,[]),X.get(p).push({element:c,port:t.port,cells:g,boundary:t.boundary?t:null})}for(let t of N.nodes){let c=w.getElementById("instruction-"+t.id);if(!c){if(s.includes(t.id)){ie(t.id);continue}throw Error("Missing graph node "+t.id)}Q.set(t.id,c),c.onclick=()=>oe(t.id),t.callee!==void 0&&(c.onclick=()=>{clearTimeout(ne),ne=setTimeout(()=>oe(t.id),400)},c.ondblclick=()=>{clearTimeout(ne),ye(t.id)},c.querySelector("title").textContent="Double-click to step into "+t.display),ie(t.id)}C!==null&&oe(C),w.addEventListener("wheel",t=>{t.preventDefault();let c=w.viewBox.baseVal,o=Math.exp(Math.max(-1,Math.min(1,t.deltaY*.001))),u=new DOMPoint(t.clientX,t.clientY).matrixTransform(w.getScreenCTM().inverse());w.setAttribute("viewBox",[u.x+(c.x-u.x)*o,u.y+(c.y-u.y)*o,c.width*o,c.height*o].join(" "))},{passive:!1});let d=null;w.onpointerdown=t=>{t.button!==0||t.target.closest(".node,.io-node,.value-node")||(d={x:t.clientX,y:t.clientY,view:w.getAttribute("viewBox").split(/\s+/).map(Number)},w.setPointerCapture(t.pointerId))},w.onpointermove=t=>{if(!d)return;let c=w.getScreenCTM(),[o,u,p,g]=d.view;w.setAttribute("viewBox",[o-(t.clientX-d.x)/c.a,u-(t.clientY-d.y)/c.d,p,g].join(" "))},w.onpointerup=w.onpointercancel=()=>{d=null},x(),l("loading").hidden=!0,f||W("Select a node to inspect it. Scroll to zoom; drag to pan.")}l("fit").onclick=()=>{w&&w.setAttribute("viewBox",he)},l("cancel-layout").onclick=()=>se("Layout cancelled. Reopen the file to try again.");function ee(){clearTimeout(ne),de(),w&&w.remove(),w=null,Q.clear(),X.clear(),l("loading").hidden=!1,l("loading-text").textContent="Laying out the graph\u2026",l("cancel-layout").hidden=!1;try{ae=URL.createObjectURL(new Blob([O.source||"",`
24
+ `,Ae],{type:"text/javascript"})),K=new Worker(ae),K.onmessage=({data:e})=>{if(e.error){se("Layout failed: "+e.error);return}de();try{Oe(e.svg,e.details,e.hidden)}catch(i){se(i.message)}},K.onerror=e=>se("Could not load Viz.js. Check connectivity, or export with the viz_js option for offline use."),K.postMessage({url:O.url,model:N,viewMode:F,showContents:le,showSizes:ue})}catch(e){se(e.message)}}return l("view-mode").onchange=()=>{F=l("view-mode").value,U(),ee()},l("detail-toggle").onchange=()=>{le=l("detail-toggle").checked,U(),ee()},l("size-toggle").onchange=()=>{ue=l("size-toggle").checked,U(),ee()},fe(),ee(),{ready:V,loadTrace:xe,destroy(){D(),clearTimeout(ne),++re,de(),R(new DOMException("Viewer replaced or destroyed","AbortError"))},setView(e){if(!["function","expression"].includes(e))throw Error("Unknown graph view: "+e);F=e,fe(),U(),ee()}}}export{Ge as createGraphViewer};
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@viz-js/viz",
3
+ "description": "WebAssembly build of Graphviz with a simple wrapper for using it on the web",
4
+ "keywords": [
5
+ "graphviz",
6
+ "emscripten"
7
+ ],
8
+ "version": "3.30.0",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/mdaines/viz-js.git",
12
+ "directory": "packages/viz"
13
+ },
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "main": "./dist/viz.js",
17
+ "types": "./types/index.d.ts",
18
+ "exports": {
19
+ "types": "./types/index.d.ts",
20
+ "require": "./dist/viz.cjs",
21
+ "default": "./dist/viz.js"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "lib",
26
+ "src",
27
+ "types"
28
+ ],
29
+ "devDependencies": {
30
+ "@babel/core": "^7.29.0",
31
+ "@babel/preset-env": "^7.29.0",
32
+ "@rollup/plugin-babel": "^6.1.0",
33
+ "@rollup/plugin-terser": "^0.4.4",
34
+ "jsdom": "^21.1.2",
35
+ "mocha": "^11.7.5",
36
+ "rollup": "^3.30.0",
37
+ "typedoc": "^0.28.17",
38
+ "typedoc-plugin-mdn-links": "^5.1.1"
39
+ },
40
+ "scripts": {
41
+ "test": "mocha",
42
+ "docs": "typedoc types/index.d.ts"
43
+ }
44
+ }