sysmantic 0.3.0__py3-none-any.whl

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.
sysmantic/LICENSE.md ADDED
@@ -0,0 +1,85 @@
1
+ # Sysmantic license
2
+
3
+ Copyright 2026 Modelware (https://www.modelware.io). All rights reserved.
4
+
5
+ Sysmantic (the `sysmantic` command and its VS Code extension) is proprietary
6
+ software, made available free of charge under the terms below. These terms apply to the
7
+ version they come with; later versions may come with different terms.
8
+
9
+ ## 1. Use
10
+
11
+ Modelware grants you a free, non-exclusive, non-transferable license to install and use
12
+ Sysmantic directly, on any number of machines, as an individual or within an organization,
13
+ companies included: for your own and your organization's work on your models (for example on
14
+ workstations, build servers or in continuous integration workflows). This includes using
15
+ Sysmantic to provide services to others, such as consulting, modeling or analysis for a client,
16
+ as long as Sysmantic itself is not provided to them (they may get their own copy from Modelware).
17
+
18
+ ## 2. No commercial use of Sysmantic itself
19
+
20
+ You may not use Sysmantic commercially beyond that direct use. In particular, you may not:
21
+
22
+ - sell, rent, lease or sublicense it, or charge for access to it;
23
+ - distribute it, or include it in or with a product, service or offering for others;
24
+ - offer it, or what it does, to others as a hosted or managed service;
25
+ - build on it a product or service that you offer to others.
26
+
27
+ Such uses need a separate license from Modelware: write to info@modelware.io.
28
+
29
+ You may copy Sysmantic as distributed by Modelware, unmodified and with this license and its
30
+ notices, only for the direct use that section 1 allows.
31
+
32
+ ## 3. Restrictions
33
+
34
+ You may not modify, adapt, translate, decompile, disassemble or otherwise reverse engineer
35
+ Sysmantic, except as far as the applicable law allows despite this restriction. You may not
36
+ remove or alter its copyright, license or third-party notices.
37
+
38
+ ## 4. Your models
39
+
40
+ Models, queries and other content you create or process with Sysmantic are yours. Sysmantic runs
41
+ on your machines, and this license gives Modelware no rights to them.
42
+
43
+ ## 5. Ownership
44
+
45
+ Sysmantic is licensed, not sold. Modelware keeps all rights not expressly granted here.
46
+
47
+ ## 6. Support
48
+
49
+ Support for this free license is through the issue tracker of Sysmantic's public repository
50
+ (https://github.com/modelware/sysmantic/issues), where you can report problems and ask
51
+ questions. Modelware handles them as it sees fit, with no commitment to response times, fixes
52
+ or future versions. Modelware offers enterprise support packages, with commitments such as
53
+ these, under a separate agreement: write to info@modelware.io. Such an agreement does not
54
+ change these terms unless it says so.
55
+
56
+ ## 7. Third-party software and standard libraries
57
+
58
+ Sysmantic includes third-party software, each part under its own license, listed in the
59
+ third-party notices that come with it (`sysmantic license --third-party`). Those licenses govern
60
+ those parts, and nothing here limits the rights they grant.
61
+
62
+ Sysmantic includes the KerML and SysML v2 standard model libraries published by the Object
63
+ Management Group (OMG) with the KerML 1.0 and SysML 2.0 specifications. They remain the
64
+ property of their copyright holders and are provided under their terms.
65
+
66
+ ## 8. No warranty
67
+
68
+ Sysmantic is provided "as is", without warranty of any kind, express or implied, including the
69
+ warranties of merchantability, fitness for a particular purpose and non-infringement. You are
70
+ responsible for checking the results it gives before relying on them.
71
+
72
+ ## 9. Limitation of liability
73
+
74
+ To the extent the applicable law allows, Modelware will not be liable for any damages arising
75
+ from the use of or inability to use Sysmantic, whether direct, indirect, incidental, special,
76
+ consequential or otherwise, even if advised of their possibility.
77
+
78
+ ## 10. Termination
79
+
80
+ This license ends automatically if you break its terms; you must then stop using Sysmantic and
81
+ delete your copies. Sections 4, 5 and 7 to 9 survive its end.
82
+
83
+ ## Contact
84
+
85
+ Questions about this license: info@modelware.io.
sysmantic/__init__.py ADDED
@@ -0,0 +1,83 @@
1
+ """Sysmantic for Python and notebooks: SysML models asked in SPARQL, evaluated, verified, and shown
2
+ in the standard views.
3
+
4
+ In a notebook, `import sysmantic` (or `%load_ext sysmantic`), then:
5
+
6
+ %%sysml a cell of SysML, part of the model
7
+ %sysml <expression> a value
8
+ %%sparql [-o var] a query's answer, as a table
9
+ %viz [--view=V] <name> a standard view of an element
10
+
11
+ In Python, the same through `sysmantic.model()` (the model the notebook adds to, if loaded; else the
12
+ current directory's): `query`, `evaluate`, `verify`, `check`, `sysml`, `view`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Any
18
+
19
+ from .client import SysmanticError
20
+ from .display import table
21
+ from .model import Diagnostic, Document, Model, Quantity, Verdict
22
+
23
+ __all__ = ["Model", "Quantity", "Verdict", "Document", "Diagnostic", "SysmanticError", "model", "query", "evaluate", "verify", "view", "sysml", "table"]
24
+ __version__ = "0.3.0"
25
+
26
+ _magics: Any = None
27
+ _default: Model | None = None
28
+
29
+
30
+ def model() -> Model:
31
+ """The notebook's model (its cells' SysML included), once `%load_ext sysmantic`; else the current directory's."""
32
+ global _default
33
+ if _magics is not None:
34
+ _magics.start()
35
+ return _magics.model
36
+ if _default is None:
37
+ _default = Model()
38
+ return _default
39
+
40
+
41
+ def query(sparql: str, **options: Any) -> Any:
42
+ return model().query(sparql, **options)
43
+
44
+
45
+ def evaluate(target: str, **options: Any) -> Any:
46
+ return model().evaluate(target, **options)
47
+
48
+
49
+ def verify(target: str) -> Verdict:
50
+ return model().verify(target)
51
+
52
+
53
+ def view(element: str, kind: str = "default", **options: Any) -> Any:
54
+ return model().view(element, kind, **options)
55
+
56
+
57
+ def sysml(text: str, name: str = "python") -> Document:
58
+ return model().sysml(text, name)
59
+
60
+
61
+ def load_ipython_extension(ipython: Any) -> None:
62
+ global _magics
63
+ if _magics is not None:
64
+ return
65
+ from .magics import SysmlMagics
66
+
67
+ _magics = SysmlMagics(ipython)
68
+ ipython.register_magics(_magics)
69
+
70
+
71
+ def _load_in_notebook() -> None:
72
+ """Imported in a notebook (or IPython): its commands too, with no `%load_ext`."""
73
+ try:
74
+ from IPython import get_ipython
75
+ except ImportError:
76
+ return
77
+ ip = get_ipython()
78
+ if ip is not None:
79
+ ip.extension_manager.loaded.add("sysmantic")
80
+ load_ipython_extension(ip)
81
+
82
+
83
+ _load_in_notebook()
sysmantic/client.py ADDED
@@ -0,0 +1,111 @@
1
+ """The model's server: found (or started) with the `sysmantic` command, then asked over HTTP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+ from glob import glob
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+
18
+ class SysmanticError(Exception):
19
+ """What the model's server, or the `sysmantic` command, said went wrong."""
20
+
21
+
22
+ def command() -> str:
23
+ """The `sysmantic` command: `SYSMANTIC_PATH`, else beside this Python, else on the PATH, else where installers and VS Code put it."""
24
+ configured = os.environ.get("SYSMANTIC_PATH", "").strip()
25
+ if configured:
26
+ return os.path.expanduser(configured)
27
+ exe = "sysmantic.exe" if os.name == "nt" else "sysmantic"
28
+ # Beside this Python (a virtual environment's own), then on the PATH.
29
+ beside = Path(sys.executable).parent / exe
30
+ if beside.is_file():
31
+ return str(beside)
32
+ found = shutil.which(exe)
33
+ if found:
34
+ return found
35
+ home = Path.home()
36
+ places = [
37
+ home / ".local" / "bin",
38
+ Path(os.environ.get("LOCALAPPDATA", home / "AppData" / "Local")) / "sysmantic" / "bin",
39
+ Path("/opt/homebrew/bin"),
40
+ Path("/usr/local/bin"),
41
+ home / ".cargo" / "bin",
42
+ *sorted((Path(p) for p in glob(str(home / ".vscode" / "extensions" / "modelware.sysmantic-*" / "bin"))), reverse=True),
43
+ ]
44
+ for place in places:
45
+ if (place / exe).is_file():
46
+ return str(place / exe)
47
+ raise SysmanticError("cannot find the `sysmantic` command: install Sysmantic, or set SYSMANTIC_PATH to it")
48
+
49
+
50
+ def check_release(release: str | None) -> None:
51
+ """Sysmantic must be at least this package's version (major and minor): they are released together."""
52
+ from . import __version__
53
+
54
+ def minor(v: str) -> tuple[int, ...]:
55
+ return tuple(int(n) for n in v.split(".")[:2])
56
+
57
+ if release is None or minor(release) < minor(__version__):
58
+ raise SysmanticError(f"Sysmantic {release or '(before 0.3)'} is older than this package ({__version__}): update Sysmantic")
59
+
60
+
61
+ class Server:
62
+ """The server of the model in `directory`'s workspace (the nearest directory upward with a `sysmantic.toml`, else `directory`)."""
63
+
64
+ def __init__(self, directory: str | os.PathLike[str] | None = None):
65
+ self.directory = os.path.realpath(directory or os.getcwd())
66
+ self._url: str | None = None
67
+ self.root: str | None = None
68
+
69
+ def _run(self, *args: str) -> str:
70
+ done = subprocess.run([command(), *args], cwd=self.directory, capture_output=True, text=True)
71
+ if done.returncode not in (0, 1, 2):
72
+ raise SysmanticError(done.stderr.strip() or f"`sysmantic {' '.join(args)}` failed")
73
+ return done.stdout
74
+
75
+ def _connect(self) -> str:
76
+ # Any command starts the server when none runs; `inspect` then says where it is.
77
+ self._run("query", "ASK {}")
78
+ info = json.loads(self._run("inspect", "--json"))
79
+ check_release(info.get("release"))
80
+ self._url, self.root = info["url"], os.path.realpath(info["workspace"])
81
+ return self._url
82
+
83
+ @property
84
+ def url(self) -> str:
85
+ return self._url or self._connect()
86
+
87
+ def request(self, path: str, params: dict[str, Any] | list[tuple[str, str]] | None = None, body: Any = None, *, raw: bool = False, accept: str | None = None) -> Any:
88
+ """Ask the server; its answer as JSON (or as text, with `raw`). Reconnects once (a server that stopped when idle)."""
89
+ query = f"?{urllib.parse.urlencode(params, doseq=True)}" if params else ""
90
+ data = None if body is None else (body if isinstance(body, bytes) else json.dumps(body).encode())
91
+ for attempt in (0, 1):
92
+ request = urllib.request.Request(f"{self.url}{path}{query}", data=data, method="POST" if data is not None else "GET")
93
+ if accept:
94
+ request.add_header("Accept", accept)
95
+ try:
96
+ with urllib.request.urlopen(request, timeout=300) as reply:
97
+ text = reply.read().decode()
98
+ except urllib.error.HTTPError as e:
99
+ text = e.read().decode()
100
+ try:
101
+ message = json.loads(text).get("error", text)
102
+ except ValueError:
103
+ message = text
104
+ raise SysmanticError(message.strip()) from None
105
+ except (urllib.error.URLError, ConnectionError):
106
+ if attempt:
107
+ raise
108
+ self._url = None
109
+ continue
110
+ return text if raw else json.loads(text)
111
+ raise AssertionError("unreachable")
sysmantic/display.py ADDED
@@ -0,0 +1,177 @@
1
+ """How things show in a notebook: the standard views (drawn by the views' script, which the first
2
+ view of a session carries), and the SysML a cell holds, with its problems."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import base64
7
+ import os
8
+ import html
9
+ import json
10
+ import uuid
11
+ from importlib import resources
12
+ from typing import TYPE_CHECKING, Any
13
+
14
+ if TYPE_CHECKING:
15
+ from .model import Document, Model
16
+
17
+ class _Session:
18
+ """What this kernel has sent: whether an output carries the views' script, and which cell's."""
19
+
20
+ carrier: str | None = None
21
+ sent = False
22
+ script: str | None = None
23
+ stamp: int | None = None
24
+
25
+
26
+ def _script() -> str:
27
+ """The views' script (gzipped, in base64): read again when it changes (a rebuilt package)."""
28
+ file = resources.files("sysmantic").joinpath("static/views.js.gz")
29
+ try:
30
+ stamp = os.stat(str(file)).st_mtime_ns
31
+ except OSError:
32
+ stamp = None
33
+ if _Session.script is None or stamp != _Session.stamp:
34
+ _Session.script = base64.b64encode(file.read_bytes()).decode()
35
+ _Session.stamp = stamp
36
+ # A new script: the next view carries it.
37
+ _Session.sent = False
38
+ return _Session.script
39
+
40
+
41
+ def _cell_id() -> str | None:
42
+ try:
43
+ from IPython import get_ipython
44
+
45
+ ip = get_ipython()
46
+ parent = ip.kernel.get_parent() if ip and hasattr(ip, "kernel") else {}
47
+ return (parent or {}).get("metadata", {}).get("cellId")
48
+ except Exception: # Not in a kernel, or one that says nothing of cells.
49
+ return None
50
+
51
+
52
+ def _version() -> str:
53
+ """The views' script's version: its digest."""
54
+ import hashlib
55
+
56
+ return hashlib.sha1(_script().encode()).hexdigest()[:12]
57
+
58
+
59
+ def _carries_script() -> bool:
60
+ """Whether this output carries the views' script: the first view of the session does, any
61
+ output of the cell that did (run again, its new output replaces the one that carried it), and
62
+ the first view after the script changed."""
63
+ _script()
64
+ cell = _cell_id()
65
+ if not _Session.sent or (cell is not None and cell == _Session.carrier):
66
+ _Session.sent, _Session.carrier = True, cell
67
+ return True
68
+ return False
69
+
70
+
71
+ # The views' script, by its version: an output loads it unless that version is loaded already (a
72
+ # page keeps what it loaded, a kernel restart notwithstanding; a newer version replaces it).
73
+ LOADER = """<script>(function () {
74
+ const version = %s;
75
+ if ((window.SysmanticViews && window.SysmanticViews.version === version) || window.__sysmanticLoading === version) return;
76
+ window.__sysmanticLoading = version;
77
+ const bytes = Uint8Array.from(atob(%s), (c) => c.charCodeAt(0));
78
+ new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))).text().then((code) => {
79
+ const s = document.createElement('script');
80
+ s.textContent = code;
81
+ document.head.appendChild(s);
82
+ window.SysmanticViews.version = version;
83
+ const pending = window.__sysmanticPending || [];
84
+ window.__sysmanticPending = [];
85
+ pending.forEach((go) => go());
86
+ });
87
+ })();</script>"""
88
+
89
+ SHOW = """<script>(function () {
90
+ const id = %s, version = %s;
91
+ const ready = () => window.SysmanticViews && window.SysmanticViews.version === version;
92
+ const go = () => {
93
+ const el = document.getElementById(id);
94
+ const data = document.getElementById(id + '-data');
95
+ if (el && data) window.SysmanticViews.render(el, JSON.parse(data.textContent));
96
+ };
97
+ if (ready()) go(); else (window.__sysmanticPending = window.__sysmanticPending || []).push(go);
98
+ setTimeout(() => {
99
+ if (ready()) return;
100
+ const el = document.getElementById(id);
101
+ if (el) el.querySelector('.sv-placeholder').textContent = 'Run this cell to draw the view: the output that carried the views’ script is gone.';
102
+ }, 8000);
103
+ })();</script>"""
104
+
105
+
106
+ class View:
107
+ """A standard view, drawn when shown (it reads the model then)."""
108
+
109
+ def __init__(self, model: "Model", kind: str, element: str, highlight: list[str], note: str | None, style: str | None, height: int | None, fade: bool = False):
110
+ self.model, self.kind, self.element = model, kind, element
111
+ self.highlight, self.note, self.style, self.height, self.fade = highlight, note, style, height, fade
112
+
113
+ def _payload(self) -> dict[str, Any]:
114
+ """The view as the server computes it (what it shows), and how to show it."""
115
+ params: list[tuple[str, str]] = [("kind", self.kind), ("element", self.element)]
116
+ params += [("highlight", h) for h in self.highlight]
117
+ view = self.model.server.request("/view", params)
118
+ payload: dict[str, Any] = {"kind": view["kind"], "name": view["name"], "title": view["title"], "classes": view["classes"], "diagram": view["diagram"], "iri": view["iri"],
119
+ # Where to ask for the next view (a package opened, a part opened in place).
120
+ "server": self.model.server.url}
121
+ if view.get("highlight"):
122
+ payload["highlight"] = view["highlight"]
123
+ for key in ("note", "style", "height"):
124
+ if getattr(self, key):
125
+ payload[key] = getattr(self, key)
126
+ if not self.fade:
127
+ payload["fade"] = False
128
+ return payload
129
+
130
+ def _repr_mimebundle_(self, include: Any = None, exclude: Any = None) -> dict[str, str]:
131
+ payload = self._payload()
132
+ title = f"{payload['title']} of {self.element}"
133
+ id = f"sv-{uuid.uuid4().hex[:12]}"
134
+ data = json.dumps(payload).replace("<", "\\u003c")
135
+ # Its full height from the start: the notebook lays out its cells once, before the view is drawn.
136
+ height = self.height or 520
137
+ page = (
138
+ f'<div id="{id}" class="sysmantic-view" style="height:{height}px;box-sizing:border-box"><div class="sv-placeholder" style="padding:8px 12px;opacity:.7;font:13px system-ui,sans-serif">'
139
+ f"{html.escape(title)}: drawn when the notebook runs in Jupyter or VS Code.</div></div>"
140
+ f'<script type="application/json" id="{id}-data">{data}</script>'
141
+ + (LOADER % (json.dumps(_version()), json.dumps(_script())) if _carries_script() else "")
142
+ + SHOW % (json.dumps(id), json.dumps(_version()))
143
+ )
144
+ return {"text/html": page, "text/plain": title}
145
+
146
+ def __repr__(self) -> str:
147
+ return f"{self.kind} view of {self.element}"
148
+
149
+
150
+ def document_html(doc: "Document") -> str:
151
+ rows = []
152
+ for d in doc.declared:
153
+ members = f' <span style="opacity:.6">({d.members} members)</span>' if d.members else ""
154
+ rows.append(f'<div><span style="opacity:.65">{html.escape(d.keyword)}</span> <b>{html.escape(d.name or "(unnamed)")}</b>{members}</div>')
155
+ colors = {"error": "#d1242f", "warning": "#9a6700", "info": "#57606a"}
156
+ for d in doc.diagnostics:
157
+ rows.append(
158
+ f'<div style="color:{colors.get(d.severity, "inherit")}">{html.escape(d.severity)} at line {d.line}: {html.escape(d.message)}</div>'
159
+ )
160
+ if not rows:
161
+ rows.append('<div style="opacity:.65">(nothing declared)</div>')
162
+ return f'<div style="font:12.5px system-ui,sans-serif;line-height:1.5;border-left:3px solid {"#d1242f" if doc.errors else "#2f8a3a"};padding:2px 10px">{"".join(rows)}</div>'
163
+
164
+
165
+ def table(df: Any, formats: dict[str, str] | None = None) -> Any:
166
+ """A table as a report shows one: no row numbers, text left, numbers right; `formats` by column
167
+ (`{"mass (kg)": "{:.3f}"}`). A pandas Styler, which notebooks show."""
168
+ import pandas as pd
169
+
170
+ df = df.reset_index(drop=True)
171
+ styled = df.style.hide(axis="index").format(formats, na_rep="")
172
+ for i, column in enumerate(df.columns):
173
+ numeric = pd.api.types.is_numeric_dtype(df[column]) and not pd.api.types.is_bool_dtype(df[column])
174
+ align = "right" if numeric else "left"
175
+ styled = styled.set_properties(subset=[column], **{"text-align": align})
176
+ styled = styled.set_table_styles([{"selector": f"th.col_heading.col{i}", "props": [("text-align", align)]}], overwrite=False)
177
+ return styled
sysmantic/magics.py ADDED
@@ -0,0 +1,165 @@
1
+ """The notebook's commands (`%load_ext sysmantic`):
2
+
3
+ %%sysml [name] the cell's SysML, held in the model (run again, it replaces itself)
4
+ %sysml <expression> a value (`%sysml Rover::rover.mass`), or `%sysml check`, `%sysml clear`
5
+ %%sparql [-o var] a SPARQL query: its answer as a table
6
+ %viz [--view=V] <name> a standard view of an element (the pilot implementation's `%viz`)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import os
13
+ import re
14
+ import shlex
15
+ from typing import Any
16
+
17
+ from IPython.core.magic import Magics, cell_magic, line_magic, magics_class
18
+ from IPython.display import HTML, display
19
+
20
+ from .client import SysmanticError
21
+ from .model import Model
22
+
23
+ DECLARATION = re.compile(
24
+ r"^\s*(?:(?:standard|library|abstract|variation|individual|private|public|protected)\s+)*"
25
+ r"(?:package|part|item|port|action|state|attribute|requirement|constraint|calc|connection|interface|occurrence|"
26
+ r"enum|view|viewpoint|use\s+case|analysis|verification|allocation|flow|metadata|concern|rendering)\b(?:\s+def)?\s+('[^']+'|\w+)",
27
+ re.M,
28
+ )
29
+
30
+
31
+ def notebook_path(ns: dict[str, Any]) -> str | None:
32
+ """The notebook's file, where the kernel can tell: VS Code says so, as does Jupyter's server."""
33
+ if ns.get("__vsc_ipynb_file__"):
34
+ return str(ns["__vsc_ipynb_file__"])
35
+ session = os.environ.get("JPY_SESSION_NAME")
36
+ if session and session.endswith(".ipynb"):
37
+ return session if os.path.isabs(session) else os.path.join(os.getcwd(), session)
38
+ return None
39
+
40
+
41
+ def _error(message: str) -> None:
42
+ display(HTML(f'<div style="font:12.5px system-ui,sans-serif;border-left:3px solid #d1242f;padding:2px 10px">{message}</div>'))
43
+
44
+
45
+ @magics_class
46
+ class SysmlMagics(Magics):
47
+ def __init__(self, shell: Any):
48
+ super().__init__(shell)
49
+ path = notebook_path(shell.user_ns)
50
+ directory = os.path.dirname(path) if path else os.getcwd()
51
+ self.model = Model(directory, documents=None)
52
+ self.notebook = os.path.realpath(path) if path else None
53
+ # Each cell's document, by the cell (as the frontend names it) or by what it declares.
54
+ self.cells: dict[str, str] = {}
55
+ self.started = False
56
+
57
+ def start(self) -> None:
58
+ """Places this notebook's documents (under the notebook, as `<notebook>.ipynb/<cell>.sysml`) and drops any left by an earlier session."""
59
+ if self.started:
60
+ return
61
+ root = self.model.server.root or (self.model.server.url and self.model.server.root)
62
+ assert root
63
+ place = os.path.relpath(self.notebook, root) if self.notebook and self.notebook.startswith(root + os.sep) else "notebook.ipynb"
64
+ self.model._documents = place
65
+ self.model.drop()
66
+ self.started = True
67
+
68
+ def _name(self, cell: str, given: str | None) -> str:
69
+ if given:
70
+ return re.sub(r"[^\w.-]", "_", given)
71
+ from .display import _cell_id
72
+
73
+ cell_id = _cell_id()
74
+ if cell_id:
75
+ if cell_id not in self.cells:
76
+ self.cells[cell_id] = f"cell-{len(self.cells) + 1}"
77
+ return self.cells[cell_id]
78
+ found = DECLARATION.search(cell)
79
+ if found:
80
+ return re.sub(r"[^\w.-]", "_", found.group(1).strip("'"))
81
+ return f"cell-{self.shell.execution_count}"
82
+
83
+ @cell_magic
84
+ def sysml(self, line: str, cell: str) -> Any:
85
+ """%%sysml [name]: the cell's SysML, part of the model (named for the cell, else as given)."""
86
+ return self._sysml(line, cell)
87
+
88
+ @line_magic("sysml")
89
+ def sysml_line(self, line: str) -> Any:
90
+ """%sysml <expression>: its value. %sysml check: the model's problems. %sysml clear: drop the notebook's SysML."""
91
+ return self._sysml(line, None)
92
+
93
+ def _sysml(self, line: str, cell: str | None) -> Any:
94
+ try:
95
+ self.start()
96
+ if cell is not None:
97
+ if not cell.strip():
98
+ return None
99
+ doc = self.model.sysml(cell, self._name(cell, line.strip() or None))
100
+ return doc
101
+ text = line.strip()
102
+ if text == "clear":
103
+ self.model.drop()
104
+ self.cells.clear()
105
+ return None
106
+ if text == "check":
107
+ found = self.model.check()
108
+ return "\n".join(f"{f}:{d}" for f, d in found) or "No problems."
109
+ if not text:
110
+ return None
111
+ return self.model.evaluate(text)
112
+ except SysmanticError as e:
113
+ _error(str(e))
114
+ return None
115
+
116
+ @cell_magic
117
+ def sparql(self, line: str, cell: str) -> Any:
118
+ """%%sparql [-o var] [--no-entailment]: the query's answer (a table; for an ASK, true or false); with -o, kept in var, not shown."""
119
+ parser = argparse.ArgumentParser(prog="%%sparql", add_help=False)
120
+ parser.add_argument("-o", "--output")
121
+ parser.add_argument("--no-entailment", action="store_true")
122
+ args = parser.parse_args(shlex.split(line))
123
+ try:
124
+ self.start()
125
+ answer = self.model.query(cell, entailment=not args.no_entailment)
126
+ except SysmanticError as e:
127
+ _error(str(e))
128
+ return None
129
+ if args.output:
130
+ # Kept for what comes next, not shown.
131
+ self.shell.user_ns[args.output] = answer
132
+ return None
133
+ return answer
134
+
135
+ @line_magic
136
+ def viz(self, line: str) -> Any:
137
+ """%viz [--view=general|interconnection|action-flow|state-transition|sequence|grid|geometry] <name>
138
+ [--highlight=a,b] [--fade] [--note=text] [--style=css] [--height=px]: a standard view of an element.
139
+ Highlighted elements are outlined; with --fade, the rest also steps back."""
140
+ parser = argparse.ArgumentParser(prog="%viz", add_help=False)
141
+ parser.add_argument("names", nargs="+")
142
+ parser.add_argument("--view", default="default")
143
+ parser.add_argument("--highlight", default="")
144
+ parser.add_argument("--note")
145
+ parser.add_argument("--style")
146
+ parser.add_argument("--height", type=int)
147
+ parser.add_argument("--fade", action="store_true")
148
+ parser.add_argument("--no-fade", action="store_true") # The default; accepted as written before.
149
+ try:
150
+ args = parser.parse_args(shlex.split(line))
151
+ except SystemExit:
152
+ _error("usage: %viz [--view=V] &lt;element&gt; [--highlight=a,b] [--note=text] [--height=px]")
153
+ return None
154
+ try:
155
+ self.start()
156
+ views = [
157
+ self.model.view(n, args.view, highlight=[h for h in args.highlight.split(",") if h], note=args.note, style=args.style, height=args.height, fade=args.fade and not args.no_fade)
158
+ for n in args.names
159
+ ]
160
+ except SysmanticError as e:
161
+ _error(str(e))
162
+ return None
163
+ for v in views[:-1]:
164
+ display(v)
165
+ return views[-1]
sysmantic/model.py ADDED
@@ -0,0 +1,232 @@
1
+ """A SysML model, as its workspace's server knows it: asked in SPARQL, evaluated, verified, checked,
2
+ added to (SysML held in memory, as a notebook's cells are), and shown in the standard views."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Iterable
9
+
10
+ from .client import Server, SysmanticError
11
+
12
+ PILOT_VIEWS = {
13
+ # The pilot implementation's `%viz --view` names; any other is the server's to know.
14
+ "tree": "general",
15
+ "mixed": "general",
16
+ "case": "general",
17
+ "state": "state-transition",
18
+ "statetransition": "state-transition",
19
+ "action": "action-flow",
20
+ "actionflow": "action-flow",
21
+ "table": "grid",
22
+ }
23
+
24
+
25
+ class Quantity(float):
26
+ """A computed number, with its unit (`1900.0 [kg]`); a plain float to compute with."""
27
+
28
+ unit: str | None
29
+ text: str
30
+
31
+ def __new__(cls, number: float, unit: str | None = None, text: str | None = None) -> "Quantity":
32
+ q = super().__new__(cls, number)
33
+ q.unit = unit or None
34
+ q.text = text or (f"{number:g} [{unit}]" if unit else f"{number:g}")
35
+ return q
36
+
37
+ def __repr__(self) -> str:
38
+ return self.text
39
+
40
+
41
+ @dataclass
42
+ class Diagnostic:
43
+ line: int
44
+ column: int
45
+ severity: str
46
+ message: str
47
+
48
+ def __str__(self) -> str:
49
+ return f"{self.line}:{self.column}: {self.severity}: {self.message}"
50
+
51
+
52
+ @dataclass
53
+ class Declared:
54
+ keyword: str
55
+ name: str | None
56
+ iri: str
57
+ members: int
58
+
59
+
60
+ @dataclass
61
+ class Document:
62
+ """SysML held in the model (a notebook cell's): what it declares, and its problems."""
63
+
64
+ name: str
65
+ text: str
66
+ declared: list[Declared] = field(default_factory=list)
67
+ diagnostics: list[Diagnostic] = field(default_factory=list)
68
+
69
+ @property
70
+ def errors(self) -> list[Diagnostic]:
71
+ return [d for d in self.diagnostics if d.severity == "error"]
72
+
73
+ def _repr_html_(self) -> str:
74
+ from .display import document_html
75
+
76
+ return document_html(self)
77
+
78
+ def __repr__(self) -> str:
79
+ lines = [f"{d.keyword} {d.name or '(unnamed)'}" for d in self.declared]
80
+ lines += [str(d) for d in self.diagnostics]
81
+ return "\n".join(lines) or "(nothing declared)"
82
+
83
+
84
+ @dataclass
85
+ class Verdict:
86
+ target: str
87
+ verdict: str
88
+ why: str | None = None
89
+
90
+ def __bool__(self) -> bool:
91
+ return self.verdict == "satisfied"
92
+
93
+ def __repr__(self) -> str:
94
+ return f"{self.target}: {self.verdict}" + (f" ({self.why})" if self.why else "")
95
+
96
+
97
+ class Model:
98
+ """The model of a workspace: `directory`'s (the nearest directory upward with a `sysmantic.toml`, else `directory` itself)."""
99
+
100
+ def __init__(self, directory: str | os.PathLike[str] | None = None, *, documents: str | None = None):
101
+ self.server = Server(directory)
102
+ # Where held documents are put, as if files: under `documents` (relative to the workspace's root).
103
+ self._documents = documents
104
+ self._held: dict[str, str] = {}
105
+
106
+ # ---- Asking ----
107
+
108
+ def query(self, sparql: str, *, entailment: bool = True) -> Any:
109
+ """SPARQL: a SELECT as a table (a pandas DataFrame, if pandas is installed; else a list of dicts), an ASK as a bool,
110
+ a CONSTRUCT or DESCRIBE as N-Triples. The prefixes kerml:, sysml:, eval:, rdf:, rdfs:, owl: and xsd: need no declaring."""
111
+ params = {"query": sparql}
112
+ if not entailment:
113
+ params["entailment"] = "none"
114
+ text = self.server.request("/query", params, raw=True, accept="application/sparql-results+json, application/n-triples;q=0.9")
115
+ if text.lstrip().startswith("{"):
116
+ import json
117
+
118
+ answer = json.loads(text)
119
+ if "boolean" in answer:
120
+ return answer["boolean"]
121
+ return table(answer)
122
+ return text
123
+
124
+ def triples(self, sparql: str) -> str:
125
+ """A CONSTRUCT's answer, as N-Triples (no entailment)."""
126
+ return self.server.request("/query", {"query": sparql, "entailment": "none"}, raw=True, accept="application/n-triples")
127
+
128
+ def evaluate(self, target: str, *, context: str | Iterable[str] | None = None, unit: str | None = None) -> Any:
129
+ """A value: of an element (`Rover::rover.mass`) or an expression (`Rover::rover.mass * 9.81`), in `unit` if given.
130
+ A number comes back as a Quantity (a float with its unit); a boolean as a bool; anything else as its text."""
131
+ params: list[tuple[str, str]] = [("target", target)]
132
+ params += [("context", c) for c in ([context] if isinstance(context, str) else context or [])]
133
+ if unit:
134
+ params.append(("unit", unit))
135
+ answer = self.server.request("/evaluate", params)
136
+ if answer.get("error"):
137
+ raise SysmanticError(f"cannot evaluate `{target}`: {answer['error']}")
138
+ if answer.get("number") is not None:
139
+ return Quantity(answer["number"], answer.get("unit"), answer.get("text"))
140
+ if answer.get("boolean") is not None:
141
+ return answer["boolean"]
142
+ return answer.get("text")
143
+
144
+ def verify(self, target: str) -> Verdict:
145
+ """Whether a requirement, constraint or `satisfy` holds: satisfied, violated or undetermined, and why."""
146
+ answer = self.server.request("/verify", {"target": target})
147
+ if answer.get("error"):
148
+ raise SysmanticError(f"cannot verify `{target}`: {answer['error']}")
149
+ return Verdict(target, answer["verdict"], answer.get("why"))
150
+
151
+ def check(self) -> list[tuple[str, Diagnostic]]:
152
+ """The model's problems, by file."""
153
+ answer = self.server.request("/check")
154
+ return [(f["file"], Diagnostic(d["line"], d["column"], d["severity"], d["message"])) for f in answer["files"] for d in f["diagnostics"]]
155
+
156
+ # ---- Adding SysML ----
157
+
158
+ def _path(self, name: str) -> str:
159
+ base = self._documents or "notebook.ipynb"
160
+ return f"{base}/{name}.sysml"
161
+
162
+ def sysml(self, text: str, name: str = "cell") -> Document:
163
+ """Holds SysML in the model, as `name` (replacing what was held as it): it is part of the model as a file is,
164
+ though none is written. Returns what it declares, and its problems."""
165
+ self.server.url # Connect first: the workspace's root places the document.
166
+ path = self._path(name)
167
+ answer = self.server.request("/documents", body={"set": {path: text}})
168
+ self._held[name] = text
169
+ return document(name, text, answer["files"][0])
170
+
171
+ def drop(self, name: str | None = None) -> None:
172
+ """Drops what `sysml` held as `name`; with no name, all of it."""
173
+ if name is None:
174
+ self.server.request("/documents", body={"clear": self._documents or "notebook.ipynb"})
175
+ self._held.clear()
176
+ else:
177
+ self.server.request("/documents", body={"remove": [self._path(name)]})
178
+ self._held.pop(name, None)
179
+
180
+ # ---- Views ----
181
+
182
+ def view(self, element: str, kind: str = "default", *, highlight: Iterable[str] = (), note: str | None = None,
183
+ style: str | None = None, height: int | None = None, fade: bool = False) -> "View":
184
+ """One of the standard views of an element (`general`, `interconnection`, `action-flow`, `state-transition`,
185
+ `sequence`, `grid`, `geometry`; `default` picks by the element), drawn where the notebook shows outputs.
186
+ `highlight` outlines elements (and, with `fade`, the rest steps back), `note` says what to see,
187
+ `style` is CSS for this view alone."""
188
+ from .display import View
189
+
190
+ name = kind.lower().replace("_", "-")
191
+ return View(self, PILOT_VIEWS.get(name, name), element, list(highlight), note, style, height, fade)
192
+
193
+
194
+ def document(name: str, text: str, answer: dict[str, Any]) -> Document:
195
+ return Document(
196
+ name,
197
+ text,
198
+ [Declared(d["keyword"], d.get("name"), d["iri"], d.get("members", 0)) for d in answer.get("declared", [])],
199
+ [Diagnostic(d["line"], d["column"], d["severity"], d["message"]) for d in answer.get("diagnostics", [])],
200
+ )
201
+
202
+
203
+ XSD = "http://www.w3.org/2001/XMLSchema#"
204
+ NUMBERS = {f"{XSD}{t}" for t in ("double", "float", "decimal")}
205
+ INTEGERS = {f"{XSD}{t}" for t in ("integer", "int", "long", "short", "nonNegativeInteger", "positiveInteger")}
206
+
207
+
208
+ def value(term: dict[str, str] | None) -> Any:
209
+ """A SPARQL result's term as Python: numbers as numbers, booleans as bools, IRIs and text as strings."""
210
+ if term is None:
211
+ return None
212
+ v, datatype = term["value"], term.get("datatype")
213
+ try:
214
+ if datatype in NUMBERS:
215
+ return float(v)
216
+ if datatype in INTEGERS:
217
+ return int(v)
218
+ except ValueError:
219
+ return v
220
+ if datatype == f"{XSD}boolean":
221
+ return v == "true"
222
+ return v
223
+
224
+
225
+ def table(answer: dict[str, Any]) -> Any:
226
+ columns = answer["head"]["vars"]
227
+ rows = [{c: value(b.get(c)) for c in columns} for b in answer["results"]["bindings"]]
228
+ try:
229
+ import pandas
230
+ except ImportError:
231
+ return rows
232
+ return pandas.DataFrame(rows, columns=columns)
Binary file
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.5
2
+ Name: sysmantic
3
+ Version: 0.3.0
4
+ Summary: SysML v2 models in Python and Jupyter notebooks: SysML cells, SPARQL as tables, values, verdicts, and the standard views
5
+ Project-URL: Homepage, https://www.modelware.io
6
+ Project-URL: Documentation, https://github.com/modelware/sysmantic/blob/main/MANUAL.md#work-in-a-notebook
7
+ Project-URL: Releases, https://github.com/modelware/sysmantic/releases
8
+ Author-email: Modelware <info@modelware.io>
9
+ License: Proprietary: see LICENSE.md
10
+ Keywords: Jupyter,KerML,MBSE,SysML,SysML v2,systems engineering
11
+ Classifier: Framework :: IPython
12
+ Classifier: Framework :: Jupyter
13
+ Classifier: License :: Other/Proprietary License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering
16
+ Requires-Python: >=3.9
17
+ Provides-Extra: notebook
18
+ Requires-Dist: ipython>=8; extra == 'notebook'
19
+ Requires-Dist: jinja2>=3; extra == 'notebook'
20
+ Requires-Dist: matplotlib>=3.6; extra == 'notebook'
21
+ Requires-Dist: pandas>=1.5; extra == 'notebook'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Sysmantic for Python
25
+
26
+ Work with SysML v2 models from Python scripts and Jupyter notebooks: query them into tables,
27
+ compute values and verdicts, try design variants as SysML, and draw the standard views in a
28
+ notebook.
29
+
30
+ ```sh
31
+ pip install sysmantic # scripts
32
+ pip install "sysmantic[notebook]" # notebooks too
33
+ ```
34
+
35
+ It uses the `sysmantic` command, which you install once:
36
+
37
+ ```sh
38
+ curl -fsSL https://github.com/modelware/sysmantic/releases/latest/download/install.sh | sh
39
+ ```
40
+
41
+ (On Windows: `powershell -c "irm https://github.com/modelware/sysmantic/releases/latest/download/install.ps1 | iex"`.
42
+ With the Sysmantic extension for VS Code, the one it includes works too.) Use the same version of
43
+ both.
44
+
45
+ In a script:
46
+
47
+ ```python
48
+ from sysmantic import Model
49
+
50
+ m = Model("path/to/model")
51
+ m.evaluate("Rover::rover.mass", unit="kg") # 1900.0 kg
52
+ m.verify("Rover::massLimit") # satisfied, violated or undetermined, and why
53
+ m.query("SELECT ?p WHERE { ?p a sysml:Part }") # a table
54
+ ```
55
+
56
+ In a notebook:
57
+
58
+ ```python
59
+ import sysmantic
60
+ ```
61
+
62
+ ```
63
+ %%sysml
64
+ package Trade { private import Rover::*; part light :> rover { /* … */ } }
65
+ ```
66
+
67
+ ```
68
+ %viz --view=interconnection Rover::rover
69
+ ```
70
+
71
+ See *Work in a notebook* in the [manual](https://github.com/modelware/sysmantic/blob/main/MANUAL.md#work-in-a-notebook).
72
+
73
+ Proprietary, free to use directly, by individuals and organizations: see
74
+ [LICENSE.md](https://github.com/modelware/sysmantic/blob/main/LICENSE.md). Other commercial use:
75
+ info@modelware.io.
@@ -0,0 +1,10 @@
1
+ sysmantic/__init__.py,sha256=zsASZsj1Myeu5sI3tuEO-ul3ieU1xWsrsQSYMgvpyvg,2392
2
+ sysmantic/client.py,sha256=aY5cC9kkmI9MR9AvBjavsm7csmzH8C66MJvhlfVLqEI,4697
3
+ sysmantic/display.py,sha256=y5F1xyig5ZaUZ1ug_whh8ExLNDguYuzV8aQZkTF32xo,8036
4
+ sysmantic/magics.py,sha256=oZnW7IklJvmMRibjHIVN6Qqb5vxWoCIBnN1hj_qwiaI,6955
5
+ sysmantic/model.py,sha256=P-xQ6o6G4c5BymBiia3I0Kvk8F4S3LfKW9qYzlj1hHg,9036
6
+ sysmantic/static/views.js.gz,sha256=3Sl56OSXejNysmKwygRtxh3uaxQCExFWERqFrRSzoz0,642437
7
+ sysmantic/LICENSE.md,sha256=W-DHKACjxZ7kB7e82TYIdcqW8Huz1r5hq1b2sv6tAEk,3970
8
+ sysmantic-0.3.0.dist-info/METADATA,sha256=DHKHiZdZRts1VQo3xDdbnvaCGvqZVwbTV9EMAToqPnY,2554
9
+ sysmantic-0.3.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ sysmantic-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any