@casadi/casadi-reader 0.0.0-poc

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.
@@ -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,17 @@
1
+ casadi-reader's implementation is licensed under the MIT License (LICENSE).
2
+
3
+ The vendored schemes/serialization_scheme.json contains serializer source
4
+ excerpts from CasADi 3.8.1, https://github.com/casadi/casadi. Those excerpts
5
+ retain CasADi's LGPL-3.0-or-later license; they are not relicensed by this
6
+ repository's MIT License. License texts are in LICENSES/.
7
+
8
+ CasADi source attribution:
9
+ Copyright (C) 2010-2023 Joel Andersson, Joris Gillis, Moritz Diehl,
10
+ KU Leuven. All rights reserved.
11
+ Copyright (C) 2011-2014 Greg Horn
12
+ Additional source-file notices remain available in the referenced CasADi tree.
13
+
14
+ The published reader runtime assets contain generated protocol metadata,
15
+ not the scheme's serializer source excerpts. The full scheme is included in
16
+ this source repository and Python source distributions as a generation/test
17
+ input; it is not needed by the installed readers.
package/README.md ADDED
@@ -0,0 +1,273 @@
1
+ # casadi-reader
2
+
3
+ Inspect `.casadi` files without installing or loading CasADi. One repository
4
+ provides JavaScript/npm, Python/PyPI, C++, C, MATLAB and Julia interfaces.
5
+ The current development focus is the **npm package**. The other language
6
+ interfaces are experimental and deferred. This is not yet a published npm release.
7
+ Files are inspected, never evaluated; no archives are extracted.
8
+
9
+ | Interface | Implementation | Runtime dependencies |
10
+ | --- | --- | --- |
11
+ | `@casadi/casadi-reader` (npm) | Standalone JavaScript | None; Node 22+ or browser ESM |
12
+ | `casadi-reader` (PyPI) | Standalone Python | None; Python 3.9+ |
13
+ | C++ | Native reader, RAII `Document` | C++ standard library |
14
+ | C | C ABI over the native reader | Same native library |
15
+ | MATLAB | MATLAB package and MEX | Native reader compiled into the MEX |
16
+ | Julia `CasadiReader` | Julia package calling the C ABI | Standalone native library, JSON.jl |
17
+
18
+ All interfaces use the same object-table JSON contract and fixtures. The three
19
+ reader implementations use source assets generated from the vendored scheme.
20
+ MATLAB and Julia do not launch Python, Node or a subprocess to decode files.
21
+
22
+ ## Python
23
+
24
+ Install locally with `pip install .` (the distribution declares no runtime
25
+ requirements):
26
+
27
+ ```python
28
+ from casadi_reader import read_casadi, read_resource, to_json
29
+
30
+ graph = read_casadi('model.casadi')
31
+ print(to_json(graph, indent=2))
32
+
33
+ resource = read_resource('resource.casadi', lazy=True)
34
+ blob = resource['resource']['blob']
35
+ try:
36
+ first_bytes = blob.read(0, 64)
37
+ finally:
38
+ blob.close()
39
+ ```
40
+
41
+ File input uses a read-only memory map. Lazy payloads keep that mapping alive;
42
+ metadata and requested slices are decoded, without allocating the whole archive.
43
+ `loads(text)` and `loads_resource(text, lazy=True)` also accept encoded strings.
44
+ The CLI is `casadi-reader [--resource] [--lazy] input.casadi [output.json]`, or
45
+ `python -m casadi_reader ...`.
46
+
47
+ ## JavaScript
48
+
49
+ Install locally with `npm install /path/to/casadi-reader`:
50
+
51
+ ```js
52
+ import {readCasadi, decodeResource, openResource} from '@casadi/casadi-reader';
53
+ const graph = readCasadi(await file.text());
54
+ const {resource} = decodeResource(resourceStreamText, {lazy: true});
55
+ const firstBytes = resource.blob.read(0, 64); // Uint8Array
56
+
57
+ // File/Blob input also defers reading the encoded payload:
58
+ const opened = await openResource(resourceFile, {lazy: true});
59
+ const bytes = await opened.resource.blob.read(0, 64);
60
+ ```
61
+
62
+ The npm tarball contains bundled ESM in `dist/`, with serialization metadata
63
+ compiled into the JavaScript. It does not fetch or import the scheme JSON.
64
+ After publication, a browser can import the versioned
65
+ `https://unpkg.com/@casadi/casadi-reader@VERSION/dist/index.js` directly from a
66
+ `<script type="module">`; no import map or bundler is required. `VERSION` is a
67
+ placeholder: this prototype has not been published.
68
+
69
+ The Node CLI is `node bin/casadi-reader.js [--resource] [--lazy] input.casadi`.
70
+ Text mode retains the encoded string. File/Blob mode reads a bounded metadata
71
+ prefix, then requested slices. File/Blob Resource input must have no surrounding
72
+ whitespace. An application installing both CLIs should use the explicit module
73
+ or Node entry point to avoid the common `casadi-reader` executable name.
74
+
75
+ ## C++ and C
76
+
77
+ Build with CMake and a C++11 compiler; no third-party library is needed:
78
+
79
+ ```sh
80
+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
81
+ cmake --build build
82
+ ctest --test-dir build --output-on-failure
83
+ cmake --install build --prefix /your/prefix
84
+ ```
85
+
86
+ Installed CMake consumers can use `find_package(casadi_reader CONFIG REQUIRED)`
87
+ and link `casadi_reader::casadi_reader`. Headers are
88
+ `<casadi_reader/reader.hpp>` and `<casadi_reader/reader.h>`.
89
+
90
+ ```cpp
91
+ casadi_reader::Document graph("model.casadi");
92
+ std::string json = graph.json();
93
+ casadi_reader::Document resource("resource.casadi", true, true);
94
+ auto bytes = resource.read_blob(0, 0, 64);
95
+ ```
96
+
97
+ ```c
98
+ char error[1024];
99
+ cr_document *doc = cr_open("model.casadi", 0, 0, error, sizeof(error));
100
+ if (doc) {
101
+ puts(cr_json(doc)); /* pointer valid until cr_close */
102
+ cr_close(doc);
103
+ } else {
104
+ fprintf(stderr, "%s\n", error);
105
+ }
106
+ ```
107
+
108
+ The C ABI catches exceptions and reports errors through caller-owned buffers.
109
+ Handles own their source streams; lazy blob slices seek directly to encoded
110
+ file ranges. C/C++ blob indices and byte offsets are zero-based. Do not share
111
+ one handle between concurrent operations. Native eager archive-to-JSON expansion
112
+ is limited to 1,000,000 bytes; use lazy mode for larger archives.
113
+
114
+ ## MATLAB
115
+
116
+ ```sh
117
+ cmake -S . -B build -DCASADI_READER_MATLAB=ON
118
+ cmake --build build
119
+ ```
120
+
121
+ ```matlab
122
+ addpath('matlab');
123
+ addpath('build/matlab');
124
+ graph = casadi_reader.read('model.casadi');
125
+ document = casadi_reader.Document('resource.casadi', true, true);
126
+ cleanup = onCleanup(@() delete(document));
127
+ metadata = document.data();
128
+ bytes = document.readBlob(1, 0, 64);
129
+ ```
130
+
131
+ `Document.json()` returns JSON text; `data()` uses MATLAB's `jsondecode`.
132
+ The package ZIP can include the built MEX. MEX binaries are platform-specific;
133
+ this prototype has been tested with MATLAB R2024b on Linux.
134
+
135
+ ## Julia
136
+
137
+ From this checkout, build the library and instantiate the Julia environment:
138
+
139
+ ```sh
140
+ julia --project=julia -e 'using Pkg; Pkg.instantiate(); include("julia/deps/build.jl")'
141
+ ```
142
+
143
+ ```julia
144
+ using CasadiReader
145
+ graph = read_casadi("model.casadi")
146
+ document = read_resource("resource.casadi"; lazy=true)
147
+ try
148
+ metadata = data(document)
149
+ bytes = read_blob(document, 1, 0, 64)
150
+ finally
151
+ close(document)
152
+ end
153
+ ```
154
+
155
+ The source archive is a self-contained Julia project, including the native
156
+ sources in `deps/reader`. `Pkg.build("CasadiReader")` needs CMake and a C++
157
+ compiler. Alternatively set `CASADI_READER_LIBRARY` to an existing standalone
158
+ reader library before starting Julia. Tested with Julia 1.6.2 on Linux.
159
+
160
+ MATLAB and Julia blob indices are one-based; byte offsets remain zero-based.
161
+ **Object references inside the JSON contract remain zero-based in every language.**
162
+ For example, a Julia consumer accesses the root as `graph["objects"][graph["root"]+1]`.
163
+
164
+ ## JSON contract
165
+
166
+ Graph documents have `format: "casadi_json"`, `version: 1`,
167
+ `serializationProtocol: 3`, a `root` object index, and an `objects` array.
168
+ References are indices; shared nodes are stored once; null references stay null.
169
+
170
+ - `kind: "function"`: name, type, input/output sparsities and names, input nodes,
171
+ and instructions containing node references and argument/result work slots.
172
+ - `kind: "mx"`: operation ID/name, dependency and sparsity references, constants
173
+ and node-specific `info`. Indexing nodes also have a normalized `mapping`.
174
+ Constants are numeric strings, including nonfinite values; decimal spelling
175
+ may differ between implementations.
176
+ - `kind: "sparsity"`: shape and compressed-column `colind` / `row` arrays.
177
+
178
+ `info` is reconstructed from serialized members and tested against native
179
+ `MX.info()`. It does not prescribe viewer layout or styling. The representation
180
+ is not lossless and cannot be written back to `.casadi` by this prototype.
181
+
182
+ Lazy Resource payloads serialize as small descriptors with `offset`, `byteLength`
183
+ and `encoding`. Retrieving bytes requires the live document/blob and its original
184
+ source; descriptors alone are not portable archive copies. Lazy mode defers
185
+ opaque payloads, not all numerical arrays or graph nodes. Eager mode is default.
186
+ Payload encoding is checked on access; declared extents are checked on opening.
187
+
188
+ ## Supported subset
189
+
190
+ The fixtures come from CasADi 3.8.1 default `Function.save()` files: MX arithmetic,
191
+ sparse matrices, gathers, slices and entry assignments. Supported layouts are
192
+ ProtoFunction 2, FunctionInternal 8, XFunction 1, MXFunction 3, little-endian
193
+ protocol 3. Unsupported operations/layouts fail explicitly. SX functions, nested
194
+ function calls, plugins, JIT, nonempty option/cache dictionaries and debug
195
+ serialization are outside this prototype. It is not a general reader for every
196
+ CasADi file or version, nor a hardened untrusted-file service.
197
+
198
+ Resource entry points accept a **raw SerializingStream containing one Resource**.
199
+ This tests the embedded ZIP representation used by FMUs, but **does not yet read
200
+ an entire saved FmuFunction**. No FMU is loaded or executed.
201
+
202
+ ## Scheme, tests and packaging
203
+
204
+ `schemes/serialization_scheme.json` vendors CasADi's checked-in
205
+ `misc/serialization_scheme.json`. It is a source-derived serializer index and
206
+ named-field contract, **not a complete executable deserialization grammar**.
207
+ `scripts/generate-reader-assets.py` consumes this JSON and emits three checked-in
208
+ source assets: `src/scheme.js`, `python/casadi_reader/_scheme.py`, and
209
+ `native/src/scheme.hpp`. These contain runtime protocol constants, operation IDs
210
+ and class versions, omitting the C++ source index. Supported positional layouts
211
+ are still implemented explicitly in the readers.
212
+
213
+ `npm run build` regenerates the assets and bundles the JavaScript. `npm pack`
214
+ runs that build automatically. Python packages contain the generated Python
215
+ module, so neither Python nor JavaScript parses the scheme JSON at runtime.
216
+ Build tools are development dependencies only.
217
+
218
+ CI checks `npm run check:generated` **before** rebuilding, rejecting stale
219
+ committed assets. The initial CI builds and tests the npm package and produces its tarball. A browser test serves the extracted npm tarball
220
+ over HTTP and checks that decoding needs one JavaScript request and no scheme
221
+ JSON request. CI uploads build artifacts; it does not publish packages.
222
+
223
+ ```sh
224
+ node scripts/vendor-scheme.mjs ../serialization-scheme/misc/serialization_scheme.json
225
+ python scripts/generate-reader-assets.py
226
+ npm ci
227
+ npm run check:generated
228
+ npm test
229
+ npm run test:browser
230
+ PYTHONPATH=python python -m unittest discover -s python/tests -v
231
+ CASADI_READER_LIBRARY="$PWD/build/libcasadi_reader.so" julia --project=julia julia/test/runtests.jl
232
+ ```
233
+
234
+ Set `CASADI_READER_NATIVE` to the native CLI to enable Python/native agreement
235
+ tests. Python tests also compare JavaScript when Node is available. Native CasADi
236
+ is used only to regenerate fixtures (`scripts/generate-fixtures.py` and
237
+ `scripts/generate-resource-fixture.cpp`), never to run the readers. Tests check
238
+ native graph/metadata oracles and deferred 16 MiB payload access.
239
+
240
+ Create unpublished artifacts with:
241
+
242
+ ```sh
243
+ python -m build
244
+ npm pack
245
+ python scripts/package-bindings.py --output dist --mex build/matlab/casadi_reader_mex.mexa64
246
+ ```
247
+
248
+ This produces Python wheel/sdist, npm tarball, native and Julia source archives,
249
+ and a MATLAB ZIP. It does not register packages or upload releases. The adjacent
250
+ `casadi-viz` proof of concept consumes the npm package through a local dependency.
251
+
252
+ The reader implementation is MIT licensed. The vendored scheme includes
253
+ upstream CasADi source excerpts that retain their original license; see NOTICE.
254
+
255
+ ## npm publishing
256
+
257
+ `.github/workflows/publish.yml` publishes on a published GitHub release, using
258
+ OIDC Trusted Publishing and provenance. Its release tag must equal `v` plus the
259
+ version in `package.json`. Prerelease versions use npm's `next` tag; stable
260
+ versions use `latest`. It runs the tests and packed-browser check before publishing.
261
+
262
+ Once the package exists on npm, open its Settings → Trusted publishing and add:
263
+
264
+ - Provider: GitHub Actions
265
+ - Organization: `casadi`
266
+ - Repository: `casadi-reader`
267
+ - Workflow filename: `publish.yml`
268
+ - Environment: leave blank (the workflow does not use a GitHub environment)
269
+ - Allowed actions: enable direct `npm publish`
270
+
271
+ No npm token secret is needed. See the current
272
+ [npm Trusted Publishing documentation](https://docs.npmjs.com/trusted-publishers/).
273
+ The workflow is prepared; the package has not yet been published to npm.
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import {readFile,writeFile} from 'node:fs/promises';
3
+ import {decodeCasadi,decodeResource} from '../dist/index.js';
4
+ try {
5
+ const args=process.argv.slice(2),options={lazy:args.includes('--lazy')},resource=args.includes('--resource');
6
+ const [input,output,...extra]=args.filter(a=>a!=='--lazy'&&a!=='--resource');
7
+ if(!input||extra.length)throw Error('Usage: casadi-reader [--lazy] [--resource] INPUT [OUTPUT.json]');
8
+ const read=resource?decodeResource:decodeCasadi;
9
+ const json=JSON.stringify(read(await readFile(input,'utf8'),options),null,2)+'\n';
10
+ if(output)await writeFile(output,json);else process.stdout.write(json);
11
+ }catch(error){console.error(error.message);process.exitCode=1;}