Visualization#
Visualization utilities for molecule graphs, reactions, ITS graphs, diagnostic graph adapters, CRNs, embeddings, and output export helpers.
Modern molecule/reaction/ITS renderers#
- synkit.Vis.molecule_drawer.draw_molecule_graph(graph: Graph, *, ax: Axes | None = None, title: str | None = None, label_mode: str = 'hetero', show_atom_map: bool = False, show_bond_order: bool = False, aromatic_style: str = 'circle', include_rdkit_panel: bool = False, use_h_count: bool = False, node_size: int | None = None, bond_width: float | None = None, figsize: Tuple[float, float] = (6.0, 5.0), highlight_nodes: Set[Any] | None = None, highlight_edges: Set[Tuple[Any, Any]] | None = None, highlight_color: str = '#f97316', custom_node_colors: Mapping[Any, str] | None = None) Axes | tuple[Figure, tuple[Axes, Axes]][source]#
Draw a scalar molecular graph using RDKit coordinates when possible.
- Parameters:
graph (nx.Graph) – Molecular NetworkX graph with scalar
elementandorderattributes.ax (Optional[plt.Axes]) – Optional Matplotlib axes.
title (Optional[str]) – Optional title.
label_mode (str) –
"all","hetero", or"none".show_atom_map (bool) – Show atom-map numbers near atoms.
show_bond_order (bool) – Show numeric bond order labels.
aromatic_style (str) –
"circle"or"dashed".include_rdkit_panel (bool) – Also show RDKit’s own rendering side-by-side.
use_h_count (bool) – Pass graph
hcounttoGraphToMolfor layout.
- Returns:
Axes, or
(fig, (rdkit_ax, graph_ax))wheninclude_rdkit_panel=True.- Return type:
Union[plt.Axes, Tuple[plt.Figure, Tuple[plt.Axes, plt.Axes]]]
- class synkit.Vis.reaction_drawer.ReactionHighlights(changed_atoms: frozenset[int], formed_bonds: frozenset[frozenset[int]], broken_bonds: frozenset[frozenset[int]], order_changed_bonds: frozenset[frozenset[int]])[source]#
Bases:
objectAtom-map based reaction-center highlights.
- synkit.Vis.reaction_drawer.draw_reaction_graph(rsmi: str, *, title: str | None = None, show_atom_map: bool = True, highlight_reaction_center: bool = True, label_mode: str = 'hetero', aromatic_style: str = 'circle', figsize_per_mol: Tuple[float, float] = (3.2, 2.8), sanitize: bool = True) tuple[Figure, list[Axes]][source]#
Draw an RSMI as molecular graph panels.
- Parameters:
rsmi (str) – Reaction SMILES, preferably atom-mapped when reaction-center highlighting is desired.
title (Optional[str]) – Optional figure title.
show_atom_map (bool) – Show atom-map/index labels on molecule panels.
highlight_reaction_center (bool) – Highlight changed mapped atoms/bonds.
label_mode (str) – Molecule label mode passed to
draw_molecule_graph.aromatic_style (str) – Molecule aromatic style.
figsize_per_mol (tuple[float, float]) – Approximate panel size for each molecular graph.
sanitize (bool) – Whether to sanitize molecules during RSMI conversion.
- Returns:
(fig, axes).- Return type:
- synkit.Vis.reaction_drawer.draw_reaction_graphs(reactant: Graph, product: Graph, *, title: str | None = None, show_atom_map: bool = True, highlight_reaction_center: bool = True, label_mode: str = 'hetero', aromatic_style: str = 'circle', figsize_per_mol: Tuple[float, float] = (3.2, 2.8)) tuple[Figure, list[Axes]][source]#
Draw reactant and product graphs as molecule panels.
- synkit.Vis.reaction_drawer.find_reaction_highlights(reactant: Graph, product: Graph) ReactionHighlights[source]#
Find atom-map based changed atoms and bonds between two side graphs.
- synkit.Vis.its_drawer.draw_its_from_rsmi(rsmi: str, *, format: str = 'tuple', core: bool = False, title: str | None = None, mode: str = 'sigma_pi', show_atom_map: bool = True, label_mode: str = 'hetero', aromatic_style: str = 'circle', include_delta_panel: bool = True, projection: bool = False, show_edge_labels: bool = False, edge_label_mode: str = 'kekule', show_electron_labels: bool = False, electron_label_mode: str = 'charge') tuple[Figure, list[Axes]][source]#
Build an ITS from RSMI and draw it.
- synkit.Vis.its_drawer.draw_its_graph(its: Graph, *, title: str | None = None, mode: str = 'sigma_pi', show_atom_map: bool = True, label_mode: str = 'hetero', aromatic_style: str = 'circle', include_delta_panel: bool = True, projection: bool = False, show_edge_labels: bool = False, edge_label_mode: str = 'kekule', show_electron_labels: bool = False, electron_label_mode: str = 'charge') tuple[Figure, list[Axes]][source]#
Draw an ITS graph.
By default this draws only the ITS as a molecule-like graph. Changed bonds are colored and compactly labeled from
kekule_order. Optional node electron labels can show one of charge, lone-pair, radical, or all changes. Setprojection=Trueto draw reactant/product molecular projections plus a diagnostic ITS panel.- Parameters:
its (nx.Graph) – ITS graph in tuple or legacy representation.
title (Optional[str]) – Optional figure title.
mode (str) – Diagnostic label mode for the projection-mode delta panel.
show_atom_map (bool) – Show atom-map labels.
label_mode (str) – Atom label mode.
aromatic_style (str) – Aromatic style for molecular panels.
include_delta_panel – In projection mode, include a diagnostic ITS graph panel. :type include_delta_panel: bool
projection (bool) – If
True, draw reactant/product molecular projection panels plus an ITS delta panel. IfFalse, draw only the ITS graph.show_edge_labels (bool) – If
True, show labels for unchanged edges too. Changed edge labels are shown by default unlessedge_label_modeis"none".edge_label_mode (str) –
"kekule","sigma_pi", or"none".show_electron_labels (bool) – Show changed atom electron annotations.
electron_label_mode (str) –
"charge","lone_pair","radical", or"all".
- Returns:
(fig, axes).- Return type:
- synkit.Vis.its_drawer.draw_its_only(its: Graph, *, ax: Axes | None = None, title: str | None = None, show_atom_map: bool = True, label_mode: str = 'hetero', aromatic_style: str = 'circle', show_edge_labels: bool = False, edge_label_mode: str = 'kekule', show_electron_labels: bool = False, electron_label_mode: str = 'charge') Axes[source]#
Draw a molecule-like ITS transition graph on one axes.
- synkit.Vis.mtg_drawer.draw_mtg_graph(mtg: Any, *, ax: Axes | None = None, title: str | None = None, mode: str = 'timeline', layout: str = 'kamada_kawai', show_atom_map: bool = True, show_edge_labels: bool = True, show_node_badges: bool = False, hydrogen_mode: str = 'changed', changed_only: bool = False, compress: bool = True, show_step_axis: bool = False, dimension: str = '2d', seed: int = 7) tuple[Figure, Axes][source]#
Draw a compact MTG timeline graph.
mtgmay be asynkit.Graph.MTG.mtg.MTGinstance or a raw compact MTGnetworkx.GraphfromMTG.get_mtg().- Parameters:
mtg (Any) – MTG object or compact MTG graph.
ax (Optional[plt.Axes]) – Optional Matplotlib axes.
title (Optional[str]) – Optional title.
mode (str) – Label mode.
"timeline"is the recommended MTG view;"sigma_pi"gives a shorter Lewis-state bond diagnostic when sigma/pi timelines are present.layout (str) – NetworkX layout name:
"kamada_kawai","spring","circular", or"shell".hydrogen_mode (str) – Hydrogen display policy.
"changed"keeps only hydrogens participating in changing edges,"all"keeps all, and"none"hides all hydrogens.changed_only (bool) – If True, hide unchanged edges and isolated nodes.
compress (bool) – If True, edge labels show only first and final state. If False, edge labels show the full mechanism-state timeline.
show_step_axis (bool) – Draw a compact state axis under the graph.
dimension (str) – Draw as
"2d"or"3d". The 3D mode uses a spring layout withdim=3and is helpful for dense changed cores.
- Returns:
(figure, axes).- Return type:
tuple[plt.Figure, plt.Axes]
- synkit.Vis.mtg_drawer.draw_mtg_steps(mtg: Any, *, steps: Iterable[int] | None = None, include_composed: bool = False, title: str | None = None, max_columns: int = 3, show_atom_map: bool = True, label_mode: str = 'hetero', edge_label_mode: str = 'kekule', show_edge_labels: bool = False, show_electron_labels: bool = False, electron_label_mode: str = 'charge') tuple[Figure, list[Axes]][source]#
Draw reconstructed MTG ITS steps as ordered panels.
- Parameters:
- Returns:
(figure, axes).- Return type:
Diagnostic adapter layer#
- class synkit.Vis.visual_model.VisualEdge(source: Hashable, target: Hashable, label: str = '', state: str = 'unchanged', color: str = '#2f3437', width: float = 2.0, raw: Mapping[str, ~typing.Any]=<factory>)[source]#
Bases:
objectDrawing-ready edge information.
- class synkit.Vis.visual_model.VisualGraph(kind: ~typing.Literal['molecule', 'legacy_its', 'tuple_its', 'compact_mtg', 'mechanism_dag', 'unknown'], nodes: tuple[~synkit.Vis.visual_model.VisualNode, ...], edges: tuple[~synkit.Vis.visual_model.VisualEdge, ...], title: str = '', metadata: ~typing.Mapping[str, ~typing.Any] = <factory>)[source]#
Bases:
objectA compact, immutable view of graph content for renderers.
- edges: tuple[VisualEdge, ...]#
- nodes: tuple[VisualNode, ...]#
- class synkit.Vis.visual_model.VisualNode(node_id: Hashable, label: str, element: str | None = None, atom_map: int | None = None, badges: tuple[str, ...]=(), changed: bool = False, raw: Mapping[str, ~typing.Any]=<factory>)[source]#
Bases:
objectDrawing-ready node information.
- synkit.Vis.visual_model.detect_visual_kind(graph: Graph) Literal['molecule', 'legacy_its', 'tuple_its', 'compact_mtg', 'mechanism_dag', 'unknown'][source]#
Return the visualization representation kind for
graph.- Parameters:
graph (nx.Graph) – NetworkX graph to inspect.
- Returns:
Detected graph kind.
- Return type:
VisualKind
- synkit.Vis.visual_model.iter_changed_edges(visual: VisualGraph) Iterable[VisualEdge][source]#
Yield edges whose visual state is not unchanged.
- synkit.Vis.visual_model.iter_changed_nodes(visual: VisualGraph) Iterable[VisualNode][source]#
Yield nodes with at least one visual badge/change marker.
- synkit.Vis.visual_model.summarize_visual_graph(visual: VisualGraph) Dict[str, Any][source]#
Return a notebook-friendly summary of a visual graph.
- synkit.Vis.visual_model.to_visual_graph(graph: Graph, *, kind: Literal['molecule', 'legacy_its', 'tuple_its', 'compact_mtg', 'mechanism_dag', 'unknown'] | None = None, mode: Literal['compact', 'electron', 'sigma_pi', 'timeline'] = 'compact', show_atom_map: bool = True, title: str = '') VisualGraph[source]#
Adapt a SynKit graph to drawing-ready labels.
- Parameters:
graph (nx.Graph) – NetworkX graph to adapt.
kind (Optional[VisualKind]) – Optional explicit representation kind.
mode (str) – Label density.
sigma_piandtimelineare mostly useful for tuple ITS and compact MTG.show_atom_map (bool) – Include atom-map numbers in node labels when present.
title (str) – Optional title carried to renderer metadata.
- Returns:
Immutable visual graph model.
- Return type:
- synkit.Vis.visual_drawer.draw_graph(graph: Graph | VisualGraph, *, ax: Axes | None = None, mode: str = 'compact', title: str | None = None, show_atom_map: bool = True, layout: str = 'spring', pos: Mapping[Any, tuple[float, float]] | None = None, seed: int = 7, node_size: int = 980, font_size: int = 9, edge_label_font_size: int = 8, show_edge_labels: bool = True, show_node_badges: bool = True) tuple[Figure, Axes][source]#
Draw a molecule, ITS, or MTG graph using the visual adapter.
- Parameters:
graph (Union[nx.Graph, VisualGraph]) – Raw NetworkX graph or already adapted
VisualGraph.ax (Optional[plt.Axes]) – Optional Matplotlib axes.
mode (str) – Adapter label mode, e.g.
compact,electron,sigma_pi, ortimeline.title (Optional[str]) – Optional title. Defaults to the detected visual kind.
show_atom_map (bool) – Include atom maps in labels when adapting raw graphs.
layout (str) – Layout name:
spring,kamada_kawai,circular, orshell.pos (Optional[Mapping[Any, Tuple[float, float]]]) – Optional fixed positions.
- Returns:
(figure, axes).- Return type:
Tuple[plt.Figure, plt.Axes]
Legacy and utility visualizers#
- class synkit.Vis.rxn_vis.RXNVis(width: int = 800, height: int = 450, dpi: int = 96, background_colour: Tuple[float, float, float, float] | None = None, highlight_by_reactant: bool = True, bond_line_width: float = 2.0, atom_label_font_size: int = 12, show_atom_map: bool = False, highlight_reaction_center: bool = False, rc_atom_color: Tuple[float, float, float] = (1.0, 0.5, 0.0), rc_broken_color: Tuple[float, float, float] = (0.9, 0.2, 0.2), rc_formed_color: Tuple[float, float, float] = (0.0, 0.75, 0.0))[source]#
Bases:
objectVisualize molecules and reactions as PIL images.
When
highlight_reaction_center=Trueand the input is an atom-mapped reaction SMILES, each molecule is drawn individually so that changed atoms and bonds can be color-coded:Broken bonds (present in reactants only) —
rc_broken_colorFormed bonds (present in products only) —
rc_formed_colorOrder-changed bonds (present on both sides with different order) —
rc_atom_colorReaction-center atoms (any atom involved in the above) —
rc_atom_color
Reactions without atom mapping fall back to the standard
DrawReactionlayout automatically.- Parameters:
width (int) – Canvas width in pixels.
height (int) – Canvas height in pixels.
dpi (int) – DPI scaling factor (72 = 1×, i.e. no scaling).
background_colour (Optional[Tuple[float, float, float, float]]) – RGBA background color, each channel in [0, 1]. Defaults to opaque white.
highlight_by_reactant (bool) – Color each reactant differently in the standard (non-RC)
DrawReactionpath.bond_line_width (float) – Bond line width in points.
atom_label_font_size (int) – Base font size for atom labels (maps to
MolDrawOptions.baseFontSize).show_atom_map (bool) – Overlay atom-map numbers as atom labels.
highlight_reaction_center (bool) – When
True, detect and highlight the reaction center in atom-mapped reaction SMILES.rc_atom_color (Tuple[float, float, float]) – RGB color for reaction-center atoms and order-changed bonds (values in [0, 1]).
rc_broken_color (Tuple[float, float, float]) – RGB color for bonds broken in the reaction.
rc_formed_color (Tuple[float, float, float]) – RGB color for bonds formed in the reaction.
from synkit.Vis.rxn_vis import RXNVis vis = RXNVis( width=1200, height=400, highlight_reaction_center=True, show_atom_map=True, ) rsmi = ( "[CH3:1][C:2](=[O:3])[O:4][CH3:5].[O:6]([H:7])[H:8]" ">>" "[CH3:1][C:2](=[O:3])[O:6][H:7].[CH3:5][O:4][H:8]" ) vis.save_png(rsmi, "transesterification.png")
- render(smiles: str, return_bytes: bool = False) Image | bytes[source]#
Render a molecule or reaction SMILES to a PIL image or PNG bytes.
When
highlight_reaction_center=Trueandsmilesis an atom-mapped reaction SMILES, the reaction center is highlighted. Falls back to the standardDrawReactionlayout when no atom mapping is present.- Parameters:
- Returns:
Rendered image or PNG bytes.
- Return type:
Union[PIL.Image.Image, bytes]
- Raises:
ValueError – If the input cannot be parsed.
- class synkit.Vis.rule_vis.RuleVis(backend: str = 'nx')[source]#
Bases:
object- nx_vis(input: str | Tuple[Graph, Graph, Graph], sanitize: bool = False, figsize: Tuple[int, int] = (18, 5), orientation: str = 'horizontal', show_titles: bool = True, show_atom_map: bool = False, titles: Tuple[str, str, str] = ('Reactant', 'Imaginary Transition State', 'Product'), add_gridbox: bool = False, rule: bool = False) Figure[source]#
Visualize reactants, ITS, and products side-by-side or vertically, with interactive plotting turned off to prevent double-display, and correct handling of matplotlib axes arrays.
- class synkit.Vis.graph_visualizer.GraphVisualizer(node_attributes: Dict[str, str] | None = None, edge_attributes: Dict[str, str] | None = None)[source]#
Bases:
objectHigh‑level wrapper around Weinbauer’s plotting utilities.
- plot_as_mol(g: Graph, ax: Axes, use_mol_coords: bool = True, node_color: str = '#FFFFFF', node_size: int = 500, edge_color: str = '#000000', edge_width: float = 2.0, label_color: str = '#000000', font_size: int = 12, show_atom_map: bool = False, bond_char: Dict[int | None, str] | None = None, symbol_key: str = 'element', bond_key: str = 'order', aam_key: str = 'atom_map') None[source]#
Core molecular plotting on a given Axes.
- plot_its(its: Graph, ax: Axes, use_mol_coords: bool = True, title: str | None = None, node_color: str = '#FFFFFF', node_size: int = 500, edge_color: str = '#000000', edge_weight: float = 2.0, show_atom_map: bool = False, use_edge_color: bool = False, symbol_key: str = 'element', bond_key: str = 'order', aam_key: str = 'atom_map', standard_order_key: str = 'standard_order', font_size: int = 12, og: bool = False, rule: bool = False, title_font_size: str = 20, title_font_weight: str = 'bold', title_font_style: str = 'italic') None[source]#
- visualize_its(its: Graph, **kwargs) Figure[source]#
Return a Matplotlib Figure plotting the ITS graph without duplicate display.
- visualize_its_grid(its_list: list[Graph], subplot_shape: tuple[int, int] | None = None, use_edge_color: bool = True, og: bool = False, figsize: tuple[float, float] = (12, 6), **kwargs) tuple[Figure, list[list[Axes]]][source]#
Plot multiple ITS graphs in a grid layout.
Parameters#
- its_listlist[nx.Graph]
List of ITS graphs to visualize.
- subplot_shapetuple[int, int] | None, optional
Grid shape (rows, cols). If None, determined by list length (supports up to 6).
- use_edge_colorbool, default True
Whether to color edges based on ‘standard_order’.
- ogbool, default False
Flag for original graph mode when coloring.
- figsizetuple[float, float], default (12,6)
Figure size.
- **kwargs
Additional parameters passed to plot_its (e.g. title, show_atom_map).
Returns#
- figplt.Figure
The Matplotlib figure containing the grid.
- axeslist of list of plt.Axes
2D list of Axes objects for each subplot.
- synkit.Vis.chemical_space.scatter_plot(data_train, data_test, size_train=10, size_test=10, title=None, ax=None, xlabel='Coordinate 1', ylabel='Coordinate 2')[source]#
- class synkit.Vis.crn_vis.CRNVisualizer(hg: Any)[source]#
Bases:
objectPlotting helper for CRN-like objects.
- Provides two backends for graph drawings:
‘nx’ : NetworkX + Matplotlib (default, prior behavior)
‘gv’ : Graphviz (dot/neato/sfdp…)
Stoichiometry heatmap stays Matplotlib-based.
- Parameters:
hg (Any) – A CRN-like object exposing: - species: Set[str] - edges: Dict[str, edge] where edge has .rule, .reactants{str->int}, .products{str->int} - to_bipartite(integer_ids=…, include_stoich=…): nx.DiGraph - incidence_matrix(): (species, edges, mapping) - get_edge(eid): edge
- bip(*, backend: str = 'nx', species_prefix: str = 'S:', reaction_prefix: str = 'R:', include_stoich: bool = True, title: str | None = None, save: str | None = None, show: bool = True, figsize: Tuple[float, float] = (10, 6), species_color: str = '#4C72B0', reaction_color: str = '#DD8452', edge_label_fontsize: int = 9, node_label_fontsize: int = 10, integer_ids: bool = True, species_fill: str = '#4C72B0', reaction_fill: str = '#DD8452', species_fontcolor: str = 'white', reaction_fontcolor: str = 'white', gv_graph_attr: Dict[str, str] | None = None, gv_node_attr: Dict[str, str] | None = None, gv_edge_attr: Dict[str, str] | None = None)[source]#
Bipartite plot (species left, reactions right).
- Parameters:
backend (str) – ‘nx’ (NetworkX) or ‘gv’.
- Returns:
For backend=’nx’ -> (fig, ax); for ‘gv’ -> Digraph
- crn(*, backend: str = 'nx', species_prefix: str = 'S:', reaction_prefix: str = 'R:', include_stoich: bool = True, title: str | None = None, save: str | None = None, show: bool = True, figsize: Tuple[float, float] = (8, 6), species_color: str = '#4C72B0', reaction_color: str = '#DD8452', edge_label_fontsize: int = 9, node_label_fontsize: int = 10, integer_ids: bool = True, species_fill: str = '#4C72B0', reaction_fill: str = '#DD8452', species_fontcolor: str = 'white', reaction_fontcolor: str = 'white', gv_engine: str = 'sfdp', gv_graph_attr: Dict[str, str] | None = None, gv_node_attr: Dict[str, str] | None = None, gv_edge_attr: Dict[str, str] | None = None)[source]#
General CRN graph plot (spring layout in NX; chosen engine in Graphviz).
- Parameters:
backend (str) – ‘nx’ (NetworkX) or ‘gv’.
- Returns:
For backend=’nx’ -> (fig, ax); for ‘gv’ -> Digraph
- species(*, backend: str = 'nx', title: str | None = None, save: str | None = None, show: bool = True, include_min_stoich: bool = True, include_rules: bool = True, figsize: Tuple[float, float] = (7.5, 6), node_color: str = '#4C72B0', node_label_fontsize: int = 10, edge_label_fontsize: int = 9, layout: str = 'spring', gv_engine: str = 'sfdp', gv_node_fill: str = '#4C72B0', gv_node_fontcolor: str = 'white', gv_graph_attr: Dict[str, str] | None = None, gv_node_attr: Dict[str, str] | None = None, gv_edge_attr: Dict[str, str] | None = None)[source]#
Species→species collapsed graph.
Uses hg.to_species_graph() if available. Otherwise, it builds the collapsed graph by connecting each reactant to each product for every reaction.
- Parameters:
backend – ‘nx’ (NetworkX) or ‘gv’ (Graphviz).
- Returns:
For ‘nx’ -> (fig, ax); for ‘gv’ -> Digraph
- synkit.Vis.crn_vis.plot_bip(hg: Any, **kwargs)[source]#
Bipartite plot. Pass backend=’nx’ or backend=’gv’.
- synkit.Vis.crn_vis.plot_crn(hg: Any, **kwargs)[source]#
General CRN plot. Pass backend=’nx’ or backend=’gv’.
- synkit.Vis.crn_vis.plot_stoich(hg: Any, **kwargs)[source]#
Stoichiometric matrix heatmap (Matplotlib).
- class synkit.Vis.embedding.Embedding(cache_dir: str = './cachedir', verbose: int = 0, custom_tsne_params: Dict | None = None)[source]#
Bases:
object- property cache: Any#
Decorator for caching the compute_tsne function.
- Returns:
Callable: Cached function.
- compute_tsne(X: ndarray, cache: bool = True) ndarray[source]#
Computes or retrieves the t-SNE embedding from cache.
- Parameters:
X (np.ndarray): High-dimensional data points. cache (bool): Determines whether to use caching for the computation.
- Returns:
np.ndarray: The 2-dimensional t-SNE embedding of the data.