fuzzybits-server 0.17.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.
- fuzzybits_server/.dockerignore +64 -0
- fuzzybits_server/__init__.py +15 -0
- fuzzybits_server/app.py +93 -0
- fuzzybits_server/config.py +310 -0
- fuzzybits_server/convergence/__init__.py +100 -0
- fuzzybits_server/convergence/gbas.py +229 -0
- fuzzybits_server/convergence/metrics.py +164 -0
- fuzzybits_server/convergence/policies.py +387 -0
- fuzzybits_server/convergence/runner.py +398 -0
- fuzzybits_server/convergence/sampling.py +409 -0
- fuzzybits_server/convergence/special.py +280 -0
- fuzzybits_server/convergence/tally.py +179 -0
- fuzzybits_server/event_hub.py +58 -0
- fuzzybits_server/event_log.py +16 -0
- fuzzybits_server/fault_tree_payload.py +899 -0
- fuzzybits_server/model_oracle_p.json +44 -0
- fuzzybits_server/native.py +536 -0
- fuzzybits_server/routes.py +408 -0
- fuzzybits_server/state.py +67 -0
- fuzzybits_server/supervisor.py +193 -0
- fuzzybits_server/ui.py +84 -0
- fuzzybits_server/webui/.vite/manifest.json +26 -0
- fuzzybits_server/webui/assets/Playground-B6V8NzhX.css +1 -0
- fuzzybits_server/webui/assets/Playground-CSpFbzwZ.js +5481 -0
- fuzzybits_server/webui/assets/Playground-CSpFbzwZ.js.map +1 -0
- fuzzybits_server/webui/assets/index-BnegRRhI.css +1 -0
- fuzzybits_server/webui/assets/index-C3oGCBE0.js +13 -0
- fuzzybits_server/webui/assets/index-C3oGCBE0.js.map +1 -0
- fuzzybits_server/webui/index.html +24 -0
- fuzzybits_server/worker.py +64 -0
- fuzzybits_server-0.17.0.dist-info/METADATA +281 -0
- fuzzybits_server-0.17.0.dist-info/RECORD +34 -0
- fuzzybits_server-0.17.0.dist-info/WHEEL +4 -0
- fuzzybits_server-0.17.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
__pycache__
|
|
2
|
+
.pytest_cache/
|
|
3
|
+
.vscode/
|
|
4
|
+
.cursorrules
|
|
5
|
+
.cursorignore
|
|
6
|
+
.cursorindexingignore
|
|
7
|
+
.specstory
|
|
8
|
+
.idea
|
|
9
|
+
.env
|
|
10
|
+
.env.local
|
|
11
|
+
.env.development.local
|
|
12
|
+
.env.test.local
|
|
13
|
+
.env.production.local
|
|
14
|
+
|
|
15
|
+
node_modules/
|
|
16
|
+
|
|
17
|
+
.git
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Qt Generated Project Configuration
|
|
21
|
+
CMakeLists.txt.user
|
|
22
|
+
|
|
23
|
+
# Build directories
|
|
24
|
+
build/
|
|
25
|
+
|
|
26
|
+
# Compiled Object files
|
|
27
|
+
*.slo
|
|
28
|
+
*.lo
|
|
29
|
+
*.o
|
|
30
|
+
|
|
31
|
+
# Compiled Dynamic libraries
|
|
32
|
+
*.so
|
|
33
|
+
*.dylib
|
|
34
|
+
|
|
35
|
+
# Compiled Static libraries
|
|
36
|
+
*.lai
|
|
37
|
+
*.la
|
|
38
|
+
*.a
|
|
39
|
+
|
|
40
|
+
# Python compiled files
|
|
41
|
+
*.pyc
|
|
42
|
+
|
|
43
|
+
# Pytest cache
|
|
44
|
+
.cache
|
|
45
|
+
.idea
|
|
46
|
+
fixtures
|
|
47
|
+
benchmarks
|
|
48
|
+
|
|
49
|
+
.vscode
|
|
50
|
+
.cursorrules
|
|
51
|
+
.cursorignore
|
|
52
|
+
.cursorindexingignore
|
|
53
|
+
.specstory
|
|
54
|
+
|
|
55
|
+
_deps
|
|
56
|
+
CMakeCache.txt
|
|
57
|
+
CMakeFiles
|
|
58
|
+
|
|
59
|
+
cmake-build-*
|
|
60
|
+
|
|
61
|
+
.env
|
|
62
|
+
|
|
63
|
+
docker-compose.yml
|
|
64
|
+
Dockerfile
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Server wrapper for the native fuzzybits engine."""
|
|
2
|
+
|
|
3
|
+
from fuzzybits_server.app import app, create_app, main
|
|
4
|
+
from fuzzybits_server.config import CalculationConfig
|
|
5
|
+
from fuzzybits_server.event_hub import EventHub
|
|
6
|
+
from fuzzybits_server.supervisor import CalculationSupervisor
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"CalculationConfig",
|
|
10
|
+
"CalculationSupervisor",
|
|
11
|
+
"EventHub",
|
|
12
|
+
"app",
|
|
13
|
+
"create_app",
|
|
14
|
+
"main",
|
|
15
|
+
]
|
fuzzybits_server/app.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
import webbrowser
|
|
8
|
+
|
|
9
|
+
import uvicorn
|
|
10
|
+
from fastapi import FastAPI
|
|
11
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
12
|
+
|
|
13
|
+
from fuzzybits_server.config import CalculationConfig, apply_server_cli, env_bool
|
|
14
|
+
from fuzzybits_server.event_hub import EventHub
|
|
15
|
+
from fuzzybits_server.native import shutdown_native_workers
|
|
16
|
+
from fuzzybits_server.routes import create_router
|
|
17
|
+
from fuzzybits_server.supervisor import CalculationSupervisor
|
|
18
|
+
from fuzzybits_server.ui import mount_ui
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def create_app(
|
|
22
|
+
*,
|
|
23
|
+
event_hub: EventHub | None = None,
|
|
24
|
+
supervisor: CalculationSupervisor | None = None,
|
|
25
|
+
autostart: bool | None = None,
|
|
26
|
+
) -> FastAPI:
|
|
27
|
+
hub = event_hub or EventHub()
|
|
28
|
+
calc_supervisor = supervisor or CalculationSupervisor(hub)
|
|
29
|
+
|
|
30
|
+
app = FastAPI(
|
|
31
|
+
title="fuzzybits-server",
|
|
32
|
+
description=(
|
|
33
|
+
"Compile OpenPSA/MEF fault trees to a PDAG (.pcfb) and sample the top event. "
|
|
34
|
+
"Monte Carlo estimates with confidence intervals. "
|
|
35
|
+
"Event-tree sequences are not compiled or sampled."
|
|
36
|
+
),
|
|
37
|
+
)
|
|
38
|
+
app.add_middleware(
|
|
39
|
+
CORSMiddleware,
|
|
40
|
+
allow_origins=["*"],
|
|
41
|
+
allow_methods=["GET", "POST", "OPTIONS"],
|
|
42
|
+
allow_headers=["*"],
|
|
43
|
+
)
|
|
44
|
+
app.state.event_hub = hub
|
|
45
|
+
app.state.supervisor = calc_supervisor
|
|
46
|
+
app.include_router(create_router(calc_supervisor, hub))
|
|
47
|
+
mount_ui(app)
|
|
48
|
+
|
|
49
|
+
should_autostart = autostart if autostart is not None else env_bool("MCSCRAM_AUTOSTART", False)
|
|
50
|
+
|
|
51
|
+
@app.on_event("startup")
|
|
52
|
+
async def on_startup() -> None:
|
|
53
|
+
hub.bind_loop(asyncio.get_running_loop())
|
|
54
|
+
if should_autostart:
|
|
55
|
+
calc_supervisor.start(CalculationConfig.from_env())
|
|
56
|
+
|
|
57
|
+
@app.on_event("shutdown")
|
|
58
|
+
def on_shutdown() -> None:
|
|
59
|
+
calc_supervisor.stop()
|
|
60
|
+
shutdown_native_workers()
|
|
61
|
+
|
|
62
|
+
return app
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
app = create_app()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _browser_url(host: str, port: int) -> str:
|
|
69
|
+
browse_host = "127.0.0.1" if host in {"0.0.0.0", "::", "[::]"} else host
|
|
70
|
+
return f"http://{browse_host}:{port}/"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main() -> None:
|
|
74
|
+
args = apply_server_cli()
|
|
75
|
+
if args.open:
|
|
76
|
+
url = _browser_url(args.host, args.port)
|
|
77
|
+
|
|
78
|
+
def _open() -> None:
|
|
79
|
+
time.sleep(0.6)
|
|
80
|
+
webbrowser.open(url)
|
|
81
|
+
|
|
82
|
+
threading.Thread(target=_open, daemon=True).start()
|
|
83
|
+
uvicorn.run(
|
|
84
|
+
"fuzzybits_server.app:create_app",
|
|
85
|
+
factory=True,
|
|
86
|
+
host=args.host,
|
|
87
|
+
port=args.port,
|
|
88
|
+
log_level=os.getenv("LOG_LEVEL", "info"),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
main()
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from importlib.resources import files
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
# Optional data mount from fuzzybits-bench (CSVs, OpenPSA/Aralia XML).
|
|
12
|
+
# Historical run tables stay in that private repo; this tree never ships them.
|
|
13
|
+
SERVER_DATA_DIR_ENV = "FUZZYBITS_SERVER_DATA_DIR"
|
|
14
|
+
SERVER_ENGINE_ENV = "FUZZYBITS_SERVER_ENGINE"
|
|
15
|
+
SERVER_CACHE_DIR_ENV = "FUZZYBITS_SERVER_CACHE_DIR"
|
|
16
|
+
SERVER_UI_ENV = "FUZZYBITS_SERVER_UI"
|
|
17
|
+
SERVER_UI_DIR_ENV = "FUZZYBITS_SERVER_UI_DIR"
|
|
18
|
+
_LEGACY_DEFAULT_INPUT = Path("/app/input/SmallTree.xml")
|
|
19
|
+
_BOOLEAN_TRUE = {"1", "true", "yes", "on"}
|
|
20
|
+
_BOOLEAN_FALSE = {"0", "false", "no", "off"}
|
|
21
|
+
_BACKENDS = ("auto", "cuda", "omp", "metal")
|
|
22
|
+
_ENGINES = ("pcfb", "legacy")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def env_bool(name: str, default: bool) -> bool:
|
|
26
|
+
raw = os.getenv(name)
|
|
27
|
+
if raw is None:
|
|
28
|
+
return default
|
|
29
|
+
return raw.strip().lower() in _BOOLEAN_TRUE
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def server_engine() -> str:
|
|
33
|
+
"""Compile/sample engine: ``pcfb`` (default) or ``legacy`` in-memory PDAG."""
|
|
34
|
+
raw = os.getenv(SERVER_ENGINE_ENV, "pcfb").strip().lower()
|
|
35
|
+
if raw in {"legacy", "memory", "in-memory", "run_compile"}:
|
|
36
|
+
return "legacy"
|
|
37
|
+
return "pcfb"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def parse_watch_value(raw: Any) -> tuple[bool | None, list[str]]:
|
|
41
|
+
"""Split ``watch`` into (watch_mode, names).
|
|
42
|
+
|
|
43
|
+
``MCSCRAM_WATCH=1`` is the C++ progress-bar flag. Any other non-boolean
|
|
44
|
+
string is a comma-separated MEF name / PDAG-index list, matching how
|
|
45
|
+
:mod:`fuzzybits_server.convergence.sampling` registers extra tally nodes.
|
|
46
|
+
"""
|
|
47
|
+
if raw is None or raw is False:
|
|
48
|
+
return None, []
|
|
49
|
+
if raw is True:
|
|
50
|
+
return True, []
|
|
51
|
+
if isinstance(raw, (int, float)) and not isinstance(raw, bool):
|
|
52
|
+
return None, [str(int(raw))]
|
|
53
|
+
if isinstance(raw, (list, tuple, set)):
|
|
54
|
+
return None, [str(item).strip() for item in raw if str(item).strip()]
|
|
55
|
+
text = str(raw).strip()
|
|
56
|
+
if not text:
|
|
57
|
+
return None, []
|
|
58
|
+
lowered = text.lower()
|
|
59
|
+
if lowered in _BOOLEAN_TRUE:
|
|
60
|
+
return True, []
|
|
61
|
+
if lowered in _BOOLEAN_FALSE:
|
|
62
|
+
return False, []
|
|
63
|
+
return None, [part.strip() for part in text.replace(";", ",").split(",") if part.strip()]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def default_cache_dir() -> Path:
|
|
67
|
+
"""Per-user cache root (platformdirs); used when ``FUZZYBITS_SERVER_CACHE_DIR`` is unset."""
|
|
68
|
+
from platformdirs import user_cache_path
|
|
69
|
+
|
|
70
|
+
return user_cache_path("fuzzybits", "fuzzybit-org") / "server"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def pcfb_cache_dir() -> Path:
|
|
74
|
+
raw = os.getenv(SERVER_CACHE_DIR_ENV, "").strip()
|
|
75
|
+
path = Path(raw).expanduser() if raw else default_cache_dir()
|
|
76
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
return path
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def env_float(name: str, default: float) -> float:
|
|
81
|
+
raw = os.getenv(name)
|
|
82
|
+
if raw is None or raw == "":
|
|
83
|
+
return default
|
|
84
|
+
return float(raw)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def server_data_dir() -> Path | None:
|
|
88
|
+
"""Directory of optional bench data (CSVs, model XML).
|
|
89
|
+
|
|
90
|
+
Set ``FUZZYBITS_SERVER_DATA_DIR`` to a fuzzybits-bench checkout or mount.
|
|
91
|
+
Returns ``None`` when unset or not a directory — the server still starts;
|
|
92
|
+
model listing is empty and default input files are omitted.
|
|
93
|
+
"""
|
|
94
|
+
raw = os.getenv(SERVER_DATA_DIR_ENV, "").strip()
|
|
95
|
+
if not raw:
|
|
96
|
+
return None
|
|
97
|
+
path = Path(raw).expanduser()
|
|
98
|
+
return path if path.is_dir() else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def optional_table_path(name: str) -> Path | None:
|
|
102
|
+
"""Locate ``compiler.csv`` / ``convergence.csv`` under the data dir.
|
|
103
|
+
|
|
104
|
+
These tables are not imported into this public repo. fuzzybits-bench can
|
|
105
|
+
mount its copies via ``FUZZYBITS_SERVER_DATA_DIR``.
|
|
106
|
+
"""
|
|
107
|
+
data = server_data_dir()
|
|
108
|
+
if data is None:
|
|
109
|
+
return None
|
|
110
|
+
path = data / name
|
|
111
|
+
return path if path.is_file() else None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def input_files_from_env() -> list[str]:
|
|
115
|
+
raw = os.getenv("MCSCRAM_INPUT_FILES")
|
|
116
|
+
if raw is not None:
|
|
117
|
+
return [part.strip() for part in raw.replace(":", ",").split(",") if part.strip()]
|
|
118
|
+
|
|
119
|
+
data = server_data_dir()
|
|
120
|
+
if data is not None:
|
|
121
|
+
for candidate in (
|
|
122
|
+
data / "SmallTree.xml",
|
|
123
|
+
data / "input" / "SmallTree.xml",
|
|
124
|
+
data / "input" / "SmallTree" / "SmallTree.xml",
|
|
125
|
+
):
|
|
126
|
+
if candidate.is_file():
|
|
127
|
+
return [str(candidate)]
|
|
128
|
+
|
|
129
|
+
if _LEGACY_DEFAULT_INPUT.is_file():
|
|
130
|
+
return [str(_LEGACY_DEFAULT_INPUT)]
|
|
131
|
+
return []
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def options_from_env() -> dict[str, Any]:
|
|
135
|
+
options: dict[str, Any] = {}
|
|
136
|
+
|
|
137
|
+
for env_name, key in (
|
|
138
|
+
("MCSCRAM_NUM_TRIALS", "num_trials"),
|
|
139
|
+
("MCSCRAM_REQUESTED_TRIALS_PER_PASS", "requested_trials_per_pass"),
|
|
140
|
+
("MCSCRAM_DELTA", "delta"),
|
|
141
|
+
("MCSCRAM_BURN_IN", "burn_in"),
|
|
142
|
+
("MCSCRAM_CONFIDENCE", "confidence"),
|
|
143
|
+
("MCSCRAM_ORACLE", "oracle"),
|
|
144
|
+
("MCSCRAM_MISSION_TIME", "mission_time"),
|
|
145
|
+
("MCSCRAM_TIME_STEP", "time_step"),
|
|
146
|
+
("MCSCRAM_CUT_OFF", "cut_off"),
|
|
147
|
+
):
|
|
148
|
+
if raw := os.getenv(env_name):
|
|
149
|
+
options[key] = float(raw)
|
|
150
|
+
|
|
151
|
+
for env_name, key in (
|
|
152
|
+
("MCSCRAM_SEED", "seed"),
|
|
153
|
+
("MCSCRAM_LIMIT_ORDER", "limit_order"),
|
|
154
|
+
("MCSCRAM_COMPILATION_PASSES", "compilation_passes"),
|
|
155
|
+
):
|
|
156
|
+
if raw := os.getenv(env_name):
|
|
157
|
+
options[key] = int(raw)
|
|
158
|
+
|
|
159
|
+
for env_name, key in (
|
|
160
|
+
("MCSCRAM_EARLY_STOP", "early_stop"),
|
|
161
|
+
("MCSCRAM_NO_KN", "no_kn"),
|
|
162
|
+
("MCSCRAM_NO_XOR", "no_xor"),
|
|
163
|
+
("MCSCRAM_RECOGNIZE_ATLEAST_GROUPS", "recognize_atleast_groups"),
|
|
164
|
+
("MCSCRAM_RECOGNIZE_XOR_GROUPS", "recognize_xor_groups"),
|
|
165
|
+
("MCSCRAM_PREPROCESSOR", "preprocessor"),
|
|
166
|
+
("MCSCRAM_PRINT", "print"),
|
|
167
|
+
("MCSCRAM_IMPORTANCE", "importance"),
|
|
168
|
+
("MCSCRAM_UNCERTAINTY", "uncertainty"),
|
|
169
|
+
("MCSCRAM_CCF", "ccf"),
|
|
170
|
+
("MCSCRAM_SIL", "sil"),
|
|
171
|
+
):
|
|
172
|
+
if raw := os.getenv(env_name):
|
|
173
|
+
options[key] = raw.strip().lower() in {"1", "true", "yes", "on"}
|
|
174
|
+
|
|
175
|
+
if watch_raw := os.getenv("MCSCRAM_WATCH"):
|
|
176
|
+
mode, names = parse_watch_value(watch_raw)
|
|
177
|
+
if mode is not None:
|
|
178
|
+
options["watch_mode"] = mode
|
|
179
|
+
if names:
|
|
180
|
+
options["watch"] = names
|
|
181
|
+
if watch_nodes := os.getenv("MCSCRAM_WATCH_NODES"):
|
|
182
|
+
_, names = parse_watch_value(watch_nodes)
|
|
183
|
+
if names:
|
|
184
|
+
existing = [str(item) for item in options.get("watch", [])] if isinstance(options.get("watch"), list) else []
|
|
185
|
+
options["watch"] = existing + names
|
|
186
|
+
|
|
187
|
+
if policy := os.getenv("MCSCRAM_POLICY"):
|
|
188
|
+
options["policy"] = policy
|
|
189
|
+
|
|
190
|
+
if overrides := os.getenv("MCSCRAM_OPTIONS_JSON"):
|
|
191
|
+
parsed = json.loads(overrides)
|
|
192
|
+
if not isinstance(parsed, dict):
|
|
193
|
+
raise ValueError("MCSCRAM_OPTIONS_JSON must decode to a JSON object")
|
|
194
|
+
options.update(parsed)
|
|
195
|
+
|
|
196
|
+
return options
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def parse_server_cli(argv: list[str] | None = None) -> argparse.Namespace:
|
|
200
|
+
parser = argparse.ArgumentParser(
|
|
201
|
+
prog="fuzzybits-server",
|
|
202
|
+
description="Serve the fuzzybits API and playground UI on one port.",
|
|
203
|
+
)
|
|
204
|
+
parser.add_argument("--host", default="127.0.0.1", help="bind address (default: 127.0.0.1)")
|
|
205
|
+
parser.add_argument("--port", type=int, default=8000, help="bind port (default: 8000)")
|
|
206
|
+
parser.add_argument("--data-dir", default=None, metavar="DIR", help="OpenPSA/Aralia XML root (FUZZYBITS_SERVER_DATA_DIR)")
|
|
207
|
+
parser.add_argument(
|
|
208
|
+
"--cache-dir",
|
|
209
|
+
default=None,
|
|
210
|
+
metavar="DIR",
|
|
211
|
+
help=f"compiled .pcfb cache (default: {default_cache_dir()})",
|
|
212
|
+
)
|
|
213
|
+
parser.add_argument(
|
|
214
|
+
"--backend",
|
|
215
|
+
choices=_BACKENDS,
|
|
216
|
+
default="auto",
|
|
217
|
+
help="AdaptiveCpp visibility: auto (default), cuda, omp, or metal",
|
|
218
|
+
)
|
|
219
|
+
parser.add_argument(
|
|
220
|
+
"--engine",
|
|
221
|
+
choices=_ENGINES,
|
|
222
|
+
default=None,
|
|
223
|
+
help="compile/sample engine: pcfb (default) or legacy in-memory PDAG",
|
|
224
|
+
)
|
|
225
|
+
parser.add_argument("--no-ui", action="store_true", help="disable the playground UI; GET / returns an API pointer")
|
|
226
|
+
parser.add_argument("--open", action="store_true", help="open the UI in a browser")
|
|
227
|
+
return parser.parse_args(argv)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def apply_server_cli(argv: list[str] | None = None) -> argparse.Namespace:
|
|
231
|
+
"""Parse CLI flags and apply them to the process environment."""
|
|
232
|
+
args = parse_server_cli(argv)
|
|
233
|
+
os.environ["HOST"] = args.host
|
|
234
|
+
os.environ["PORT"] = str(args.port)
|
|
235
|
+
if args.data_dir:
|
|
236
|
+
os.environ[SERVER_DATA_DIR_ENV] = str(Path(args.data_dir).expanduser())
|
|
237
|
+
if args.cache_dir:
|
|
238
|
+
os.environ[SERVER_CACHE_DIR_ENV] = str(Path(args.cache_dir).expanduser())
|
|
239
|
+
if args.backend != "auto":
|
|
240
|
+
os.environ["ACPP_VISIBILITY_MASK"] = args.backend
|
|
241
|
+
os.environ["FUZZYBITS_BACKEND"] = args.backend
|
|
242
|
+
if args.engine:
|
|
243
|
+
os.environ[SERVER_ENGINE_ENV] = args.engine
|
|
244
|
+
if args.no_ui:
|
|
245
|
+
os.environ[SERVER_UI_ENV] = "0"
|
|
246
|
+
return args
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def server_ui_enabled() -> bool:
|
|
250
|
+
return env_bool(SERVER_UI_ENV, True)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _ui_index(path: Path) -> Path | None:
|
|
254
|
+
index = path / "index.html"
|
|
255
|
+
return path if path.is_dir() and index.is_file() else None
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def packaged_ui_dir() -> Path | None:
|
|
259
|
+
"""CSR build shipped in the wheel at ``fuzzybits_server/webui/``."""
|
|
260
|
+
try:
|
|
261
|
+
traversable = files("fuzzybits_server") / "webui"
|
|
262
|
+
except (ModuleNotFoundError, FileNotFoundError, TypeError, AttributeError, NotADirectoryError):
|
|
263
|
+
return None
|
|
264
|
+
try:
|
|
265
|
+
if not traversable.is_dir() or not (traversable / "index.html").is_file():
|
|
266
|
+
return None
|
|
267
|
+
except (FileNotFoundError, OSError, TypeError, NotADirectoryError):
|
|
268
|
+
return None
|
|
269
|
+
path = Path(traversable) if isinstance(traversable, Path) else Path(str(traversable))
|
|
270
|
+
return _ui_index(path)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def source_ui_dir() -> Path | None:
|
|
274
|
+
"""``tools/server/webui/dist`` next to a src checkout or the Docker image copy."""
|
|
275
|
+
return _ui_index(Path(__file__).resolve().parents[2] / "webui" / "dist")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def server_ui_dir() -> Path | None:
|
|
279
|
+
"""Directory of the CSR playground build (``index.html`` + ``assets/``).
|
|
280
|
+
|
|
281
|
+
``FUZZYBITS_SERVER_UI_DIR`` wins. Otherwise the copy bundled in the wheel
|
|
282
|
+
(``importlib.resources``), then ``tools/server/webui/dist`` for a source
|
|
283
|
+
checkout or the server image.
|
|
284
|
+
"""
|
|
285
|
+
raw = os.getenv(SERVER_UI_DIR_ENV, "").strip()
|
|
286
|
+
if raw:
|
|
287
|
+
return _ui_index(Path(raw).expanduser())
|
|
288
|
+
return packaged_ui_dir() or source_ui_dir()
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@dataclass(frozen=True)
|
|
292
|
+
class CalculationConfig:
|
|
293
|
+
input_files: list[str]
|
|
294
|
+
options: dict[str, Any]
|
|
295
|
+
pcfb_path: str | None = None
|
|
296
|
+
|
|
297
|
+
@classmethod
|
|
298
|
+
def from_env(cls) -> CalculationConfig:
|
|
299
|
+
return cls(input_files=input_files_from_env(), options=options_from_env())
|
|
300
|
+
|
|
301
|
+
def with_options(self, **overrides: Any) -> CalculationConfig:
|
|
302
|
+
if not overrides:
|
|
303
|
+
return self
|
|
304
|
+
options = dict(self.options)
|
|
305
|
+
options.update(overrides)
|
|
306
|
+
return CalculationConfig(
|
|
307
|
+
input_files=self.input_files,
|
|
308
|
+
options=options,
|
|
309
|
+
pcfb_path=self.pcfb_path,
|
|
310
|
+
)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Host-side Monte-Carlo convergence and statistics engine.
|
|
2
|
+
|
|
3
|
+
The native ``fuzzybits`` engine is responsible only for the massively
|
|
4
|
+
parallel, device-side bitstream sampling. Everything statistical -- point
|
|
5
|
+
estimates, confidence/credible intervals, convergence policies, information gain,
|
|
6
|
+
diagnostics -- is computed here, on the host, in pure Python.
|
|
7
|
+
|
|
8
|
+
Layered design (each layer is independently testable):
|
|
9
|
+
|
|
10
|
+
* :mod:`.special` -- dependency-free special functions / sampling formulas.
|
|
11
|
+
* :mod:`.tally` -- raw counter + trajectory state (``NodeState``, ``RunState``).
|
|
12
|
+
* :mod:`.sampling` -- the ``Sampler`` boundary (native + simulated).
|
|
13
|
+
* :mod:`.metrics` -- non-stopping derived metrics (point estimate, information
|
|
14
|
+
gain, oracle diagnostics).
|
|
15
|
+
* :mod:`.policies` -- convergence policies (Wald linear, Bayes credible, GBAS).
|
|
16
|
+
* :mod:`.gbas` -- Huber's GBAS numerics (numpy/scipy; imported lazily).
|
|
17
|
+
* :mod:`.runner` -- the pass->tally->update->emit loop and configuration.
|
|
18
|
+
|
|
19
|
+
Typical use::
|
|
20
|
+
|
|
21
|
+
from fuzzybits_server.convergence import run_calculation
|
|
22
|
+
result = run_calculation(input_files, options, on_progress)
|
|
23
|
+
|
|
24
|
+
or, for full control / testing::
|
|
25
|
+
|
|
26
|
+
from fuzzybits_server.convergence import (
|
|
27
|
+
BernoulliSampler, ConvergenceConfig, ConvergenceRunner,
|
|
28
|
+
WaldLinearPolicy, BayesPolicy,
|
|
29
|
+
)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from .metrics import (
|
|
35
|
+
InfoGainMetric,
|
|
36
|
+
Metric,
|
|
37
|
+
OracleDiagnostics,
|
|
38
|
+
PointEstimate,
|
|
39
|
+
default_metrics,
|
|
40
|
+
)
|
|
41
|
+
from .policies import (
|
|
42
|
+
BayesPolicy,
|
|
43
|
+
ConvergencePolicy,
|
|
44
|
+
GBASPolicy,
|
|
45
|
+
PolicyVerdict,
|
|
46
|
+
WaldLinearPolicy,
|
|
47
|
+
make_policy,
|
|
48
|
+
)
|
|
49
|
+
from .runner import (
|
|
50
|
+
ConvergenceConfig,
|
|
51
|
+
ConvergenceRunner,
|
|
52
|
+
ProgressCallback,
|
|
53
|
+
RunResult,
|
|
54
|
+
run_calculation,
|
|
55
|
+
)
|
|
56
|
+
from .sampling import BernoulliSampler, NativeSampler, PcfbSampler, SampleShape, Sampler, make_sampler
|
|
57
|
+
from .tally import (
|
|
58
|
+
HistoryPoint,
|
|
59
|
+
NodeCounters,
|
|
60
|
+
NodeState,
|
|
61
|
+
PassObservation,
|
|
62
|
+
RunContext,
|
|
63
|
+
RunState,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
__all__ = [
|
|
67
|
+
# entry points
|
|
68
|
+
"run_calculation",
|
|
69
|
+
"ConvergenceRunner",
|
|
70
|
+
"ConvergenceConfig",
|
|
71
|
+
"RunResult",
|
|
72
|
+
"ProgressCallback",
|
|
73
|
+
# sampling
|
|
74
|
+
"Sampler",
|
|
75
|
+
"NativeSampler",
|
|
76
|
+
"PcfbSampler",
|
|
77
|
+
"BernoulliSampler",
|
|
78
|
+
"make_sampler",
|
|
79
|
+
"SampleShape",
|
|
80
|
+
# state
|
|
81
|
+
"NodeCounters",
|
|
82
|
+
"HistoryPoint",
|
|
83
|
+
"PassObservation",
|
|
84
|
+
"NodeState",
|
|
85
|
+
"RunState",
|
|
86
|
+
"RunContext",
|
|
87
|
+
# metrics
|
|
88
|
+
"Metric",
|
|
89
|
+
"PointEstimate",
|
|
90
|
+
"InfoGainMetric",
|
|
91
|
+
"OracleDiagnostics",
|
|
92
|
+
"default_metrics",
|
|
93
|
+
# policies
|
|
94
|
+
"ConvergencePolicy",
|
|
95
|
+
"PolicyVerdict",
|
|
96
|
+
"WaldLinearPolicy",
|
|
97
|
+
"BayesPolicy",
|
|
98
|
+
"GBASPolicy",
|
|
99
|
+
"make_policy",
|
|
100
|
+
]
|