HMO documentation

Hückel Molecule Drawer & Viewer (HMO Tool)

This program provides a complete graphical interface for the interactive construction of (planar π-conjugated) molecules and the analysis of their molecular orbitals using the Hückel model. It allows the user to draw the molecular skeleton on a grid, select atom types (C·, N:, O·, etc.), add bonds, and perform a full Hückel analysis that includes:

  • generation of the Hückel matrix,

  • solving for orbital energies (eigenvalues),

  • calculating the molecular orbital coefficients (eigenvectors),

  • determining π-charges on atoms and π-bond orders,

  • computing global descriptors: total energy, HOMO-LUMO gap, hardness, chemical potential, etc.

Main features:

  • Manual construction of the molecular skeleton (adding/removing atoms and bonds),

  • Saving and loading the sigma skeleton of molecules (.hmo format),

  • Running Hückel analysis and directly visualizing results,

  • Exporting complete results (MO coefficients, π-charges, bond orders, descriptors) to Excel or PDF,

  • Graphical visualization of molecular orbitals (shapes and energies) in a dedicated window.

Display organization (Tkinter-based):

The program is built with the Tkinter library, which manages all graphical interfaces:

  1. Molecule Drawer (main window):
    • Handled by the MoleculeDrawer class, this main window (based on Tk()) contains:

    • Left section: a Canvas where the user builds the molecule (grid, atoms, bonds),

    • Right section: a toolbar with buttons for main actions (run analysis, save/load molecule,

      access visualizations, export data).

  2. HMO Viewer (dedicated MO visualization window):
    • Instantiated by the HMOViewer class when the user clicks the visualization button.

    • This secondary window uses Toplevel to open independently.

    • It displays:
      • an energy diagram (MO energy levels),

      • graphical representations of occupied and virtual orbitals,

      • a miniature view of the molecule to show its overall topology.

  3. Numerical Results Window:
    • Managed by the ResultsViewer class and also opened via Toplevel.

    • Displays:
      • molecular orbital coefficients in a table format,

      • π-charges, π-bond orders,

      • global descriptors (total energy, HOMO-LUMO gap, etc.).

Usage:

The user starts by constructing the molecule, then runs the Hückel analysis. After computation, results can be explored numerically (ResultsViewer window) and graphically (HMOViewer window), and exported. The graphical visualization allows easy exploration of molecular orbitals and their energy levels.

Notes:

  • Most graphical interactions (atom placement, bond drawing) are done with the mouse, with keyboard shortcuts for efficiency.

  • The program is structured around the main classes: MoleculeDrawer (main interface), HMOViewer (MO visualization), ResultsViewer (numerical results), and Node (management of individual atoms).

  • Hückel parameters and some visulization settings are defined in the HuckelParameters class

  • Visualization and layout parameters for the HMOViewer interface are provided by the HMOViewerParameters class

class hmo.HMO.HMOViewer(master, df_MOs, df_atoms, df_bonds, df_descriptors, project_name)

GUI application for visualizing Hückel Molecular Orbitals (MOs) and their energy diagrams.

This class provides a graphical interface to render the molecular structure and the associated energy levels of the molecular orbitals (occupied and virtual). It allows the user to explore the molecule’s π-system, display orbital diagrams, and save visualizations.

Parameters:
  • master (tk.Toplevel or tk.Tk) – The parent Tkinter window that contains the interface.

  • df_MOs (pd.DataFrame) – DataFrame containing molecular orbital coefficients for each atom in the system.

  • df_atoms (pd.DataFrame) – DataFrame containing atomic positions, indices, and element types.

  • df_bonds (pd.DataFrame) – DataFrame specifying bonds between atoms (indices and bond order).

  • df_descriptors (pd.DataFrame) – DataFrame containing computed molecular descriptors (e.g., number of π electrons, symmetry).

  • project_name (str) – Name of the current project, used in window titles and when saving files.

canvas

The canvas widget where the molecule and energy levels are drawn.

Type:

tk.Canvas

scale_factor

Factor used to scale the molecular diagram to fit the canvas.

Type:

float

atom_radius

Radius in pixels for drawing atom circles.

Type:

int

bond_width

Width of bond lines in pixels.

Type:

int

energy_levels

List of orbital energies for plotting the energy diagram.

Type:

list of floats

display_default_homo_lumo()
display_om(idx, occupied=True)

Affiche la représentation d’une OM dans le cadre approprié.

draw_energy_levels()
draw_energy_scale_and_descriptors(min_e, max_e, scale, energies_sorted)

