Open existing results in the browser-based web viewer
This script demonstrates the “reopen results without re-running the solver” workflow:
- Load a serialized model from
<out_dir>/model.pkl. - The Problem’s SQLite results database is reconnected lazily on first
access (
Problem.__getstate__drops the live connection; the.rdbproperty recreates it from the preserved path). - Pick the first scalar field output on the last step.
- Serve the geometry + field as JSON via
WebViewer, which opens a three.js viewer in the browser; it works over SSH tunnels and on headless servers.
Prerequisite
Section titled “Prerequisite”Run a producing script first so that a pickle exists, e.g.:
python examples/scripts/01_getting_started/05_results_and_viewer.py# Default — load the cantilever produced by script 05python 06_load_results_webviewer.py
# Any other model name that has been pickled under the temp dirpython 06_load_results_webviewer.py getting_started_resultspython 06_load_results_webviewer.py fire_isotherm_500
# Pick a specific field/componentpython 06_load_results_webviewer.py getting_started_results U z
The model before it is solved: its parts, supports (red) and loads (blue).
![The result: the deformed shape coloured by displacement (magnitude [mm])](/examples/getting-started/06-load-results-webviewer-results.webp)
The deformed shape, coloured by displacement (magnitude [mm]), in xfea’s 3D viewer.
Open in 3D turn it, cut it, pick any field: in xfea's viewer, in your browser
The script
Section titled “The script”examples/scripts/01_getting_started/06_load_results_webviewer.py. Run it from the repository with uv run python examples/scripts/01_getting_started/06_load_results_webviewer.py, or, with xfea-examples installed, xfea-examples run 01_getting_started/06_load_results_webviewer.py.
from __future__ import annotations
import sysfrom pathlib import Path
from xfea.model import Modelfrom xfea.viewers import SceneContextfrom xfea.viewers import ViewerSettingsfrom xfea_view import WebViewer
from xfea_examples import out_dirfrom xfea_examples import viewer_wanted
# CLI argumentsMODEL_NAME = sys.argv[1] if len(sys.argv) > 1 else "getting_started_results"FIELD_HINT = sys.argv[2] if len(sys.argv) > 2 else None # e.g. "U", "T", "S"COMPONENT = sys.argv[3] if len(sys.argv) > 3 else None # e.g. "z", "magnitude"
# 1. Load the pickled modelpkl_path = Path(out_dir(MODEL_NAME)) / "model.pkl"if not pkl_path.exists(): raise FileNotFoundError( f"No pickled model found at {pkl_path}. Run a producing script first " f"(e.g. 05_results_and_viewer.py) so that `model.to_pickle(...)` is " f"called after the analysis." )
print(f"Loading model from: {pkl_path}")model = Model.from_pickle(str(pkl_path))
problem = list(model.problems)[0]step = problem.steps[-1]print(f"Problem: {problem.name}")print(f"Step: {step.name}")print(f"DB: {problem.rdb.db_uri}") # lazy reconnect happens here
# 2. Pick a field output to visualisefields = list(step.field_outputs or [])if not fields: raise RuntimeError(f"Step {step.name!r} has no field outputs.")
def _select_field(fields, hint): """Pick a field output from *fields* matching ``hint``.
Matching is tried in increasing order of "loose-ness" so unambiguous short hints like ``s`` / ``u`` / ``t`` resolve to the expected canonical field (stress / displacement / temperature) even though ``s`` is a substring of ``DisplacementFieldResults`` etc.:
1. Exact (case-insensitive) match on ``field_name`` — xfea's canonical short label (``"s"``, ``"u"``, ``"t"``, ...). 2. Case-insensitive prefix match on the class name or a class it derives from (``"stress"`` ⇒ ``StressFieldResults``, which a solver plugin's own stress field derives from). 3. Substring match on the class name (fallback). """ if hint is None: return fields[0] h = hint.lower() # 1. Exact canonical short name. for fo in fields: if str(getattr(fo, "field_name", "")).lower() == h: return fo # 2. Prefix match on the class name or a class it derives from (a solver # plugin's field derives from xfea's own). for fo in fields: if any(c.__name__.lower().startswith(h) for c in type(fo).__mro__): return fo # 3. Loose substring match on class name. for fo in fields: if h in type(fo).__name__.lower(): return fo raise RuntimeError( f"No field output matches hint {hint!r}. Available: " + ", ".join( f"{type(fo).__name__}({getattr(fo, 'field_name', '?')})" for fo in fields ) )
field = _select_field(fields, FIELD_HINT)
# 3. Pick component(s) to export# For stress fields we export the whole catalogue of useful scalars at once,# and let the user switch between them via the in-browser "Field:" dropdown.# That way the CLI stays simple — ``06_load_results_webviewer.py reference_arch_solid s``# is enough — and the full s11/s22/.../smin/smid/smax/von_mises/... set is# available interactively without re-running the script.from xfea.results.fields import StressFieldResults
STRESS_SCALAR_COMPONENTS = ( # Tensor components (global frame). "s11", "s22", "s33", "s12", "s13", "s23", # Ordered principal values. "smin", "smid", "smax", # Common invariants and derived scalars. "von_mises_stress", "tresca_stress", "hydrostatic_stress", "I1", "J2",)
if isinstance(field, StressFieldResults): # List form: [(field, component, units?), ...] — the browser viewer's # _iter_results_fields handles duplicates and dedups labels, and the # build_scene() results cache means the underlying centroid aggregation # runs exactly once for the whole catalogue. results_fields_arg = [(field, comp) for comp in STRESS_SCALAR_COMPONENTS] print( f"Showing field {type(field).__name__} with {len(STRESS_SCALAR_COMPONENTS)} " f"components available in the viewer dropdown: {', '.join(STRESS_SCALAR_COMPONENTS)}" )else: component = COMPONENT or (getattr(field, "components", ["magnitude"]) or ["magnitude"])[0] results_fields_arg = {field: component} print(f"Showing field {type(field).__name__} / component {component!r}")
# 4. Build the scene and open the web viewer# WebViewer serialises the surface mesh + per-node scalars to JSON, starts# a tiny HTTP server, and serves a three.js page. No GUI libraries are# needed — just a browser. Set open_browser=False if you are running over# an SSH tunnel and will open the URL manually on the client.settings = ViewerSettings()
viewer_kwargs = dict( settings=settings, port=9999, # auto-falls back to a free port if taken open_browser=True,)# When a stress field is being visualised, also export principal-stress# vectors at element centroids so the three.js viewer can render them as# arrows (toggle in the UI panel).if isinstance(field, StressFieldResults): viewer_kwargs["element_location"] = "centroid" viewer_kwargs["stress_vectors"] = "centroid"
viewer = WebViewer(**viewer_kwargs)
ctx = SceneContext.from_settings( settings, model=model, results_fields=results_fields_arg,)
viewer.build_scene(ctx)if viewer_wanted(): # XFEA_EXAMPLES_SHOW_VIEWER=1, or `xfea-examples config set-show-viewer on` print("\nPress Ctrl+C in this terminal to stop the viewer server.") try: viewer.show() # blocks until Ctrl+C finally: viewer.clear()else: print("Viewer scene built. Set XFEA_EXAMPLES_SHOW_VIEWER=1 to open it in the browser.") viewer.clear()© 2026 Francesco Ranaudo · Text and pictures CC BY 4.0 · Code Elastic License 2.0 · how to reuse them