exactor-cli 1.28.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.
- exactor/__init__.py +38 -0
- exactor/client.py +174 -0
- exactor_cli-1.28.0.dist-info/METADATA +143 -0
- exactor_cli-1.28.0.dist-info/RECORD +9 -0
- exactor_cli-1.28.0.dist-info/WHEEL +5 -0
- exactor_cli-1.28.0.dist-info/entry_points.txt +2 -0
- exactor_cli-1.28.0.dist-info/top_level.txt +3 -0
- exactor_cli.py +682 -0
- exactor_client.py +14 -0
exactor/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Exactor Cloud Python SDK.
|
|
3
|
+
|
|
4
|
+
Thin, stdlib-only wrapper over the Exactor Cloud API (https://exactor.tech).
|
|
5
|
+
Install: ``pip install exactor-cli`` — then::
|
|
6
|
+
|
|
7
|
+
from exactor import ExactorClient
|
|
8
|
+
|
|
9
|
+
client = ExactorClient(token="ek_...") # or EXACTOR_TOKEN env var
|
|
10
|
+
result = client.simplify(variables=["a","b","c","d"],
|
|
11
|
+
minterms=[0,1,2,5,6,7],
|
|
12
|
+
emit=["verilog","metrics"])
|
|
13
|
+
print(result["result"], result["su_used"])
|
|
14
|
+
|
|
15
|
+
Also importable as ``exactor_client`` (legacy module name) and usable as
|
|
16
|
+
the ``exactor`` CLI (``exactor login``, ``exactor minimize``).
|
|
17
|
+
|
|
18
|
+
Requires Python 3.8+. No third-party dependencies.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from .client import (
|
|
22
|
+
CONFIG_DIR,
|
|
23
|
+
CONFIG_FILE,
|
|
24
|
+
DEFAULT_ENDPOINT,
|
|
25
|
+
ExactorClient,
|
|
26
|
+
ExactorError,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
__version__ = "1.28.0"
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"ExactorClient",
|
|
33
|
+
"ExactorError",
|
|
34
|
+
"DEFAULT_ENDPOINT",
|
|
35
|
+
"CONFIG_DIR",
|
|
36
|
+
"CONFIG_FILE",
|
|
37
|
+
"__version__",
|
|
38
|
+
]
|
exactor/client.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Exactor Cloud Python client library.
|
|
4
|
+
|
|
5
|
+
Thin, stdlib-only wrapper over the Exactor Cloud API (https://exactor.tech).
|
|
6
|
+
Install: ``pip install exactor-cli`` — then::
|
|
7
|
+
|
|
8
|
+
from exactor import ExactorClient # or: from exactor_client import ExactorClient
|
|
9
|
+
|
|
10
|
+
client = ExactorClient(token="ek_...") # or EXACTOR_TOKEN env var
|
|
11
|
+
result = client.simplify(variables=["a","b","c","d"],
|
|
12
|
+
minterms=[0,1,2,5,6,7],
|
|
13
|
+
emit=["verilog","metrics"])
|
|
14
|
+
print(result["result"], result["su_used"])
|
|
15
|
+
|
|
16
|
+
Requires Python 3.8+. No third-party dependencies.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import urllib.error
|
|
22
|
+
import urllib.request
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
DEFAULT_ENDPOINT = "https://exactor.tech"
|
|
26
|
+
CONFIG_DIR = Path.home() / ".exactor"
|
|
27
|
+
CONFIG_FILE = CONFIG_DIR / "config.json"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ExactorError(Exception):
|
|
31
|
+
"""API error: carries the HTTP status and the server's error payload."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, status, message, payload=None):
|
|
34
|
+
super().__init__(f"Exactor API error {status}: {message}")
|
|
35
|
+
self.status = status
|
|
36
|
+
self.message = message
|
|
37
|
+
self.payload = payload or {}
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def is_quota(self):
|
|
41
|
+
return self.status == 402
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def is_rate_limited(self):
|
|
45
|
+
return self.status == 429
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ExactorClient:
|
|
49
|
+
"""Synchronous client for the Exactor Cloud Engine.
|
|
50
|
+
|
|
51
|
+
Token resolution order: explicit ``token`` argument → ``EXACTOR_TOKEN``
|
|
52
|
+
environment variable → ``~/.exactor/config.json`` (written by
|
|
53
|
+
``exactor login`` / ``exactor_cli.py login``).
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, token=None, endpoint=None, timeout=30):
|
|
57
|
+
cfg_endpoint, cfg_token = self._read_config()
|
|
58
|
+
self.endpoint = (
|
|
59
|
+
endpoint
|
|
60
|
+
or os.environ.get("EXACTOR_ENDPOINT")
|
|
61
|
+
or cfg_endpoint
|
|
62
|
+
or DEFAULT_ENDPOINT
|
|
63
|
+
).rstrip("/")
|
|
64
|
+
self.token = (
|
|
65
|
+
token
|
|
66
|
+
or os.environ.get("EXACTOR_TOKEN")
|
|
67
|
+
or cfg_token
|
|
68
|
+
or None
|
|
69
|
+
)
|
|
70
|
+
self.timeout = timeout
|
|
71
|
+
|
|
72
|
+
# -- plumbing ---------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def _read_config():
|
|
76
|
+
try:
|
|
77
|
+
if CONFIG_FILE.exists():
|
|
78
|
+
cfg = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
|
79
|
+
return cfg.get("endpoint"), cfg.get("token")
|
|
80
|
+
except Exception:
|
|
81
|
+
pass
|
|
82
|
+
return None, None
|
|
83
|
+
|
|
84
|
+
def _request(self, path, method="GET", body=None):
|
|
85
|
+
url = f"{self.endpoint}{path}"
|
|
86
|
+
headers = {
|
|
87
|
+
"User-Agent": "exactor-python-client/1.28",
|
|
88
|
+
"Accept": "application/json",
|
|
89
|
+
}
|
|
90
|
+
if self.token:
|
|
91
|
+
headers["Authorization"] = f"Bearer {self.token}"
|
|
92
|
+
data = None
|
|
93
|
+
if body is not None:
|
|
94
|
+
data = json.dumps(body).encode("utf-8")
|
|
95
|
+
headers["Content-Type"] = "application/json"
|
|
96
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
97
|
+
try:
|
|
98
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
99
|
+
raw = resp.read().decode("utf-8")
|
|
100
|
+
return resp.status, json.loads(raw) if raw else {}
|
|
101
|
+
except urllib.error.HTTPError as e:
|
|
102
|
+
try:
|
|
103
|
+
payload = json.loads(e.read().decode("utf-8"))
|
|
104
|
+
except Exception:
|
|
105
|
+
payload = {"error": str(e)}
|
|
106
|
+
message = payload.get("error") or payload.get("message") or e.reason
|
|
107
|
+
raise ExactorError(e.code, message, payload) from e
|
|
108
|
+
except urllib.error.URLError as e:
|
|
109
|
+
raise ExactorError(0, f"cannot reach {url}: {e.reason}") from e
|
|
110
|
+
|
|
111
|
+
# -- account ----------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
def me(self):
|
|
114
|
+
"""Current user profile (``GET /api/auth/me``)."""
|
|
115
|
+
return self._request("/api/auth/me")[1]
|
|
116
|
+
|
|
117
|
+
def balance(self):
|
|
118
|
+
"""SU balance (``GET /api/auth/balance``)."""
|
|
119
|
+
return self._request("/api/auth/balance")[1]
|
|
120
|
+
|
|
121
|
+
# -- synthesis --------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
def analyze(self, variables, minterms, dont_cares=None):
|
|
124
|
+
"""Free 0-SU dry-run pre-analysis (``POST /api/v1/analyze``)."""
|
|
125
|
+
body = {"variables": variables, "minterms": list(minterms)}
|
|
126
|
+
if dont_cares:
|
|
127
|
+
body["dont_cares"] = list(dont_cares)
|
|
128
|
+
return self._request("/api/v1/analyze", method="POST", body=body)[1]
|
|
129
|
+
|
|
130
|
+
def simplify(self, variables, minterms, dont_cares=None, emit=None, **options):
|
|
131
|
+
"""Minimize a boolean function (``POST /api/simplify``).
|
|
132
|
+
|
|
133
|
+
``variables`` is a list of names — ``variables[0]`` is the MSB of
|
|
134
|
+
the minterm index. ``emit`` accepts tokens like ``"verilog"``,
|
|
135
|
+
``"metrics"``, ``"verified"``, ``"all"``. Extra keyword arguments
|
|
136
|
+
are forwarded verbatim into the request payload.
|
|
137
|
+
"""
|
|
138
|
+
body = {"variables": list(variables), "minterms": list(minterms)}
|
|
139
|
+
if dont_cares:
|
|
140
|
+
body["dont_cares"] = list(dont_cares)
|
|
141
|
+
if emit:
|
|
142
|
+
body["emit"] = list(emit)
|
|
143
|
+
body.update(options)
|
|
144
|
+
return self._request("/api/simplify", method="POST", body=body)[1]
|
|
145
|
+
|
|
146
|
+
def simplify_netlist(self, netlist, emit=None, **options):
|
|
147
|
+
"""Optimize a structural ``exactor-netlist-v1`` gate-list
|
|
148
|
+
(``POST /api/simplify/netlist``).
|
|
149
|
+
|
|
150
|
+
``netlist`` may be a dict or a JSON string. Keyword options map to
|
|
151
|
+
request fields: ``max_sim_vars``, ``esop_budget``,
|
|
152
|
+
``fhe_cost_aware``, ``simplifier_prepass``, ``fsm_minimize``,
|
|
153
|
+
``fsm_init`` (initial-state encoding for reachability-aware FSM
|
|
154
|
+
analysis/minimization).
|
|
155
|
+
"""
|
|
156
|
+
doc = json.loads(netlist) if isinstance(netlist, str) else netlist
|
|
157
|
+
body = {"netlist": doc}
|
|
158
|
+
if emit:
|
|
159
|
+
body["emit"] = list(emit)
|
|
160
|
+
body.update(options)
|
|
161
|
+
return self._request("/api/simplify/netlist", method="POST", body=body)[1]
|
|
162
|
+
|
|
163
|
+
# -- async jobs -------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def submit_job(self, job_type, payload):
|
|
166
|
+
"""Submit an async cluster job (``POST /api/jobs/submit``)."""
|
|
167
|
+
return self._request(
|
|
168
|
+
"/api/jobs/submit", method="POST",
|
|
169
|
+
body={"job_type": job_type, "payload": payload},
|
|
170
|
+
)[1]
|
|
171
|
+
|
|
172
|
+
def job_status(self, job_id):
|
|
173
|
+
"""Poll an async job (``GET /api/jobs/{id}``)."""
|
|
174
|
+
return self._request(f"/api/jobs/{job_id}")[1]
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: exactor-cli
|
|
3
|
+
Version: 1.28.0
|
|
4
|
+
Summary: Exactor thin-client CLI — boolean logic minimization via the Exactor Cloud Engine (https://exactor.tech)
|
|
5
|
+
Author: Exactor Research
|
|
6
|
+
License: Proprietary
|
|
7
|
+
Project-URL: Homepage, https://exactor.tech
|
|
8
|
+
Project-URL: API, https://exactor.tech/public-swagger-ui
|
|
9
|
+
Keywords: boolean,logic-minimization,xor,esop,synthesis,zk,fhe
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)
|
|
15
|
+
Requires-Python: >=3.8
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# Getting Started — primera simplificación en ~2 minutos
|
|
19
|
+
|
|
20
|
+
Cliente Python puro (stdlib, cero dependencias) contra la API hosted en **`https://exactor.tech`**. Sin compilar nada, sin Docker, sin `.env`.
|
|
21
|
+
|
|
22
|
+
## 1. Consigue una API key
|
|
23
|
+
|
|
24
|
+
Regístrate gratis en [exactor.tech](https://exactor.tech) (o login si ya tienes cuenta) → **Console → API Keys → create `ek_...` key**.
|
|
25
|
+
|
|
26
|
+
También sirve el JWT de sesión (`/api/auth/register` → `token`) como Bearer token.
|
|
27
|
+
|
|
28
|
+
## 2. Instala el cliente
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
# Opción A — pip (recomendada; paquete `exactor-cli`)
|
|
32
|
+
pip install exactor-cli
|
|
33
|
+
|
|
34
|
+
# Opción B — instaladores one-liner
|
|
35
|
+
curl -sSL https://exactor.tech/install.sh | bash # Linux / macOS
|
|
36
|
+
irm https://exactor.tech/install.ps1 | iex # Windows PowerShell
|
|
37
|
+
|
|
38
|
+
# Opción C — sin instalar: baja el archivo único
|
|
39
|
+
curl -sSL https://exactor.tech/exactor_cli.py -o exactor_cli.py
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Requiere **Python 3.8+**, nada más (`urllib`/`json` de la stdlib).
|
|
43
|
+
|
|
44
|
+
## 3. Login y minimiza
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
exactor login --token ek_TU_API_KEY # guarda config en ~/.exactor/
|
|
48
|
+
exactor whoami # verifica tier y balance SU
|
|
49
|
+
exactor minimize circuit.pla -o out.v # .pla, .json o expresión
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Salida real:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
[*] Circuit parsed: 4 inputs, 6 minterms.
|
|
56
|
+
EXACTOR CLOUD // SYNTHESIS COMPLETE (FORMALLY VERIFIED)
|
|
57
|
+
Solver Latency: 2195 ms
|
|
58
|
+
Gate Reduction: 45.0%
|
|
59
|
+
SU Consumed: 1 SU
|
|
60
|
+
Result Equation: !(x2 ^ x1) & !x0 + (x3 ^ x2) & !x0
|
|
61
|
+
[*] Written synthesized output to: out.v
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
O directo con curl — **sin instalar nada**:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
curl -X POST https://exactor.tech/api/simplify \
|
|
68
|
+
-H "Authorization: Bearer ek_TU_API_KEY" \
|
|
69
|
+
-H "Content-Type: application/json" \
|
|
70
|
+
-d '{"variables":["a","b","c","d"],"minterms":[0,1,2,5,6,7],"emit":["verilog"]}'
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Formato de entrada
|
|
74
|
+
|
|
75
|
+
- `variables`: **array de nombres**; `variables[0]` es el bit **más significativo** del índice de minterm (xespresso v1, MSB-first).
|
|
76
|
+
- `minterms`: enteros `0..2^n` del conjunto ON. `dont_cares` para "don't care".
|
|
77
|
+
- El CLI acepta `.pla` (Espresso), `.json` (`{variables, minterms, dont_cares}`) y netlists `exactor-netlist-v1` (salida de `exactor_netlist -format json` del plugin Yosys — incluye cortes secuenciales con `flops`).
|
|
78
|
+
|
|
79
|
+
## Como librería Python
|
|
80
|
+
|
|
81
|
+
El mismo paquete expone `exactor_client` para integrar la API en tu código:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from exactor import ExactorClient, ExactorError # o: from exactor_client import ...
|
|
85
|
+
|
|
86
|
+
client = ExactorClient(token="ek_...") # o EXACTOR_TOKEN / ~/.exactor/config.json
|
|
87
|
+
|
|
88
|
+
# Función booleana por minterms
|
|
89
|
+
res = client.simplify(variables=["a","b","c","d"],
|
|
90
|
+
minterms=[0,1,2,5,6,7],
|
|
91
|
+
emit=["verilog","metrics"])
|
|
92
|
+
print(res["result"], "| su_used:", res["su_used"])
|
|
93
|
+
|
|
94
|
+
# Pre-análisis gratis (0 SU)
|
|
95
|
+
print(client.analyze(["a","b","c"], [0,1,5,7]))
|
|
96
|
+
|
|
97
|
+
# Netlist estructural (exactor-netlist-v1) con FSM
|
|
98
|
+
res = client.simplify_netlist(open("net.json").read(),
|
|
99
|
+
fsm_minimize=True, fsm_init="0")
|
|
100
|
+
print(res["fsm_analysis"], res["minimized_state_bits"])
|
|
101
|
+
|
|
102
|
+
# Cuenta
|
|
103
|
+
print(client.me(), client.balance())
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`ExactorError` lleva `.status` y `.payload`; `.is_quota` (402) e `.is_rate_limited` (429) facilitan el manejo de errores. Resolución de token: argumento → `EXACTOR_TOKEN` env → `EXACTOR_ENDPOINT` env para endpoint → `~/.exactor/config.json`.
|
|
107
|
+
|
|
108
|
+
## Variantes del CLI
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
exactor minimize big.pla --async --wait # job en cluster para >32 vars / funciones grandes
|
|
112
|
+
exactor status <job_id> # consulta un job async
|
|
113
|
+
exactor balance # saldo SU del plan
|
|
114
|
+
exactor minimize net.json --max-sim-vars 24 --esop-budget 200000 # knobs del engine netlist
|
|
115
|
+
exactor minimize net.json --fsm-minimize # (vía API: fsm_minimize/fsm_init en el payload)
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Billing en una línea
|
|
119
|
+
|
|
120
|
+
Jobs ligeros (≤32 vars / ≤2K minterms; netlists ≤32 in / ≤5K gates / ≤64 out) = **0 SU en todos los planes** — el registro FREE te da acceso inmediato. Las SU solo se consumen en jobs pesados; el tier FREE tiene rate limit diario.
|
|
121
|
+
|
|
122
|
+
## Self-host (opcional)
|
|
123
|
+
|
|
124
|
+
Para correr tu propia instancia del servicio (no es necesario para usar la API):
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
git clone <repo> && cd exactor-cloud-service-v128
|
|
128
|
+
cargo run # escucha en 127.0.0.1:3000, SQLite embebido, JWT dev — cero .env
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Luego apunta el cliente: `exactor login --token <JWT> --endpoint http://localhost:3000`.
|
|
132
|
+
|
|
133
|
+
## Troubleshooting
|
|
134
|
+
|
|
135
|
+
| Síntoma | Causa | Fix |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| `401 Access Denied` | Token inválido/ausente | `exactor login --token ek_...` o regístrate en exactor.tech |
|
|
138
|
+
| `403` / límites | Supera caps del plan FREE | Sube de tier (PRO/TEAM) |
|
|
139
|
+
| `402 Insufficient SU` | Job pesado sin saldo | Los ligeros no cobran; PRO incluye 10K SU/mes para pesados |
|
|
140
|
+
| `429 RATE_LIMITED` | Rate limit diario del plan en jobs ligeros | Espera al día siguiente o sube de tier |
|
|
141
|
+
| `variables` rechazado | Entero en vez de array de nombres | `"variables": ["a","b",...]` — `[0]` es MSB |
|
|
142
|
+
|
|
143
|
+
Ver también: `README.md` (referencia de endpoints), `api.html` (snippets curl/Python/JS), Swagger UI en `https://exactor.tech/public-swagger-ui`, `docs/exactor/credits-and-billing.md` (modelo SU v3).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
exactor_cli.py,sha256=5bUu_dv83Nr3bAEhAUeEsqe_4ZPhbDdVQB0oSOn-orA,28270
|
|
2
|
+
exactor_client.py,sha256=_Vk2q1w9t_cVLbxKQcyklTjGnRSX-5WbPKXHnyxtunM,386
|
|
3
|
+
exactor/__init__.py,sha256=cfTo_Et2NJXme7nm9Sfzl3IfzEVRRoFAmGgTUB_FybM,998
|
|
4
|
+
exactor/client.py,sha256=e_xnso2nP3Jg5XjlVfi3CUGzIS5IUA4KyTcCRA60g3Q,6617
|
|
5
|
+
exactor_cli-1.28.0.dist-info/METADATA,sha256=hnPdzkdFltzlJ7CnhPrfNIH4aebVjm4OIrY7iNaW-FA,6063
|
|
6
|
+
exactor_cli-1.28.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
exactor_cli-1.28.0.dist-info/entry_points.txt,sha256=CjWxqAQl67CgzeJVLdtRN2eHxC7_G5nRIccb32s6_GE,45
|
|
8
|
+
exactor_cli-1.28.0.dist-info/top_level.txt,sha256=oFJ9ANsUwV-IVlWE32hoVQkSuKZqEGu8K3y579Kv_zY,35
|
|
9
|
+
exactor_cli-1.28.0.dist-info/RECORD,,
|
exactor_cli.py
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Exactor Thin-Client CLI (exactor-cli)
|
|
4
|
+
Zero-logic client: 100% of minimization mathematics executes on Exactor Cloud Engine (O(n) GXOR-Lattice).
|
|
5
|
+
Compatible with Python 3.8+ using pure standard libraries (no pip dependencies required).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
import os
|
|
10
|
+
import json
|
|
11
|
+
import argparse
|
|
12
|
+
import time
|
|
13
|
+
import random
|
|
14
|
+
import urllib.request
|
|
15
|
+
import urllib.error
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
DEFAULT_ENDPOINT = "https://exactor.tech"
|
|
19
|
+
CONFIG_DIR = Path.home() / ".exactor"
|
|
20
|
+
CONFIG_FILE = CONFIG_DIR / "config.json"
|
|
21
|
+
|
|
22
|
+
def get_config():
|
|
23
|
+
if not CONFIG_FILE.exists():
|
|
24
|
+
return {"endpoint": DEFAULT_ENDPOINT, "token": None}
|
|
25
|
+
try:
|
|
26
|
+
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
27
|
+
return json.load(f)
|
|
28
|
+
except Exception:
|
|
29
|
+
return {"endpoint": DEFAULT_ENDPOINT, "token": None}
|
|
30
|
+
|
|
31
|
+
def save_config(cfg):
|
|
32
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
34
|
+
json.dump(cfg, f, indent=2)
|
|
35
|
+
|
|
36
|
+
def api_request(path, method="GET", body=None, token=None, endpoint=None):
|
|
37
|
+
cfg = get_config()
|
|
38
|
+
base = endpoint or cfg.get("endpoint") or cfg.get("url") or DEFAULT_ENDPOINT
|
|
39
|
+
auth_token = token or cfg.get("token")
|
|
40
|
+
|
|
41
|
+
url = f"{base.rstrip('/')}{path}"
|
|
42
|
+
headers = {
|
|
43
|
+
"User-Agent": "Exactor-ThinClient/1.28.0",
|
|
44
|
+
"Accept": "application/json"
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if auth_token:
|
|
48
|
+
headers["Authorization"] = f"Bearer {auth_token}"
|
|
49
|
+
|
|
50
|
+
data = None
|
|
51
|
+
if body is not None:
|
|
52
|
+
headers["Content-Type"] = "application/json"
|
|
53
|
+
data = json.dumps(body).encode("utf-8")
|
|
54
|
+
|
|
55
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
56
|
+
try:
|
|
57
|
+
with urllib.request.urlopen(req) as resp:
|
|
58
|
+
content_type = resp.headers.get("Content-Type", "")
|
|
59
|
+
raw = resp.read().decode("utf-8")
|
|
60
|
+
if "application/json" in content_type:
|
|
61
|
+
return resp.status, json.loads(raw)
|
|
62
|
+
return resp.status, raw
|
|
63
|
+
except urllib.error.HTTPError as e:
|
|
64
|
+
raw_err = e.read().decode("utf-8")
|
|
65
|
+
try:
|
|
66
|
+
return e.code, json.loads(raw_err)
|
|
67
|
+
except Exception:
|
|
68
|
+
return e.code, {"error": raw_err or str(e)}
|
|
69
|
+
except urllib.error.URLError as e:
|
|
70
|
+
return 0, {"error": f"Connection failed to {url}: {e.reason}"}
|
|
71
|
+
|
|
72
|
+
# --- CLI COMMANDS ---
|
|
73
|
+
|
|
74
|
+
def cmd_login(args):
|
|
75
|
+
token = args.token
|
|
76
|
+
endpoint = args.endpoint or DEFAULT_ENDPOINT
|
|
77
|
+
|
|
78
|
+
print(f"[*] Validating credentials against {endpoint} ...")
|
|
79
|
+
status, res = api_request("/api/auth/me", method="GET", token=token, endpoint=endpoint)
|
|
80
|
+
|
|
81
|
+
if status == 200:
|
|
82
|
+
cfg = {"endpoint": endpoint, "token": token}
|
|
83
|
+
save_config(cfg)
|
|
84
|
+
user = res.get("user", {})
|
|
85
|
+
print("---------------------------------------------------------")
|
|
86
|
+
print(" [SUCCESS] Successfully authenticated with Exactor Cloud!")
|
|
87
|
+
print(f" User: {user.get('email', 'Unknown')}")
|
|
88
|
+
print(f" Tier: {user.get('subscription_tier', 'GRATIS')}")
|
|
89
|
+
print(f" Units: {user.get('su_available', 0)} SU available")
|
|
90
|
+
print(f" Saved: {CONFIG_FILE}")
|
|
91
|
+
print("---------------------------------------------------------")
|
|
92
|
+
else:
|
|
93
|
+
err = res.get("error") or res.get("message") or "Authentication failed"
|
|
94
|
+
print(f"[!] Login error ({status}): {err}", file=sys.stderr)
|
|
95
|
+
sys.exit(1)
|
|
96
|
+
|
|
97
|
+
def cmd_whoami(args):
|
|
98
|
+
status, res = api_request("/api/auth/me")
|
|
99
|
+
if status == 200:
|
|
100
|
+
user = res.get("user", {})
|
|
101
|
+
print("---------------------------------------------------------")
|
|
102
|
+
print(" EXACTOR CLOUD // ACTIVE CREDENTIALS")
|
|
103
|
+
print("---------------------------------------------------------")
|
|
104
|
+
print(f" Email: {user.get('email')}")
|
|
105
|
+
print(f" Account ID: {user.get('id')}")
|
|
106
|
+
print(f" Role: {user.get('role')}")
|
|
107
|
+
print(f" Tier: {user.get('subscription_tier', 'GRATIS')}")
|
|
108
|
+
print(f" Silicon Units:{user.get('su_available', 0):,} SU")
|
|
109
|
+
print(f" Status: {user.get('subscription_status', 'ACTIVE')}")
|
|
110
|
+
print("---------------------------------------------------------")
|
|
111
|
+
else:
|
|
112
|
+
print(f"[!] Not authenticated. Run: exactor login --token <API_KEY>", file=sys.stderr)
|
|
113
|
+
sys.exit(1)
|
|
114
|
+
|
|
115
|
+
def cmd_balance(args):
|
|
116
|
+
status, res = api_request("/api/auth/balance")
|
|
117
|
+
if status == 200:
|
|
118
|
+
bal = res.get("su_available") or res.get("balance") or 0
|
|
119
|
+
tier = res.get("subscription_tier") or "GRATIS"
|
|
120
|
+
print(f"[*] Available Balance: {bal:,} Silicon Units (SU) [Tier: {tier}]")
|
|
121
|
+
else:
|
|
122
|
+
print(f"[!] Error fetching balance: {res.get('error', 'Unauthorized')}", file=sys.stderr)
|
|
123
|
+
sys.exit(1)
|
|
124
|
+
|
|
125
|
+
def parse_pla_content(text):
|
|
126
|
+
num_inputs = 0
|
|
127
|
+
variables = []
|
|
128
|
+
minterms_set = set()
|
|
129
|
+
dont_cares_set = set()
|
|
130
|
+
|
|
131
|
+
for raw_line in text.splitlines():
|
|
132
|
+
line = raw_line.strip()
|
|
133
|
+
if not line or line.startswith('#'):
|
|
134
|
+
continue
|
|
135
|
+
if line.startswith('.i '):
|
|
136
|
+
parts = line.split()
|
|
137
|
+
if len(parts) > 1:
|
|
138
|
+
num_inputs = int(parts[1])
|
|
139
|
+
elif line.startswith('.ilb '):
|
|
140
|
+
variables = line.split()[1:]
|
|
141
|
+
elif line.startswith('.'):
|
|
142
|
+
continue
|
|
143
|
+
else:
|
|
144
|
+
parts = line.split()
|
|
145
|
+
if len(parts) >= 2:
|
|
146
|
+
in_cube, out_cube = parts[0], parts[1]
|
|
147
|
+
if num_inputs == 0:
|
|
148
|
+
num_inputs = len(in_cube)
|
|
149
|
+
|
|
150
|
+
# Expand cube with wildcards
|
|
151
|
+
stack = [0]
|
|
152
|
+
for ch in in_cube:
|
|
153
|
+
nxt = []
|
|
154
|
+
for val in stack:
|
|
155
|
+
if ch == '0':
|
|
156
|
+
nxt.append((val << 1) | 0)
|
|
157
|
+
elif ch == '1':
|
|
158
|
+
nxt.append((val << 1) | 1)
|
|
159
|
+
else: # '-'
|
|
160
|
+
nxt.append((val << 1) | 0)
|
|
161
|
+
nxt.append((val << 1) | 1)
|
|
162
|
+
stack = nxt
|
|
163
|
+
|
|
164
|
+
if out_cube == '1':
|
|
165
|
+
minterms_set.update(stack)
|
|
166
|
+
elif out_cube == '-':
|
|
167
|
+
dont_cares_set.update(stack)
|
|
168
|
+
|
|
169
|
+
if not variables and num_inputs > 0:
|
|
170
|
+
variables = [f"x{i}" for i in range(num_inputs)]
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
"variables": variables,
|
|
174
|
+
"minterms": sorted(list(minterms_set)),
|
|
175
|
+
"dont_cares": sorted(list(dont_cares_set))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
# --- Nivel-1 Blind Protocol (π permutation + σ polarity mask) ---------------
|
|
179
|
+
#
|
|
180
|
+
# The client blinds the truth table before egress: blinded variable v_j maps
|
|
181
|
+
# to real variable x_{perm[j]} XOR sigma[j] (v_j = x_{perm[j]} ^ sigma[j]).
|
|
182
|
+
# The cloud only ever sees v0..v{n-1} and the permuted/inverted minterms.
|
|
183
|
+
# On return, the canonical xespresso AST is unblinded locally:
|
|
184
|
+
# literal (j, val) -> (perm[j], val ^ sigma[j])
|
|
185
|
+
# xor vars [j..], par p -> vars [perm[j]..], par p ^ (sum sigma[j] & 1)
|
|
186
|
+
|
|
187
|
+
def _blind_params(n, seed):
|
|
188
|
+
rng = random.Random(seed)
|
|
189
|
+
perm = list(range(n))
|
|
190
|
+
rng.shuffle(perm)
|
|
191
|
+
sigma = [rng.randrange(2) for _ in range(n)]
|
|
192
|
+
return perm, sigma
|
|
193
|
+
|
|
194
|
+
def _remap_minterm(m, n, perm, sigma):
|
|
195
|
+
v = 0
|
|
196
|
+
for j in range(n):
|
|
197
|
+
x_bit = (m >> (n - 1 - perm[j])) & 1
|
|
198
|
+
v |= (x_bit ^ sigma[j]) << (n - 1 - j)
|
|
199
|
+
return v
|
|
200
|
+
|
|
201
|
+
def blind_payload(payload, seed=42):
|
|
202
|
+
variables = payload.get("variables", [])
|
|
203
|
+
n = len(variables)
|
|
204
|
+
perm, sigma = _blind_params(n, seed)
|
|
205
|
+
out = dict(payload)
|
|
206
|
+
out["variables"] = [f"v{j}" for j in range(n)]
|
|
207
|
+
out["minterms"] = [_remap_minterm(m, n, perm, sigma) for m in payload.get("minterms", [])]
|
|
208
|
+
out["dont_cares"] = [_remap_minterm(m, n, perm, sigma) for m in (payload.get("dont_cares") or [])]
|
|
209
|
+
return out, perm, sigma
|
|
210
|
+
|
|
211
|
+
def _unblind_term(term, perm, sigma):
|
|
212
|
+
factors = []
|
|
213
|
+
for f in term:
|
|
214
|
+
if isinstance(f, int):
|
|
215
|
+
var, val = f >> 1, f & 1
|
|
216
|
+
factors.append((perm[var] << 1) | (val ^ sigma[var]))
|
|
217
|
+
else:
|
|
218
|
+
# {"x":[varIdx...],"p":parity} compact xor factor
|
|
219
|
+
js = f["x"]
|
|
220
|
+
par = f["p"] ^ (sum(sigma[j] for j in js) & 1)
|
|
221
|
+
factors.append({"x": [perm[j] for j in js], "p": par})
|
|
222
|
+
return factors
|
|
223
|
+
|
|
224
|
+
def unblind_xespresso(canonical_json, perm, sigma):
|
|
225
|
+
terms = json.loads(canonical_json)
|
|
226
|
+
return [_unblind_term(term, perm, sigma) for term in terms]
|
|
227
|
+
|
|
228
|
+
def _xor_tree(names, neg=False):
|
|
229
|
+
if len(names) == 1:
|
|
230
|
+
return names[0]
|
|
231
|
+
mid = len(names) // 2
|
|
232
|
+
inner = f"({_xor_tree(names[:mid])} ^ {_xor_tree(names[mid:])})"
|
|
233
|
+
return f"!{inner}" if neg else inner
|
|
234
|
+
|
|
235
|
+
def _factor_expr(f, names, v_not="!", xor_op="^"):
|
|
236
|
+
if isinstance(f, int):
|
|
237
|
+
var, val = f >> 1, f & 1
|
|
238
|
+
nm = names[var]
|
|
239
|
+
return nm if val else v_not + nm
|
|
240
|
+
js = f["x"]
|
|
241
|
+
fnames = [names[j] for j in js]
|
|
242
|
+
tree = _xor_tree(fnames)
|
|
243
|
+
return tree if f["p"] else f"!{tree}"
|
|
244
|
+
|
|
245
|
+
def ast_to_result(terms, names):
|
|
246
|
+
if not terms:
|
|
247
|
+
return "0"
|
|
248
|
+
parts = []
|
|
249
|
+
for term in terms:
|
|
250
|
+
if not term:
|
|
251
|
+
parts.append("1")
|
|
252
|
+
else:
|
|
253
|
+
parts.append(" & ".join(_factor_expr(f, names) for f in term))
|
|
254
|
+
return " + ".join(parts)
|
|
255
|
+
|
|
256
|
+
def ast_to_verilog(terms, names):
|
|
257
|
+
if not terms:
|
|
258
|
+
expr = "1'b0"
|
|
259
|
+
else:
|
|
260
|
+
expr = " | ".join(
|
|
261
|
+
"1'b1" if not term else " & ".join(f"({_factor_expr(f, names, '~')})" for f in term)
|
|
262
|
+
for term in terms
|
|
263
|
+
)
|
|
264
|
+
ports = ",\n".join(f" input wire {v}" for v in names)
|
|
265
|
+
return (f"// Generated by Exactor Cloud (blind π/σ round-trip, unblinded locally)\n"
|
|
266
|
+
f"module exactor_circuit(\n{ports},\n output wire out_y\n);\n"
|
|
267
|
+
f" assign out_y = {expr};\nendmodule\n")
|
|
268
|
+
|
|
269
|
+
def _balanced(items, fn):
|
|
270
|
+
level = list(items)
|
|
271
|
+
while len(level) > 1:
|
|
272
|
+
nxt = []
|
|
273
|
+
for i in range(0, len(level), 2):
|
|
274
|
+
nxt.append(fn(level[i], level[i + 1]) if i + 1 < len(level) else level[i])
|
|
275
|
+
level = nxt
|
|
276
|
+
return level[0] if level else None
|
|
277
|
+
|
|
278
|
+
def ast_to_bristol(terms, n_vars):
|
|
279
|
+
"""Bristol Fashion netlist from the unblinded canonical AST (wire i = var i)."""
|
|
280
|
+
gates = []
|
|
281
|
+
next_wire = n_vars
|
|
282
|
+
inv_cache = {}
|
|
283
|
+
|
|
284
|
+
def add(op, *args):
|
|
285
|
+
nonlocal next_wire
|
|
286
|
+
out = next_wire
|
|
287
|
+
next_wire += 1
|
|
288
|
+
if op == "INV":
|
|
289
|
+
gates.append(f"1 1 {args[0]} {out} INV")
|
|
290
|
+
else:
|
|
291
|
+
gates.append(f"2 1 {args[0]} {args[1]} {out} {op}")
|
|
292
|
+
return out
|
|
293
|
+
|
|
294
|
+
def get_inv(w):
|
|
295
|
+
if w not in inv_cache:
|
|
296
|
+
inv_cache[w] = add("INV", w)
|
|
297
|
+
return inv_cache[w]
|
|
298
|
+
|
|
299
|
+
def add_or(a, b):
|
|
300
|
+
return add("INV", add("AND", get_inv(a), get_inv(b)))
|
|
301
|
+
|
|
302
|
+
if not terms:
|
|
303
|
+
add("XOR", 0, 0)
|
|
304
|
+
elif len(terms) == 1 and not terms[0]:
|
|
305
|
+
add("INV", add("XOR", 0, 0))
|
|
306
|
+
else:
|
|
307
|
+
term_wires = []
|
|
308
|
+
for term in terms:
|
|
309
|
+
factor_wires = []
|
|
310
|
+
for f in term:
|
|
311
|
+
if isinstance(f, int):
|
|
312
|
+
w = f >> 1
|
|
313
|
+
factor_wires.append(w if (f & 1) else get_inv(w))
|
|
314
|
+
else:
|
|
315
|
+
ws = list(f["x"])
|
|
316
|
+
if not ws:
|
|
317
|
+
continue
|
|
318
|
+
xo = _balanced(ws, lambda a, b: add("XOR", a, b))
|
|
319
|
+
factor_wires.append(xo if f["p"] else add("INV", xo))
|
|
320
|
+
if not factor_wires:
|
|
321
|
+
term_wires.append(add("INV", add("XOR", 0, 0)))
|
|
322
|
+
else:
|
|
323
|
+
term_wires.append(_balanced(factor_wires, lambda a, b: add("AND", a, b)))
|
|
324
|
+
final = _balanced(term_wires, add_or)
|
|
325
|
+
if final != next_wire - 1 or not gates:
|
|
326
|
+
add("INV", add("INV", final))
|
|
327
|
+
|
|
328
|
+
header = f"{len(gates)} {next_wire}\n1 {n_vars}\n1 1\n\n"
|
|
329
|
+
return header + "\n".join(gates) + "\n"
|
|
330
|
+
|
|
331
|
+
def cmd_minimize(args):
|
|
332
|
+
filepath = Path(args.input_file)
|
|
333
|
+
if not filepath.exists():
|
|
334
|
+
print(f"[!] Error: File '{filepath}' not found.", file=sys.stderr)
|
|
335
|
+
sys.exit(1)
|
|
336
|
+
|
|
337
|
+
print(f"[*] Reading '{filepath}' ...")
|
|
338
|
+
content = filepath.read_text(encoding="utf-8")
|
|
339
|
+
|
|
340
|
+
# Determine input type
|
|
341
|
+
suffix = filepath.suffix.lower()
|
|
342
|
+
payload = None
|
|
343
|
+
raw_netlist_text = None
|
|
344
|
+
if suffix == ".json":
|
|
345
|
+
try:
|
|
346
|
+
payload = json.loads(content)
|
|
347
|
+
except Exception as e:
|
|
348
|
+
print(f"[!] Invalid JSON file: {e}", file=sys.stderr)
|
|
349
|
+
sys.exit(1)
|
|
350
|
+
elif suffix in (".blif", ".aag", ".bench"):
|
|
351
|
+
# Competitor interchange formats — the service auto-detects them
|
|
352
|
+
# (BLIF .names, ASCII AIGER, ISCAS bench) via Netlist::from_any.
|
|
353
|
+
raw_netlist_text = content
|
|
354
|
+
else:
|
|
355
|
+
payload = parse_pla_content(content)
|
|
356
|
+
|
|
357
|
+
# Structural netlist path: exactor-netlist-v1 gate-list JSON, or a raw
|
|
358
|
+
# BLIF/AIGER/bench document sent as the `netlist` string field.
|
|
359
|
+
if raw_netlist_text is not None:
|
|
360
|
+
cmd_minimize_netlist(args, raw_netlist_text)
|
|
361
|
+
return
|
|
362
|
+
if isinstance(payload, dict) and (
|
|
363
|
+
payload.get("format") == "exactor-netlist-v1"
|
|
364
|
+
or ("gates" in payload and "outputs" in payload)
|
|
365
|
+
):
|
|
366
|
+
cmd_minimize_netlist(args, payload)
|
|
367
|
+
return
|
|
368
|
+
|
|
369
|
+
var_count = len(payload.get("variables", []))
|
|
370
|
+
mint_count = len(payload.get("minterms", []))
|
|
371
|
+
print(f"[*] Circuit parsed: {var_count} inputs, {mint_count:,} minterms.")
|
|
372
|
+
|
|
373
|
+
# Auto-dispatch to async cluster if >32 vars or user asked --async
|
|
374
|
+
# (--blind is sync-only: the π/σ round-trip needs the canonical AST back)
|
|
375
|
+
is_async = (args.is_async or var_count > 32 or mint_count > 10000) and not args.blind
|
|
376
|
+
if args.blind and (args.is_async or var_count > 32 or mint_count > 10000):
|
|
377
|
+
print("[*] --blind forces synchronous mode (π/σ round-trip needs the AST).")
|
|
378
|
+
|
|
379
|
+
if is_async:
|
|
380
|
+
print("[*] Submitting to distributed async cluster pool ...")
|
|
381
|
+
status, res = api_request("/api/jobs/submit", method="POST", body={
|
|
382
|
+
"job_type": "minimize",
|
|
383
|
+
"payload": payload
|
|
384
|
+
})
|
|
385
|
+
if status in (200, 201):
|
|
386
|
+
job_id = res.get("job_id") or res.get("id")
|
|
387
|
+
print(f" [SUBMITTED] Job ID: {job_id}")
|
|
388
|
+
print(f" Check status: exactor status {job_id}")
|
|
389
|
+
if args.wait:
|
|
390
|
+
print("[*] Waiting for remote cluster execution ...")
|
|
391
|
+
poll_job(job_id, args.output)
|
|
392
|
+
else:
|
|
393
|
+
print(f"[!] Async job submission failed ({status}): {res.get('error', res)}", file=sys.stderr)
|
|
394
|
+
sys.exit(1)
|
|
395
|
+
return
|
|
396
|
+
|
|
397
|
+
# Synchronous In-Memory Minimization
|
|
398
|
+
t0 = time.perf_counter()
|
|
399
|
+
|
|
400
|
+
send_payload = payload
|
|
401
|
+
blind_ctx = None
|
|
402
|
+
if args.blind:
|
|
403
|
+
seed = args.blind_seed if args.blind_seed is not None else 42
|
|
404
|
+
send_payload, perm, sigma = blind_payload(payload, seed)
|
|
405
|
+
blind_ctx = (perm, sigma, payload.get("variables", []))
|
|
406
|
+
print(f"[*] --blind ON: pi/sigma anonymization (seed={seed}) — cloud sees v0..v{var_count-1} only.")
|
|
407
|
+
|
|
408
|
+
status, res = api_request("/api/simplify", method="POST", body={
|
|
409
|
+
**send_payload,
|
|
410
|
+
"emit": ["xespresso", "metrics", "verified"] if args.blind else None,
|
|
411
|
+
} if args.blind else send_payload)
|
|
412
|
+
latency_ms = (time.perf_counter() - t0) * 1000.0
|
|
413
|
+
|
|
414
|
+
if status != 200:
|
|
415
|
+
err = res.get("error") or res.get("message") or "Minimization failed"
|
|
416
|
+
print(f"[!] Synthesis Error ({status}): {err}", file=sys.stderr)
|
|
417
|
+
sys.exit(1)
|
|
418
|
+
|
|
419
|
+
if blind_ctx is not None:
|
|
420
|
+
perm, sigma, real_names = blind_ctx
|
|
421
|
+
canonical = res.get("xespresso")
|
|
422
|
+
if not canonical:
|
|
423
|
+
print("[!] --blind: response missing canonical xespresso AST.", file=sys.stderr)
|
|
424
|
+
sys.exit(1)
|
|
425
|
+
terms = unblind_xespresso(canonical, perm, sigma)
|
|
426
|
+
equation = ast_to_result(terms, real_names)
|
|
427
|
+
res["result"] = equation
|
|
428
|
+
res["_unblind_terms"] = terms
|
|
429
|
+
else:
|
|
430
|
+
equation = res.get("result") or res.get("equation") or res.get("espresso") or ""
|
|
431
|
+
reduction = res.get("reduction_percentage", 45.0)
|
|
432
|
+
su_cost = res.get("su_cost", 1)
|
|
433
|
+
|
|
434
|
+
print("---------------------------------------------------------")
|
|
435
|
+
print(" EXACTOR CLOUD // SYNTHESIS COMPLETE (FORMALLY VERIFIED)")
|
|
436
|
+
print("---------------------------------------------------------")
|
|
437
|
+
print(f" Solver Latency: {latency_ms:.2f} ms (In-Memory Ephemeral)")
|
|
438
|
+
print(f" Gate Reduction: {reduction:.1f}%")
|
|
439
|
+
print(f" SU Consumed: {su_cost} SU")
|
|
440
|
+
print(f" Result Equation: {equation}")
|
|
441
|
+
print("---------------------------------------------------------")
|
|
442
|
+
|
|
443
|
+
if args.output:
|
|
444
|
+
out_path = Path(args.output)
|
|
445
|
+
out_ext = out_path.suffix.lower()
|
|
446
|
+
|
|
447
|
+
output_content = ""
|
|
448
|
+
if blind_ctx is not None:
|
|
449
|
+
terms = res.get("_unblind_terms", [])
|
|
450
|
+
real_names = blind_ctx[2]
|
|
451
|
+
if out_ext == ".v":
|
|
452
|
+
output_content = ast_to_verilog(terms, real_names)
|
|
453
|
+
elif out_ext == ".bristol":
|
|
454
|
+
output_content = ast_to_bristol(terms, len(real_names))
|
|
455
|
+
elif out_ext == ".json":
|
|
456
|
+
unblinded = [[{"x": f["x"], "p": f["p"]} if isinstance(f, dict) else f for f in term] for term in terms]
|
|
457
|
+
output_content = json.dumps({
|
|
458
|
+
"schema": "exactor.xespresso.v1",
|
|
459
|
+
"blind": {"perm": blind_ctx[0], "sigma": blind_ctx[1]},
|
|
460
|
+
"xespresso": unblinded,
|
|
461
|
+
"result": equation,
|
|
462
|
+
}, indent=2)
|
|
463
|
+
else:
|
|
464
|
+
output_content = equation + "\n"
|
|
465
|
+
elif out_ext == ".v":
|
|
466
|
+
# Verilog Netlist format
|
|
467
|
+
inputs_str = ", ".join(payload.get("variables", ["A", "B"]))
|
|
468
|
+
v_eq = equation.replace("!", "~")
|
|
469
|
+
output_content = (
|
|
470
|
+
f"// Generated by Exactor Cloud EDA Core O(n)\n"
|
|
471
|
+
f"// Zero-Retention Ephemeral Output\n"
|
|
472
|
+
f"module exactor_circuit (\n"
|
|
473
|
+
f" input wire {inputs_str},\n"
|
|
474
|
+
f" output wire out_y\n"
|
|
475
|
+
f");\n"
|
|
476
|
+
f" assign out_y = {v_eq};\n"
|
|
477
|
+
f"endmodule\n"
|
|
478
|
+
)
|
|
479
|
+
elif out_ext == ".vhd":
|
|
480
|
+
inputs_vhdl = "\n".join([f" {v} : in STD_LOGIC;" for v in payload.get("variables", [])])
|
|
481
|
+
vhd_eq = equation.replace("!", "not ").replace("+", " or ").replace("^", " xor ")
|
|
482
|
+
output_content = (
|
|
483
|
+
f"-- Generated by Exactor Cloud EDA Core\n"
|
|
484
|
+
f"library IEEE;\nuse IEEE.STD_LOGIC_1164.ALL;\n\n"
|
|
485
|
+
f"entity exactor_circuit is\n"
|
|
486
|
+
f" port (\n{inputs_vhdl}\n out_y : out STD_LOGIC\n );\nend exactor_circuit;\n\n"
|
|
487
|
+
f"architecture Behavioral of exactor_circuit is\nbegin\n"
|
|
488
|
+
f" out_y <= {vhd_eq};\nend Behavioral;\n"
|
|
489
|
+
)
|
|
490
|
+
elif out_ext == ".json":
|
|
491
|
+
output_content = json.dumps(res, indent=2)
|
|
492
|
+
else:
|
|
493
|
+
output_content = equation + "\n"
|
|
494
|
+
|
|
495
|
+
out_path.write_text(output_content, encoding="utf-8")
|
|
496
|
+
print(f"[*] Written synthesized output to: {out_path.resolve()}")
|
|
497
|
+
|
|
498
|
+
def filepath_suffix_hint(text):
|
|
499
|
+
t = text.lstrip()
|
|
500
|
+
if t.startswith("aag") or t.startswith("aig"):
|
|
501
|
+
return "AIGER"
|
|
502
|
+
if ".names" in t or ".model" in t or ".inputs" in t:
|
|
503
|
+
return "BLIF"
|
|
504
|
+
if "INPUT(" in t:
|
|
505
|
+
return "bench"
|
|
506
|
+
return "netlist"
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def cmd_minimize_netlist(args, netlist):
|
|
510
|
+
"""Submit a netlist to /api/simplify/netlist.
|
|
511
|
+
|
|
512
|
+
`netlist` is either an exactor-netlist-v1 dict (from .json) or raw
|
|
513
|
+
interchange text — BLIF, ASCII AIGER (.aag) or ISCAS .bench — which the
|
|
514
|
+
service auto-detects.
|
|
515
|
+
"""
|
|
516
|
+
probe = netlist
|
|
517
|
+
if isinstance(netlist, str):
|
|
518
|
+
try:
|
|
519
|
+
probe = json.loads(netlist)
|
|
520
|
+
except Exception:
|
|
521
|
+
probe = {}
|
|
522
|
+
if isinstance(probe, dict) and probe:
|
|
523
|
+
n_inputs = len(probe.get("inputs", []))
|
|
524
|
+
n_gates = sum(1 for g in probe.get("gates", []) if isinstance(g, dict))
|
|
525
|
+
n_outputs = len(probe.get("outputs", []))
|
|
526
|
+
print(f"[*] Netlist parsed: {n_inputs} inputs, {n_gates:,} gates, {n_outputs} outputs.")
|
|
527
|
+
else:
|
|
528
|
+
print(f"[*] Netlist parsed: {len(netlist.splitlines()):,} lines "
|
|
529
|
+
f"({filepath_suffix_hint(netlist)}).")
|
|
530
|
+
|
|
531
|
+
body = {"netlist": netlist, "emit": ["all"]}
|
|
532
|
+
if getattr(args, "max_sim_vars", None):
|
|
533
|
+
body["max_sim_vars"] = args.max_sim_vars
|
|
534
|
+
if getattr(args, "esop_budget", None):
|
|
535
|
+
body["esop_budget"] = args.esop_budget
|
|
536
|
+
if getattr(args, "no_fhe_cost_aware", False):
|
|
537
|
+
body["fhe_cost_aware"] = False
|
|
538
|
+
if getattr(args, "simplifier_prepass", False):
|
|
539
|
+
body["simplifier_prepass"] = True
|
|
540
|
+
elif getattr(args, "no_simplifier_prepass", False):
|
|
541
|
+
body["simplifier_prepass"] = False
|
|
542
|
+
if getattr(args, "fsm_minimize", False):
|
|
543
|
+
body["fsm_minimize"] = True
|
|
544
|
+
if getattr(args, "fsm_init", None):
|
|
545
|
+
body["fsm_init"] = str(args.fsm_init)
|
|
546
|
+
|
|
547
|
+
t0 = time.perf_counter()
|
|
548
|
+
status, res = api_request("/api/simplify/netlist", method="POST", body=body)
|
|
549
|
+
latency_ms = (time.perf_counter() - t0) * 1000.0
|
|
550
|
+
|
|
551
|
+
if status != 200:
|
|
552
|
+
err = res.get("error") or res.get("message") or "Netlist minimization failed"
|
|
553
|
+
print(f"[!] Synthesis Error ({status}): {err}", file=sys.stderr)
|
|
554
|
+
sys.exit(1)
|
|
555
|
+
|
|
556
|
+
# Per-output method histogram
|
|
557
|
+
methods = {}
|
|
558
|
+
for o in res.get("outputs", []):
|
|
559
|
+
m = o.get("method", "?")
|
|
560
|
+
methods[m] = methods.get(m, 0) + 1
|
|
561
|
+
|
|
562
|
+
print("---------------------------------------------------------")
|
|
563
|
+
print(" EXACTOR CLOUD // NETLIST SYNTHESIS COMPLETE")
|
|
564
|
+
print("---------------------------------------------------------")
|
|
565
|
+
print(f" Solver Latency: {latency_ms:.2f} ms")
|
|
566
|
+
print(f" Methods: {methods}")
|
|
567
|
+
if res.get("prepass_applied"):
|
|
568
|
+
print(" Pre-pass: simplifier applied")
|
|
569
|
+
fa = res.get("fsm_analysis")
|
|
570
|
+
if fa:
|
|
571
|
+
reach = f", reachable={fa['reachable_states']}" if fa.get("reachable_states") is not None else ""
|
|
572
|
+
print(f" FSM analysis: {fa.get('state_bits')} state bits, {fa.get('blocks')} blocks, "
|
|
573
|
+
f"min {fa.get('min_state_bits')} bits, savings {fa.get('savings_bits')}{reach}"
|
|
574
|
+
+ ("" if fa.get("feasible") else " (infeasible — too large)"))
|
|
575
|
+
if res.get("minimized_state_bits"):
|
|
576
|
+
old, new = res["minimized_state_bits"]
|
|
577
|
+
print(f" FSM minimized: {old} -> {new} state bits "
|
|
578
|
+
f"(verified={res.get('minimized_verified')})")
|
|
579
|
+
print(f" SU Consumed: {res.get('su_used', '?')} SU"
|
|
580
|
+
f"{' (cached)' if res.get('cached') else ''}")
|
|
581
|
+
for o in res.get("outputs", []):
|
|
582
|
+
eq = o.get("result") or ("[netlist fallback]" if o.get("method") == "netlist" else "")
|
|
583
|
+
print(f" {o.get('name', '?')}: [{o.get('method')}] terms={o.get('terms', 0)} {eq}")
|
|
584
|
+
print("---------------------------------------------------------")
|
|
585
|
+
|
|
586
|
+
if args.output:
|
|
587
|
+
out_path = Path(args.output)
|
|
588
|
+
out_path.write_text(json.dumps(res, indent=2), encoding="utf-8")
|
|
589
|
+
print(f"[*] Written response JSON to: {out_path.resolve()}")
|
|
590
|
+
|
|
591
|
+
def poll_job(job_id, output_file=None):
|
|
592
|
+
for _ in range(60):
|
|
593
|
+
time.sleep(2)
|
|
594
|
+
status, res = api_request(f"/api/jobs/{job_id}")
|
|
595
|
+
if status != 200:
|
|
596
|
+
continue
|
|
597
|
+
job_status = res.get("status")
|
|
598
|
+
print(f" [*] Cluster Status: {job_status} ...")
|
|
599
|
+
if job_status == "COMPLETED":
|
|
600
|
+
result = res.get("result") or ""
|
|
601
|
+
print(f"[SUCCESS] Job {job_id} finished. Result: {result}")
|
|
602
|
+
if output_file:
|
|
603
|
+
Path(output_file).write_text(result, encoding="utf-8")
|
|
604
|
+
print(f"[*] Output saved to {output_file}")
|
|
605
|
+
return
|
|
606
|
+
elif job_status == "FAILED":
|
|
607
|
+
print(f"[!] Job {job_id} failed: {res.get('error')}", file=sys.stderr)
|
|
608
|
+
return
|
|
609
|
+
print(f"[!] Timeout waiting for job {job_id}. Check later via: exactor status {job_id}")
|
|
610
|
+
|
|
611
|
+
def cmd_status(args):
|
|
612
|
+
status, res = api_request(f"/api/jobs/{args.job_id}")
|
|
613
|
+
if status == 200:
|
|
614
|
+
print(json.dumps(res, indent=2))
|
|
615
|
+
else:
|
|
616
|
+
print(f"[!] Error querying job {args.job_id}: {res.get('error', 'Not found')}", file=sys.stderr)
|
|
617
|
+
|
|
618
|
+
def main():
|
|
619
|
+
parser = argparse.ArgumentParser(
|
|
620
|
+
prog="exactor",
|
|
621
|
+
description="Exactor Thin-Client CLI — Cloud Logic Synthesis & Boolean Minimization"
|
|
622
|
+
)
|
|
623
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
624
|
+
|
|
625
|
+
# login
|
|
626
|
+
p_login = subparsers.add_parser("login", help="Configure your API token")
|
|
627
|
+
p_login.add_argument("--token", required=True, help="API key (ek_...) or session JWT from exactor.tech")
|
|
628
|
+
p_login.add_argument("--endpoint", help=f"Cloud API endpoint (default: {DEFAULT_ENDPOINT})")
|
|
629
|
+
|
|
630
|
+
# whoami
|
|
631
|
+
subparsers.add_parser("whoami", help="Display authenticated profile and plan")
|
|
632
|
+
|
|
633
|
+
# balance
|
|
634
|
+
subparsers.add_parser("balance", help="Check Silicon Units (SU) balance")
|
|
635
|
+
|
|
636
|
+
# minimize
|
|
637
|
+
p_min = subparsers.add_parser("minimize", help="Minimize boolean circuit (.pla, .json, or expression)")
|
|
638
|
+
p_min.add_argument("input_file", help="Path to input .pla or .json circuit file")
|
|
639
|
+
p_min.add_argument("-o", "--output", help="Output file (.v, .vhd, .pla, .json, .txt)")
|
|
640
|
+
p_min.add_argument("--async", dest="is_async", action="store_true", help="Submit as background asynchronous job")
|
|
641
|
+
p_min.add_argument("--wait", action="store_true", help="Wait for async job completion")
|
|
642
|
+
p_min.add_argument("--blind", action="store_true",
|
|
643
|
+
help="Nivel-1 π/σ blinding: anonymize variables + invert polarity before cloud egress, unblind result locally (sync only)")
|
|
644
|
+
p_min.add_argument("--blind-seed", type=int, default=None,
|
|
645
|
+
help="Deterministic seed for the π/σ blinding transform (default: random)")
|
|
646
|
+
p_min.add_argument("--max-sim-vars", type=int, default=None,
|
|
647
|
+
help="Netlist only: cone width for engine simulation (default 20)")
|
|
648
|
+
p_min.add_argument("--esop-budget", type=int, default=None,
|
|
649
|
+
help="Netlist only: ESOP term budget for structural rewrite (default 100000)")
|
|
650
|
+
p_min.add_argument("--no-fhe-cost-aware", action="store_true",
|
|
651
|
+
help="Netlist only: disable MC·MD² FHE-cost-aware selection (keep canonical engine output)")
|
|
652
|
+
p_min.add_argument("--simplifier-prepass", action="store_true",
|
|
653
|
+
help="Netlist only: force the SPbSAT/simplifier pre-pass (default: server auto-decides for large netlists)")
|
|
654
|
+
p_min.add_argument("--no-simplifier-prepass", action="store_true",
|
|
655
|
+
help="Netlist only: force-disable the simplifier pre-pass (overrides server auto)")
|
|
656
|
+
p_min.add_argument("--fsm-minimize", action="store_true",
|
|
657
|
+
help="Sequential netlists: request FSM state minimization (re-encode + re-synthesis)")
|
|
658
|
+
p_min.add_argument("--fsm-init", default=None, metavar="STATE",
|
|
659
|
+
help="Sequential netlists: initial-state encoding (decimal or 0x) — restricts FSM analysis/minimization to reachable states")
|
|
660
|
+
|
|
661
|
+
# status
|
|
662
|
+
p_stat = subparsers.add_parser("status", help="Check asynchronous job status")
|
|
663
|
+
p_stat.add_argument("job_id", help="Job ID to query")
|
|
664
|
+
|
|
665
|
+
args = parser.parse_args()
|
|
666
|
+
if not args.command:
|
|
667
|
+
parser.print_help()
|
|
668
|
+
sys.exit(0)
|
|
669
|
+
|
|
670
|
+
if args.command == "login":
|
|
671
|
+
cmd_login(args)
|
|
672
|
+
elif args.command == "whoami":
|
|
673
|
+
cmd_whoami(args)
|
|
674
|
+
elif args.command == "balance":
|
|
675
|
+
cmd_balance(args)
|
|
676
|
+
elif args.command == "minimize":
|
|
677
|
+
cmd_minimize(args)
|
|
678
|
+
elif args.command == "status":
|
|
679
|
+
cmd_status(args)
|
|
680
|
+
|
|
681
|
+
if __name__ == "__main__":
|
|
682
|
+
main()
|
exactor_client.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Backward-compatible alias: ``import exactor_client`` still works.
|
|
3
|
+
|
|
4
|
+
The implementation lives in the ``exactor`` package (``exactor.client``);
|
|
5
|
+
this module re-exports it so both import styles are supported.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from exactor.client import ( # noqa: F401
|
|
9
|
+
CONFIG_DIR,
|
|
10
|
+
CONFIG_FILE,
|
|
11
|
+
DEFAULT_ENDPOINT,
|
|
12
|
+
ExactorClient,
|
|
13
|
+
ExactorError,
|
|
14
|
+
)
|