Dessine l’échelle énergétique, les repères horizontaux et les descripteurs sous le diagramme.

draw_layout()
draw_skeleton_overview(x0, y0, width, height)

Dessine la molécule complète dans une petite fenêtre sous le diagramme d’OM.

load_images()
on_escape(event)
on_level_click(idx)
prepare_data()
refresh_MOs()

Redessine l’OM actuellement affichée (HOMO & LUMO).

refresh_skeleton()

Efface et redessine le squelette global.

save_canvas_as_png()

Sauvegarde le canvas entier en PNG haute qualité.

toggle_skeleton()

Active/désactive le mode skeleton only.

class hmo.HMO.MoleculeDrawer(master)

GUI application for drawing molecules and performing Hückel Molecular Orbital (HMO) calculations and analysis.

The MoleculeDrawer class provides an interactive graphical interface that allows the user to build a molecular structure by placing atoms and bonds on a grid. It supports the customization of atom types, and includes functionalities to save/load molecules, undo/redo actions, and erase atoms or bonds.

Once a molecule is built, the tool can run a Hückel analysis to compute molecular orbital energies, coefficients, π-charges, and π-bond orders. Results are displayed numerically and graphically, with options to save data as Excel files or images.

Parameters:

master (tk.Tk or tk.Toplevel) – The root window or parent window that holds the GUI.

nodes

The list of atoms (nodes) in the current molecule.

Type:

list of Node

bonds

The list of bonds, each defined by a tuple of two node indices.

Type:

list of tuple

undo_stack

A stack to store the history of molecule states for undo functionality.

Type:

list

redo_stack

A stack to store undone actions for redo functionality.

Type:

list

df

The main DataFrame containing molecular orbital coefficients.

Type:

pd.DataFrame or None

df_atoms

DataFrame containing atom types, coordinates, and π charges.

Type:

pd.DataFrame or None

df_bonds

DataFrame listing bonds between atoms.

Type:

pd.DataFrame or None

df_summary

DataFrame summarizing molecular descriptors (energy, hardness, gap, etc.).

Type:

pd.DataFrame or None

project_name

The user-defined name of the current project.

Type:

str or None

safe_project_name

A sanitized version of the project name (safe for filenames).

Type:

str or None

mo_viewer_window

The window displaying molecular orbital visualizations.

Type:

tk.Toplevel or None

om_window

The window showing numerical molecular orbital data.

Type:

tk.Toplevel or None

Notes

  • The interface includes a toolbar with buttons for running the Hückel analysis, saving/loading molecules, exporting results, and accessing help/about information.

  • Huckel parameters (α and β) are set by default to -11.0 and -2.7 but can be modified in the code.

  • The program supports exporting results as .xlsx files (multi-sheet Excel) and visual representations as .png or .pdf.

  • The tool can gracefully handle molecule resizing and grid alignment, making drawing easy.

Examples

>>> root = tk.Tk()
>>> app = MoleculeDrawer(root)
>>> root.mainloop()
apply_scale(x, y)
bind_shortcuts()
build_dataframes()

Builds and updates key DataFrames summarizing the molecule’s structural and electronic properties.

This method generates and assigns four main DataFrames: 1. df_bond_orders_matrix: A symmetric matrix showing π-bond orders between all atom pairs. 2. df_atoms: A table containing atom indices, types, positions (grid units), π charges, and colors. 3. df_bonds: A table listing all bonds between atoms with atom labels. 4. df_summary: A summary table of molecular descriptors, such as total π-electron energy, HOMO-LUMO gap, chemical potential, hardness, softness, and electrophilicity.

The resulting DataFrames are stored as attributes for export or display in other parts of the application.

Returns:

  • None

  • (The method updates internal attributes (df_bond_orders_matrix, df_atoms, df_bonds, and df_summary))

Notes

  • Atom labels are formatted as ‘<AtomType><Index>’ (e.g., ‘C·1’, ‘O:2’).

  • Bond orders are rounded to 3 decimal places.

  • π charges are computed from Hückel analysis results and rounded to 3 decimal places.

  • The summary DataFrame expresses all energy-related descriptors in units of β (or multiples/fractions thereof).

  • The method assumes that the Hückel analysis (and charge/bond order computation) has already been performed.

Example

>>> mol = MoleculeDrawer(root)
>>> mol.build_dataframes()

The following attributes are now available: - mol.df_bond_orders_matrix - mol.df_atoms - mol.df_bonds - mol.df_summary

build_huckel_matrix(alpha=-11.0, beta=-2.7)

Constructs the Hückel matrix (Hamiltonian) for the current molecular graph.

