Python API Reference
megane - A fast, beautiful molecular viewer.
Installation
pip install megane
import megane
MolecularViewer
Inherits from: anywidget.AnyWidget
Interactive molecular viewer widget for Jupyter notebooks.
Usage:
import megane viewer = megane.MolecularViewer() viewer.load("protein.pdb") viewer # displays in notebook cell
With trajectory:
viewer.load("protein.pdb", xtc="trajectory.xtc") viewer.frame_index = 50 # jump to frame 50
External event triggers:
Set atom selection programmatically
viewer.selected_atoms = [10, 20, 30, 40] print(viewer.measurement) # dihedral angle result
React to events
@viewer.on_event("measurement") ... def on_measurement(data): ... print(f"Measured: {data}")
Plotly integration example
fig = go.FigureWidget(data=[go.Scatter(x=times, y=energies)]) def on_click(trace, points, state): ... viewer.frame_index = points.point_inds[0] fig.data[0].on_click(on_click)
__init__
def __init__(*args, **kwargs)
load
def load(pdb_path: str, xtc: str | None = None, traj: str | None = None) -> None
Load a molecular structure, optionally with a trajectory.
.. deprecated::
Use :meth:set_pipeline with a :class:~megane.pipeline.Pipeline
instead.
Args: pdb_path: Path to PDB file. xtc: Optional path to XTC trajectory file. traj: Optional path to ASE .traj file. When provided, pdb_path is ignored and both structure and trajectory are read from the .traj file.
measurement
def measurement() -> dict | None
Current measurement result, or None if fewer than 2 atoms selected.
Returns a dict with keys: type, value, label, atoms. Example: {'type': 'dihedral', 'value': 120.5, 'label': '120.5°', 'atoms': [10, 20, 30, 40]}
on_event
def on_event(event_name: str, callback: Callable | None = None)
Register a callback for an event.
Can be used as a decorator or a method call:
@viewer.on_event("measurement") def on_measurement(data): print(data)
or equivalently:
viewer.on_event("measurement", on_measurement)
Supported events:
- "frame_change": fired when frame_index changes. Data: {"frame_index": int}
- "selection_change": fired when selected_atoms changes. Data: {"atoms": list[int]}
- "measurement": fired when a measurement is computed. Data: {"type": str, "value": float, "label": str, "atoms": list[int]} or None
Args: event_name: Name of the event. callback: Callable to invoke. If None, returns a decorator.
Returns: The callback (for decorator usage).
off_event
def off_event(event_name: str, callback: Callable | None = None)
Remove event callback(s).
Args: event_name: Name of the event. callback: Specific callback to remove. If None, removes all callbacks for the event.
set_pipeline
def set_pipeline(pipeline: Pipeline | None) -> None
Apply a pipeline to this viewer.
Args:
pipeline: A :class:~megane.pipeline.Pipeline instance,
or None to clear the pipeline.
Structure
Parsed molecular structure.
Fields:
| Field | Type | Description |
|---|---|---|
n_atoms | int | |
positions | np.ndarray | (N, 3) float32 |
elements | np.ndarray | (N,) uint8 - atomic numbers |
bonds | np.ndarray | (M, 2) uint32 - bond pairs |
bond_orders | np.ndarray | (M,) uint8 - 1=single, 2=double, 3=triple, 4=aromatic |
box | np.ndarray | (3, 3) float32 - cell vectors as rows, zero if no cell |
Functions
cell_params_to_matrix
def cell_params_to_matrix(a: float, b: float, c: float, alpha: float, beta: float, gamma: float) -> np.ndarray
Convert crystallographic cell parameters to a 3x3 matrix of cell vectors.
Args: a, b, c: Cell edge lengths in Angstroms. alpha, beta, gamma: Cell angles in degrees.
Returns: (3, 3) float32 array with cell vectors as rows.
load_pdb
def load_pdb(path: str) -> Structure
Load a PDB file using the shared Rust parser (megane-core).
Replaces the previous RDKit-based implementation for dramatically faster parsing. The same Rust code is used by the WASM frontend.
load_trajectory
def load_trajectory(pdb_path: str, xtc_path: str) -> InMemoryTrajectory
Load a trajectory from PDB topology + XTC coordinates.
Uses the Rust XTC parser (megane-core) instead of MDAnalysis.
Args: pdb_path: Path to PDB file (topology, used for atom count validation). xtc_path: Path to XTC file (trajectory).
Returns: InMemoryTrajectory with frame-by-frame access.