This method builds the square matrix H of size n×n, where n is the number of atoms (nodes) in the molecule. The diagonal elements (alpha) represent Coulomb integrals, while the off-diagonal elements (beta) represent resonance integrals between bonded atoms.

Atomic parameters are retrieved from the Huckel_atomic_parameters dictionary using the atom’s type (e.g., ‘C’, ‘N’, etc.), and bond parameters are retrieved from the Huckel_kXY_parameters dictionary to handle heteroatomic systems with scaling factors.

Parameters:
  • alpha (float, optional) – The Coulomb integral (diagonal value), default is -11.0.

  • beta (float, optional) – The resonance integral (off-diagonal value), default is -2.7.

Returns:

  • np.ndarray – The n×n Hückel matrix, where n is the number of atoms in the molecule.

  • Error Handling

  • ————–

  • - If an atom type is not recognized or has no defined alpha parameter, an error message – is shown and the program exits.

  • - If a bond type is not recognized or has no defined beta parameter, an error message – is shown and the program exits.

Notes

  • The Huckel_atomic_parameters dictionary must provide a valid alpha_expr for each atom type involved in the molecule.

  • The Huckel_kXY_parameters dictionary must provide scaling factors for bonds between different atom types (e.g., C-N, C-O).

  • The method evaluates alpha expressions using the self.evaluate() method, which substitutes the global alpha and beta values.

Example

>>> H = drawer.build_huckel_matrix(alpha=-11.0, beta=-2.7)
change_atom_type(idx, new_type)
clear()
compute_charges_and_bond_orders(eigvecs, occupation_dict)
count_bonds(idx)
create_button(icon, command, tooltip)
create_toolbar()
delete_node(idx)
draw_grid()
evaluate(expr, alpha, beta)
find_bond(x, y)
find_node(x, y)
find_node_by_coords(x_grid, y_grid)
left_click(event)
load_icons()
load_molecule()
mouse_drag(event)
mouse_motion(event)
mouse_release(event)
node_exists_at(x, y)
on_run_huckel()
props(eigvals, occupation_dict, sorted_indices, alpha, beta)
quit_program()
redo()
redraw()
resize_canvas(event)
right_click(event)
run_huckel_analysis()

Executes the full Hückel Molecular Orbital (HMO) analysis for the current molecule.

This method performs the following steps: 1. Builds the Hückel matrix using build_huckel_matrix. 2. Solves for molecular orbital energies and coefficients (eigenvalues and eigenvectors). 3. Counts the total number of π-electrons based on atomic types. 4. Computes the occupation numbers for each molecular orbital, handling degeneracies. 5. Calculates π-electron charges and π-bond orders using the eigenvectors and occupations. 6. Updates molecular properties and builds a DataFrame of orbital coefficients for display.

The analysis assumes default Hückel parameters (alpha = -11.0, beta = -2.7) unless specified otherwise when building the matrix.

Notes

  • Atoms and bonds are validated to ensure parameters exist in the Huckel parameter dictionaries.

  • If any atom or bond type is unknown, an error message is displayed and the program exits.

  • Degenerate orbitals are handled by grouping them within a numerical tolerance (1e-5 by default).

Attributes Updated

dfpd.DataFrame

A DataFrame showing molecular orbital coefficients, sorted by energy levels.

chargeslist of float

List of π-electron charges on each atom.

bond_ordersdict

Dictionary with keys as (i, j) tuples (atom indices) and values as bond orders.

total_pi_electronsint

The total number of π-electrons in the molecule.

alpha_valuefloat

The alpha value used for the current Hückel analysis.

beta_valuefloat

The beta value used for the current Hückel analysis.

Error Handling

  • Unknown atom types or missing parameters in Huckel_atomic_parameters trigger an error.

  • Unknown bond types or missing parameters in Huckel_kXY_parameters also trigger an error.

  • In both cases, a messagebox error is shown, and the program exits gracefully.

Example

>>> MoleculeDrawer.run_huckel_analysis()
sanitize_filename(name)
save_data()
save_dataframe_as_pdf(win)
save_dataframe_as_xlsx(win)
save_molecule()
save_state()
show_about()
show_dataframe_in_window()
show_numerical_data()
snap_to_grid(x, y)
toggle_eraser()
undo()
class hmo.HMO.Node(x, y, atom_type='C·')

A class representing an atom (node) in the molecular graph.

Each Node object stores information about its position in the molecular diagram, its chemical element type (e.g., C, N, O), and its π-charge (from Hückel analysis).

Parameters:
  • canvas (tk.Canvas) – The canvas on which the node (atom) will be drawn.

  • x (int) – The x-coordinate of the node in the canvas (in pixels).

  • y (int) – The y-coordinate of the node in the canvas (in pixels).

  • radius (int, optional) – Radius of the circle representing the atom (default is 20 pixels).

  • atom_type (str, optional) – Chemical element symbol for the node (default is ‘C’).

  • color (str, optional) – Fill color for the node (default is ‘white’).

x

X-coordinate of the node center.

Type:

int

y

Y-coordinate of the node center.

Type:

int

radius

Radius of the circle representing the atom.

Type:

int

atom_type

Chemical element symbol (e.g., ‘C’, ‘N’, ‘O’).

Type:

str

color

Fill color of the atom.

Type:

str

circle

ID of the oval shape on the canvas (for drawing reference).

Type:

int

label

ID of the text label on the canvas (for element symbol).

Type:

int

pi_charge

The π-electron charge on the atom, computed after Hückel analysis.

Type:

float or None

draw()

Draws the node (circle + label) on the canvas.

update_label()

Updates the displayed label based on the atom type and charge.

is_within(x, y)

Checks if a given (x, y) coordinate is within the node’s radius.

move_to(new_x, new_y)

Moves the node to a new position on the canvas.

set_pi_charge(charge)

Sets the π-charge for the atom and updates the label accordingly.

class hmo.HMO.ToolTip(widget, text='widget info')

A class to create and manage tooltips for Tkinter widgets.

This class attaches a tooltip (a small pop-up window displaying text) to any Tkinter widget. The tooltip appears when the mouse hovers over the widget and disappears when the mouse leaves.

The tooltip text is rendered using a custom Open Sans Regular font loaded from a TrueType Font (TTF) file located at ‘Fonts/OpenSans/static/OpenSans-Regular.ttf’. This ensures a consistent and modern look across different platforms and display environments.

Parameters:
  • widget (tk.Widget) – The Tkinter widget to which the tooltip will be attached.

  • text (str) – The text content to display in the tooltip.

widget

The widget associated with the tooltip.

Type:

tk.Widget

text

The message displayed when hovering over the widget.

Type:

str

tooltip_window

The pop-up window that displays the tooltip text (created when the mouse enters the widget).

Type:

tk.Toplevel or None

OpenSansReg_font

The custom font object used to render the tooltip text, loaded from OpenSans-Regular.ttf.

Type:

tkFont.Font

Main Methods
-------
show_tooltip(event=None)

Creates and displays the tooltip near the mouse cursor using the Open Sans font.

hide_tooltip(event=None)

Destroys the tooltip window when the mouse leaves the widget.

enter(event=None)
hidetip()
leave(event=None)
motion(event=None)
schedule()
showtip(event=None)
unschedule()
class hmo.HMO.HMOViewerParameters

Visualization and layout parameters for the HMOViewer interface.

This class centralizes all GUI layout settings, dimensions, and rendering parameters used in the molecular orbital (MO) diagram viewer. It includes frame sizes and positions for HOMO/LUMO, diagram coordinates, canvas size, and parameters for drawing molecular orbitals (lobes, bonds).

FRAME_WIDTH

Width (in pixels) of each MO visualization frame (for HOMO/LUMO).

Type:

int

FRAME_HEIGHT

Height (in pixels) of each MO visualization frame.

Type:

int

FRAME_LUMO_X

X-coordinate (in pixels) of the LUMO frame’s top-left corner.

Type:

int

FRAME_LUMO_Y

Y-coordinate (in pixels) of the LUMO frame’s top-left corner.

Type:

int

FRAME_HOMO_X

X-coordinate of the HOMO frame’s top-left corner (aligned with LUMO frame).

Type:

int

FRAME_HOMO_Y

Y-coordinate of the HOMO frame’s top-left corner (placed below LUMO with spacing).

Type:

int

BOTTOM_OF_HOMO

Y-coordinate of the bottom of the HOMO frame.

Type:

int

MARGIN_BOTTOM

Margin (in pixels) below the HOMO frame in the canvas.

Type:

int

CANVAS_HEIGHT

Total height (in pixels) of the drawing canvas, computed dynamically.

Type:

int

CANVAS_WIDTH

Total width (in pixels) of the drawing canvas.

Type:

int

DIAG_X

X-position (in pixels) for the center of the MO energy diagram (left side).

Type:

int

DIAG_Y_TOP

Top Y-coordinate of the MO energy diagram.

Type:

int

DIAG_Y_BOTTOM

Bottom Y-coordinate of the MO energy diagram.

Type:

int

DIAG_WIDTH_UNIT

Width of a unit interval in the diagram (used for scaling purposes).

Type:

int

SHRINK_FACTOR

Scaling factor applied to lobe sizes to prevent overlap.

Type:

float

LOBE_OFFSET

Pixel offset for lobe positioning when rendering orbitals.

Type:

int

TARGET_BOND_PX

Target length (in pixels) for bond drawings between atoms.

Type:

int

Path2Imgs

Path object pointing to the directory where design images or assets are stored.

Type:

Path

Notes

  • The canvas is designed to hold both HOMO and LUMO visualizations side by side with appropriate margins.

  • The MO energy diagram is drawn to the left of the MO frames for visual reference.

  • The SHRINK_FACTOR and LOBE_OFFSET parameters allow fine control of orbital lobe rendering for clarity.

  • The Path2Imgs attribute should point to a valid directory containing any additional images used in the visualization (e.g., backgrounds, decorations).

Example

>>> HMOViewerParameters.FRAME_WIDTH
700
>>> HMOViewerParameters.Path2Imgs
PosixPath('DesignMOdiagram')
class hmo.HMO.HuckelParameters

Container for Huckel model parameters and visualization settings.

This class centralizes all constants and mappings used for building and analyzing molecules within the Hückel framework. It includes atomic and bond parameters, grid and drawing settings, and atom display options for the GUI.

GRID_SIZE

The size of one grid unit (in pixels) for positioning atoms in the molecular canvas.

Type:

int

ATOM_RADIUS

The radius (in pixels) of the circle used to draw an atom on the canvas.

Type:

int

HIGHLIGHT_RADIUS

The radius (in pixels) of the highlight circle used when selecting atoms or bonds.

Type:

int

ATOM_COLORS

A dictionary mapping atom type strings (e.g., ‘C·’, ‘O:’, ‘N+·’) to their display color in hex code or standard color names.

Type:

dict

ATOM_OPTIONS

The list of atom types available for selection and drawing in the molecule builder.

Type:

list of str

Huckel_atomic_parameters
A dictionary mapping atom types to their Hückel parameters, each of which is a dictionary with:
  • ‘alpha_expr’: a string expression for the Coulomb integral α (often depends on β),

  • ‘Fx’: the index of free valence (reactivity index) representing the reactivity of the center,

  • ‘n_pi’: the number of π-electrons contributed by the atom.

Type:

dict

Huckel_kXY_parameters

A nested dictionary mapping pairs of atom types to their interaction energies (float), representing the interaction between two 2p atomic orbitals (used for the β term in the Hückel matrix).

Type:

dict

Notes

  • The atom types include common π-conjugated atoms and heteroatoms (e.g., C·, N·, N:, O·, etc.).

  • The ▯ symbol (e.g., ‘B▯’) indicates that the atom holds a π-vacancy (e.g., boron with an empty p-orbital).

  • A colon (:) after the atom type (e.g., ‘O:’, ‘N:’) denotes that the atom provides a lone pair into the π system (typically 2 π-electrons).

  • A dot (·) after the atom type (e.g., ‘C·’, ‘O·’, ‘N·’) indicates the atom provides a single π-electron to the system.

  • The ‘Fx’ parameter (index of free valence) represents the theoretical reactivity of the atom in the π system and can be used as a qualitative indicator of chemical reactivity.

  • The Huckel_kXY_parameters dictionary does not hold mere bond scaling factors, but rather contains interaction energies between two 2p atomic orbitals, which define the off-diagonal β terms in the Hückel Hamiltonian.

  • The alpha_expr parameter (Coulomb integral) gives the energy of an electron in a 2p atomic orbital of a given atom.

  • Typically, α and β are negative values. For carbon atoms, it is common to use:
    • α_C ≈ -11.0 eV (Coulomb integral / 2p orbital energy),

    • β_CC ≈ -2.7 eV (interaction between two carbon 2p orbitals).

  • For heteroatoms (atoms other than carbon), the parameters α_X and β_XY are expressed as functions of α_C and β_C, enabling a transferability of parameters while keeping carbon as the reference.

Example

>>> # Access a color for carbon
>>> HuckelParameters.ATOM_COLORS['C·']
'#909090'
>>> # Access π-electron count for nitrogen (lone pair donor)
>>> HuckelParameters.Huckel_atomic_parameters['N:']['n_pi']
2
>>> # Access 2p–2p interaction energy between C and O
>>> HuckelParameters.Huckel_kXY_parameters['C·']['O·']
1.06