pyphyschemtools package

The pyphyschemtools library provides a comprehensive suite of utilities for Physical Chemistry, ranging from spectroscopic unit management to kinetic modeling and cheminformatics.

pyphyschemtools.get_ppct_data(file: str, main_folder: str = 'data_examples') Path

Retrieves the absolute path to a pyphyschemtools resource. Compatible with Python 3.11+ using importlib.resources. Works across all platforms (Windows, Linux, MacOS) and Google Colab.

Parameters:
  • file (str) – The path and name of the file (e.g., β€œMolecules/betaCD-closed.xyz”).

  • main_folder (str) – The resource subfolder inside the package (defaults to β€œdata_examples”).

Returns:

A pathlib.Path object pointing to the absolute location of the file.

Return type:

Path

pyphyschemtools.Chem3D module

class pyphyschemtools.Chem3D.XYZData(symbols, positions)

Bases: object

Object containing molecular coordinates and symbols extracted by molView. Allows for geometric calculations without reloading data.

get_bounding_sphere(include_vdw=True, scale=1.0)

Calculates the center and radius of the bounding sphere using ASE. scale: multiplication factor (e.g., 0.6 to match a reduced CPK style).

get_cage_volume(grid_spacing=0.5, return_spheres=False)

Calculates the internal cavity volume of a molecular cage using CageCavityCalc.

This method interfaces with the CageCavityCalc library by generating a temporary PDB file of the current structure. It can also retrieve the coordinates of the β€˜dummy atoms’ (points) that fill the detected void.

Parameters:
  • grid_spacing (float, optional) – The resolution of the grid used for volume integration in Γ…. Smaller values provide higher precision (default: 0.5).

  • return_spheres (bool, optional) – If True, returns both the volume and an ase.Atoms object containing the dummy atoms representing the cavity (default: False).

Returns:

  • volume (float or None) – The calculated cavity volume in Γ…Β³. Returns None if the calculation fails.

  • cavity_atoms (ase.Atoms, optional) – Returned only if return_spheres is True. An ASE Atoms object representing the internal void space.

get_cavity_dimensions(cavity_atoms)

Calculates the principal dimensions (Length, Width, Height) of the cavity points.

This method uses Principal Component Analysis (PCA) to find the natural axes of the cavity, making it independent of the molecule’s orientation. Percentiles are used instead of absolute Max-Min to filter out potential outliers or β€˜leaking’ points at the openings.

Parameters:

cavity_atoms (ase.Atoms) – The Atoms object containing the β€˜dummy atoms’ generated by the cavity calculation.

Returns:

The dimensions (L, W, H) sorted from largest to smallest.

Return type:

tuple (float, float, float)

get_center_of_geometry()

Calculates the arithmetic mean of the atomic positions (Centroid).

get_center_of_mass()
class pyphyschemtools.Chem3D.molView(mol, source=None, style='bs', displayHbonds=True, cpk_scale=0.6, w=600, h=400, supercell=(1, 1, 1), display_now=True, detect_BondOrders=True, viewer=True, zoom=None)

Bases: object

Initializes a molecular/crystal viewer and coordinate extractor.

This class acts as a bridge between various molecular data sources and the py3Dmol interactive viewer. It can operate in β€˜Full’ mode (display + analysis) or β€˜Headless’ mode (analysis only) by toggling the viewer parameter.

The class automatically extracts geometric data into the self.data attribute (an XYZData object), allowing for volume, dimension, and cavity calculations.

Display molecular and crystal structures in py3Dmol from various sources:

  • XYZ/PDB/CIF local files

  • XYZ-format string

  • PubChem CID

  • ASE Atoms object

  • COD ID

  • RSCB PDB ID

Three visualization styles are available:

  • β€˜bs’ : ball-and-stick (default)

  • β€˜cpk’ : CPK space-filling spheres (with adjustable size)

  • β€˜cartoon’: protein backbone representation

Upon creation, an interactive 3D viewer is shown directly in a Jupyter notebook cell, unless the headless viewer parameter is set to False.

Parameters:
  • mol (str or ase.Atoms) –

    The molecular structure to visualize.

    • If source=’file’, this should be a path to a structure file (XYZ, PDB, etc.)

    • If source=’mol’, this should be a string containing the structure (XYZ, PDB…)

    • If source=’cif’, this should be a cif file (string)

    • If source=’cid’, this should be a PubChem CID (string or int)

    • If source=’rscb’, this should be a RSCB PDB ID (string)

    • If source=’cod’, this should be a COD ID (string)

    • If source=’ase’, this should be an ase.Atoms object

  • source ({'file', 'mol', 'cif', 'cid', 'rscb', 'ase'}, optional) – The type of the input mol (default: β€˜file’).

  • style ({'bs', 'cpk', 'cartoon'}, optional) –

    Visualization style (default: β€˜bs’).

    • ’bs’ β†’ ball-and-stick

    • ’cpk’ β†’ CPK space-filling spheres

    • ’cartoon’ β†’ draws a smooth tube or ribbon through the protein backbone

      (default for pdb structures)

  • displayHbonds (plots hydrogen bonds (default: True))

  • cpk_scale (float, optional) – Overall scaling factor for sphere size in CPK style (default: 0.5). Ignored when style=’bs’.

  • supercell (tuple of int) – Repetition of the unit cell (na, nb, nc). Default is (1, 1, 1).

  • w (int, optional) – Width of the viewer in pixels (default: 600).

  • h (int, optional) – Height of the viewer in pixels (default: 400).

  • detect_BondOrders (bool, optional) – If True (default) and input is XYZ, uses RDKit to perceive connectivity and bond orders (detects double/triple bonds). Requires the rdkit library. If False, fallback to standard 3Dmol distance-based single bonds.

  • display_now (bool, optional) – If True (default), renders the molecule immediately. Set to False to prevent immediate display when you plan to call further visualization methods provided by the molView class

  • viewer (bool, optional) – If True (default), initializes the py3Dmol engine and prepares the 3D model. If False, operates in β€˜headless’ mode: only geometric data is processed for analysis (volume, CM, etc.), saving significant memory for high-throughput processing.

  • zoom (None, optional) – scaling factor

data

Container for atomic symbols and positions, used for geometric analysis.

Type:

XYZData or None

v

The 3Dmol.js viewer instance (None if viewer=False).

Type:

py3Dmol.view or None

Examples

>>> molView("molecule.xyz", source="file")
>>> molView(xyz_string, source="mol")
>>> molView(2244, source="cid")   # PubChem aspirin
>>> from ase.build import molecule
>>> molView(molecule("H2O"), source="ase")
>>> molView.view_grid([2244, 2519, 702], n_cols=3, source='cid', style='bs')
>>> molView.view_grid(xyzFiles, n_cols=3, source='file', style='bs', titles=titles, w=500, sync=True)
>>> # Headless mode for high-throughput volume calculations
>>> mv = molView("cage.xyz", viewer=False)
>>> vol = mv.data.get_cage_volume()
analyze_symmetry(tolerance=0.3, angle_tolerance=5.0, eigen_tolerance=0.01, matrix_tolerance=0.1)

Comprehensive symmetry analysis using Pymatgen.

Parameters:
  • tolerance (float) – Distance tolerance in Γ… (symprec for crystals). Default 0.3.

  • angle_tolerance (float) – Angular tolerance in degrees (Crystals only). Default 5.0.

  • eigen_tolerance (float) – Inertia tensor eigenvalue tolerance (Molecules only). Default 0.01.

  • matrix_tolerance (float) – Symmetry operation matrix tolerance (Molecules only). Default 0.1.

show_bounding_sphere(color='gray', opacity=0.2, scale=1.0)

Calculates and displays the VdW bounding sphere in one go.

show_cage_cavity(grid_spacing=0.5, color='cyan', opacity=0.5)

Calculates cavity with CageCavityCalc and displays it as a single model.

classmethod view_grid(mol_list, n_cols=3, titles=None, **kwargs)

Displays a list of molecular structures in an interactive n_rows x n_cols grid.

This method uses ipywidgets.GridspecLayout to organize multiple 3D viewers into a clean matrix. It automatically calculates the required number of rows based on the length of the input list.

Parameters:
  • mol_list (list) – A list containing the molecular data to visualize. Elements should match the expected β€˜mol’ input for the class (paths, CIDs, strings, etc.).

  • n_cols (int, optional) – Number of columns in the grid (default: 3).

  • titles (list of str, optional) – Custom labels for each cell. If None, the string representation of the β€˜mol’ input is used as the title.

  • **kwargs (dict) – Additional arguments passed to the molView constructor: - source : {β€˜file’, β€˜mol’, β€˜cif’, β€˜cid’, β€˜rscb’, β€˜ase’} - style : {β€˜bs’, β€˜cpk’, β€˜cartoon’} - displayHbonds : plots hydrogen bonds (default: True) - w : width of each individual viewer in pixels (default: 300) - h : height of each individual viewer in pixels (default: 300) - supercell : tuple (na, nb, nc) for crystal structures - cpk_scale : scaling factor for space-filling spheres

Returns:

A widget object containing the grid of molecular viewers.

Return type:

ipywidgets.GridspecLayout

Examples

>>> files = ["mol1.xyz", "mol2.xyz", "mol3.xyz", "mol4.xyz"]
>>> labels = ["Reactant", "TS", "Intermediate", "Product"]
>>> molView.view_grid(files, n_cols=2, titles=labels, source='file', w=400)

pyphyschemtools.ML module

pyphyschemtools.ML.categorizeY_2ohe(Ctot, y1, y2)

one-hot-encodes a pandas column of categorical data

input: - Ctot is the reference pandas column, necessary to find all unique categories in this column - y1 and y2 are the actual pandas column that will be categorized. y1 and y2 are supposed to be the ytest and ytrain subsets of Ctot output: - y1ohe and y2ohe are the numpy arrays returned by this routine

pyphyschemtools.ML.y2c(mc2i, y)

pyphyschemtools.PeriodicTable module

class pyphyschemtools.PeriodicTable.TableauPeriodique

Bases: object

Classe permettant de manipuler et d’afficher les donnΓ©es du tableau pΓ©riodique.

Cette classe utilise la bibliothΓ¨que β€˜mendeleev’ pour rΓ©cupΓ©rer les donnΓ©es chimiques et β€˜bokeh’ pour la visualisation interactive. Elle francise les noms et corrige certaines classifications de familles chimiques.

Initialise l’objet TableauPeriodique en chargeant les donnΓ©es de la bibliothΓ¨que mendeleev.

afficher()

Génère et affiche le tableau périodique interactif dans un notebook Jupyter.

Le tableau permet de visualiser les propriΓ©tΓ©s au survol de la souris.

nomsFr = ['HydrogΓ¨ne', 'HΓ©lium', 'Lithium', 'BΓ©ryllium', 'Bore', 'Carbone', 'Azote', 'OxygΓ¨ne', 'Fluor', 'NΓ©on', 'Sodium', 'MagnΓ©sium', 'Aluminium', 'Silicium', 'Phosphore', 'Soufre', 'Chlore', 'Argon', 'Potassium', 'Calcium', 'Scandium', 'Titane', 'Vanadium', 'Chrome', 'ManganΓ¨se', 'Fer', 'Cobalt', 'Nickel', 'Cuivre', 'Zinc', 'Gallium', 'Germanium', 'Arsenic', 'SΓ©lΓ©nium', 'Brome', 'Krypton', 'Rubidium', 'Strontium', 'Yttrium', 'Zirconium', 'Niobium', 'MolybdΓ¨ne', 'TechnΓ©tium', 'RuthΓ©nium', 'Rhodium', 'Palladium', 'Argent', 'Cadmium', 'Indium', 'Γ‰tain', 'Antimoine', 'Tellure', 'Iode', 'XΓ©non', 'CΓ©sium', 'Baryum', 'Lanthane', 'CΓ©rium', 'PrasΓ©odyme', 'NΓ©odyme', 'PromΓ©thium', 'Samarium', 'Europium', 'Gadolinium', 'Terbium', 'Dysprosium', 'Holmium', 'Erbium', 'Thulium', 'Ytterbium', 'Lutetium', 'Hafnium', 'Tantale', 'TungstΓ¨ne', 'RhΓ©nium', 'Osmium', 'Iridium', 'Platine', 'Or', 'Mercure', 'Thallium', 'Plomb', 'Bismuth', 'Polonium', 'Astate', 'Radon', 'Francium', 'Radium', 'Actinium', 'Thorium', 'Protactinium', 'Uranium', 'Neptunium', 'Plutonium', 'Americium', 'Curium', 'Berkelium', 'Californium', 'Einsteinium', 'Fermium', 'Mendelevium', 'Nobelium', 'Lawrencium', 'Rutherfordium', 'Dubnium', 'Seaborgium', 'Bohrium', 'Hassium', 'Meitnerium', 'Darmstadtium', 'Roentgenium', 'Copernicium', 'Nihonium', 'Flerovium', 'Moscovium', 'Livermorium', 'Tennesse', 'Oganesson']
patch_elements()

Ce patch, appliquΓ© Γ  self.elements, créé par l’appel Γ  create_vis_dataframe(), va servir Γ  : - ajouter des informations en franΓ§ais : les noms des Γ©lΓ©ments et des sΓ©ries (familles) auxquelles ils appartiennent - retirer les Γ©lΓ©ments du groupe 12 de la famille des mΓ©taux de transition, qui est le choix CONTESTABLE par dΓ©faut de la bibliothΓ¨que mendeleev

input : elements est un dataframe pandas préalablement créé par la fonction create_vis_dataframe() de mendeleev.vis

output : elements avec deux nouvelles colonnes name_seriesFr et nom, qui contient dorΓ©navant les noms des Γ©lΓ©ments en franΓ§ais + correction des donnΓ©es name_series et series_id pour les Γ©lΓ©ments Zn, Cd, Hg, Cn + de nouvelles colonnes qui contiennent l’énergie de premiΓ¨re ionisation et les isotopes naturels

prop(elt_id)

Affiche les propriΓ©tΓ©s dΓ©taillΓ©es d’un Γ©lΓ©ment chimique.

Parameters:

elt_id (str ou int) – Symbole de l’élΓ©ment (ex: β€˜O’) ou numΓ©ro atomique (ex: 8).

trad = {'Actinides': 'Actinide', 'Alkali metals': 'MΓ©tal alcalin', 'Alkaline earth metals': 'MΓ©tal alcalino-terreux', 'Halogens': 'HalogΓ¨ne', 'Lanthanides': 'Lanthanide', 'Metalloids': 'MΓ©talloΓ―de', 'Metals': 'MΓ©tal', 'Noble gases': 'Gaz noble', 'Nonmetals': 'Non mΓ©tal', 'Poor metals': 'MΓ©tal pauvre', 'Transition metals': 'MΓ©tal de transition'}

pyphyschemtools.aithermo module

class pyphyschemtools.aithermo.aiThermo(folder_path=None, color_scales=None)

Bases: object

A class to handle thermodynamic surface stability analysis and visualization within the tools4pyPhysChem framework. Initialize the aiThermo object.

Parameters:
  • folder_path (str or Path) – Path to the working directory.

  • color_scales (list, optional) – List of plotly-compatible color scales.

ListOfStableSurfaceCompositions(vib)

Identify and list the relevant thermodynamic data files for the current analysis.

This method scans the working directory for data files matching specific naming conventions (TPcoverage or TPcoveragevib). It cross-references these with a local configuration file β€˜ListOfStableSurfaces.dat’ to extract surface names and legend labels.

Parameters:

vib (bool) – If True, filters for files including vibrational corrections (prefixed with vib_). If False, looks for standard thermodynamic data.

Returns:

A triplet containing: - file_paths (list of str): Absolute or relative paths to the .dat files. - names (list of str): Internal identifiers for each surface phase. - legends (list of str): LaTeX-formatted or plain text labels for graphical legends.

Return type:

tuple

Notes

  • The lists are returned in reverse order to ensure correct layering during 3D plotting.

  • Relies on β€˜ListOfStableSurfaces.dat’ existing in the folder_path.

plot_palette(angle=0, save_png=None)

Visualize the 1D color palette used for surface identification.

This method generates a horizontal bar of colors corresponding to the different surface phases defined in the instance. Each color is labeled with its numerical index, allowing for quick cross-referencing between the palette and the 3D surface plot.

Parameters:
  • angle (int, optional) – Rotation angle of the x-axis tick labels (indices). Defaults to 0.

  • save_png (str, optional) – Filename (including .png extension) to save the palette image to the working directory. Defaults to None (display only).

Returns:

Displays the plot using matplotlib.pyplot.show().

Return type:

None

Notes

  • Requires β€˜seaborn’ for the palplot generation.

  • If β€˜save_png’ is provided, the image is saved with a resolution of 300 DPI and a transparent background.

plot_surface(saveFig=None, vib=True, texLegend=False, xLegend=0.5, yLegend=0.4)

Generate an interactive 3D thermodynamic stability map using Plotly.

This method visualizes multiple Gibbs free energy surfaces as a function of Temperature (X) and Pressure (Y). It automatically handles log-scale transformations for the pressure axis and projects reference experimental conditions and phase boundaries onto the plot.

Parameters:
  • saveFig (str, optional) – The filename (without extension) to export the resulting plot as a PNG image. Defaults to None (no save).

  • vib (bool) – Whether to use vibration-corrected data. Defaults to True.

  • texLegend (bool) – If True, uses LaTeX legends extracted from the configuration file. Defaults to False.

  • xLegend (float) – Horizontal position of the legend box (0 to 1). Defaults to 0.5.

  • yLegend (float) – Vertical position of the legend box (0 to 1). Defaults to 0.4.

Returns:

An interactive widget containing

the 3D surfaces, experimental markers, and reference lines.

Return type:

plotly.graph_objects.FigureWidget

Workflow:
  1. Scans data files and parses Temperature/Pressure/Energy grids.

  2. Traces individual 3D surfaces with mapped color scales.

  3. Calculates and plots intersection boundaries between surface phases.

  4. Overlays experimental markers (e.g., specific T/P conditions).

  5. Optionally exports and crops the resulting image using Pillow.

pyphyschemtools.cheminformatics module

class pyphyschemtools.cheminformatics.easy_rdkit(smiles, canonical=True, lang='En')

Bases: object

A helper class to analyze and visualize molecules using RDKit. Provides tools for Lewis structure analysis and advanced 2D drawing. Initialize the molecule object from a SMILES string.

Parameters:
  • smiles (str) – The SMILES representation of the molecule.

  • canonical (bool) – If True, converts the SMILES to its canonical form to ensure consistent atom numbering and uniqueness.

  • lang (str) – Language for headers and messages of the Lewis analyzis(β€œEn” (default) or β€œFr”).

analyze_lewis()

Performs a Lewis structure analysis for each atom in the molecule. Calculates valence electrons, lone pairs, formal charges, and octet rule compliance.

Returns:

A table containing detailed Lewis electronic data per atom.

Return type:

pd.DataFrame

analyze_stereochemistry()

Identifies chiral centers and stereogenic double bonds. Returns a dictionary with counts and specific assignments.

property descriptors

Compute and return a dictionary of key molecular descriptors.

static draw_consistent_svg(smiles_list, legends=None, size_per_mol=300, mols_per_row=3, bond_length=35.0, bond_width=1.2, font_size=12, save_img='export/molecules.svg')

Generates an SVG file with a grid of molecules having consistent bond lengths. Ideal for high-quality printing and comparison.

Parameters:
  • smiles_list (list) – List of SMILES strings to draw.

  • legends (list, optional) – List of strings to display under each molecule.

  • size_per_mol (int) – Size of the square panel for each molecule (Default: 300).

  • mols_per_row (int) – Number of molecules per row (Default: 3).

  • bond_length (float) – Fixed length for bonds in pixels (Default: 35.0).

  • bond_width (float) – Thickness of the bonds (Default: 1.2).

  • font_size (int) – Font size for atom labels (Default: 12).

  • save_img (str) – Output SVG file path (Default: β€œexport/molecules.svg”).

fetch_pubchem_data()

Retrieves CID and IUPAC name from PubChem based on the current SMILES. Useful for molecules initialized directly via SMILES.

classmethod from_cid(cid)

Create an easy_rdkit instance directly from a PubChem CID.

Parameters:

cidint or str

The PubChem Compound ID.

get_isomers(max_isomers=12, verbose=True)

Explores the stereochemical space of the molecule by enumerating all possible stereoisomers.

This method identifies all unassigned or flexible stereocenters (chiral centers and double bonds) and generates a complete set of discrete stereochemical configurations. It is particularly useful for resolving β€œflat” SMILES strings into their constituent enantiomers and diastereomers.

Parameters:
  • max_isomers (int) – The maximum number of isomers to generate. This prevents computational explosion for molecules with many stereocenters (2^n). Defaults to 12.

  • verbose (bool) – If True, prints a summary of the number of isomers found using a colored terminal message. Defaults to True.

Returns:

A list of easy_rdkit instances, each representing a unique,

fully-defined stereoisomer of the parent molecule.

Return type:

list

static plot_grid_from_df(df, smiles_col='SMILES', legend_cols='IUPAC Name', mols_per_row=4, size=(250, 250), show_stereo=False, save_img=None)

Generates a grid image of molecular structures from a pandas DataFrame.

This method extracts SMILES strings from the specified column, generates 2D representations, and arranges them in a grid. It supports multi-line legends by passing a list of column names, and can export the result to external files.

Parameters:
  • df (pd.DataFrame) – DataFrame containing the molecular data.

  • smiles_col (str) – Name of the column containing SMILES strings. Defaults to β€˜SMILES’.

  • legend_cols (str or list) – Column name(s) to display as legends below each molecule. If a list is provided, each value is displayed on a new line (e.g., [β€˜IUPAC Name’, β€˜MW’, β€˜LogP’]). Defaults to β€˜IUPAC Name’.

  • mols_per_row (int) – Number of molecules to display in each row. Defaults to 4.

  • size (tuple) – Dimensions (width, height) in pixels for each individual molecule panel. Defaults to (250, 250).

  • save_img (str, optional) – File path to save the resulting image. Supports β€˜.svg’ (vector) and β€˜.png’ (raster) extensions. Defaults to None.

Returns:

An SVG object for rich display in Jupyter/Colab environments.

Return type:

IPython.display.SVG

Note

PNG export requires the Cairo backend to be available in the RDKit installation.

show_descriptors()

Print all computed descriptors in a formatted table.

show_isomers(mols_per_row=4, size=(250, 250), save_img=None)

Generates, labels, and displays a grid of all possible stereoisomers.

This method automates the transition from a single chemical identity to a visual comparative analysis of its stereoisomers. Each isomer is rendered with its specific SMILES string (including @ markers and / directionals) and an isomer index. It utilizes the class’s internal grid-plotting logic to ensure high-quality SVG output and optional file export.

Parameters:
  • mols_per_row (int) – Number of isomer structures to display per row in the grid. Defaults to 4.

  • size (tuple) – The (width, height) in pixels for each individual molecular panel. Defaults to (250, 250).

  • save_img (str, optional) – File path (e.g., β€˜isomers.svg’ or β€˜isomers.png’) to export the grid. Directories are created automatically. Defaults to None.

Returns:

A grid image displayed directly in the Jupyter/Colab

environment.

Return type:

IPython.display.SVG

show_mol(size: tuple = (400, 400), show_Lewis: bool = False, plot_conjugation: bool = False, plot_aromatic: bool = False, show_n: bool = False, show_hybrid: bool = False, show_H: bool = False, show_stereo: bool = False, rep3D: bool = False, macrocycle: bool = False, highlightAtoms: list = [], legend: str = '', save_img: str = None)

Renders the molecule in 2D SVG format with optional property overlays.

Parameters:
  • size (tuple) – Drawing dimensions in pixels.

  • show_Lewis (bool) – Annotates atoms with Lone Pairs and Vacancies.

  • plot_conjugation (bool) – Highlights conjugated bonds in blue.

  • plot_aromatic (bool) – Highlights aromatic rings in red.

  • show_n (bool) – Displays atom indices.

  • show_hybrid (bool) – Displays atom hybridization (sp3, sp2, etc.).

  • show_H (bool) – Adds explicit Hydrogens to the drawing.

  • show_stereo (bool) – Shows R,S,Z,E labels - if relevant

  • rep3D (bool) – Computes a 3D-like conformation before drawing.

  • macrocycle (bool) – Uses CoordGen for better rendering of large rings (e.g., Cyclodextrins).

  • highlightAtoms (list) – List of indices to highlight.

  • legend (str) – Title or legend text for the drawing.

  • save_img (str) – File path to save the resulting image. Supports β€˜.svg’ (vector) and β€˜.png’ (raster) extensions. Defaults to None.

to_dict(auto_fetch=False)

Export identity and descriptors as a flat dictionary. If auto_fetch is True, it will attempt to find missing CID/Name on PubChem.

pyphyschemtools.core module

pyphyschemtools.core.centerTitle(content=None)

centers and renders as HTML a text in the notebook font size = 16px, background color = dark grey, foreground color = white

pyphyschemtools.core.centertxt(content=None, font='sans', size=12, weight='normal', bgc='#000000', fgc='#ffffff')

centers and renders as HTML a text in the notebook

input: - content = the text to render (default: None) - font = font family (default: β€˜sans’, values allowed = β€˜sans-serif’ | β€˜serif’ | β€˜monospace’ | β€˜cursive’ | β€˜fantasy’ | …) - size = font size (default: 12) - weight = font weight (default: β€˜normal’, values allowed = β€˜normal’ | β€˜bold’ | β€˜bolder’ | β€˜lighter’ | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 ) - bgc = background color (name or hex code, default = β€˜#ffffff’) - fgc = foreground color (name or hex code, default = β€˜#000000’)

pyphyschemtools.core.crop_images(input_files, process_folder=False)

Trims whitespace or transparency from image files and saves the results.

If process_folder is True, input_files is treated as a directory path, and all images within (excluding those ending in -C) are processed. Otherwise, input_files is treated as a single file path or a list of paths.

The function preserves original image metadata (DPI, ICC profiles).

Parameters:
  • input_files (str, Path, or list) – File path(s) or a directory path.

  • process_folder (bool) – If True, treats input_files as a directory to crawl.

Returns:

Prints status messages to the console for each file processed.

Return type:

None

pyphyschemtools.core.get_qc_examples(suite=None)

Copies QC examples archive to the current directory. Supports terminal CLI (with help) and direct Python calls.

pyphyschemtools.core.save_data(df, path_with_name: str, **kwargs)

Saves a Pandas DataFrame to CSV or Excel, automatically creating missing directories.

Parameters:
  • df (pd.DataFrame) – The DataFrame to save.

  • path_with_name (str) – The path and filename (e.g., β€œdata/results.csv”).

  • **kwargs – Additional arguments passed to to_csv or to_excel (e.g., index=True).

pyphyschemtools.core.save_fig(path_with_name: str, fig=None, dpi: int = 300, **kwargs)

Saves a figure to a path, automatically creating missing directories. Works with the current plt or a specific figure object.

Parameters:
  • path_with_name (str) – The path and filename (e.g., β€œresults/plots/energy.svg”).

  • fig (matplotlib.figure.Figure, optional) – A specific figure object. If None, uses plt.gcf().

  • dpi (int) – Resolution for raster formats. Defaults to 300.

  • **kwargs – Additional arguments passed to savefig (e.g., transparent=True).

pyphyschemtools.core.smart_trim(img)

Determines the bounding box of the meaningful content in an image.

This function automatically detects if the image has transparency (Alpha channel). If it does, it calculates the bounding box based on non-transparent pixels. If the image is opaque, it assumes a white background and calculates the bounding box by detecting differences from a pure white canvas.

Parameters:

img (PIL.Image.Image) – The source image object.

Returns:

A 4-tuple (left, upper, right, lower) defining the crop box,

or None if the image is uniform/empty.

Return type:

tuple

pyphyschemtools.kinetics module

class pyphyschemtools.kinetics.KORD(t_exp=None, G_exp=None, headers=('Time / s', 'G'), a0=1.0, alpha=1.0, beta=1.0, k_guess=None, G_0_guess=None, G_inf_guess=None, b_inf_guess=None, t_simul_max=15, verbose=True)

Bases: object

Initialize the kinetic study with experimental data. Reaction: alpha A = beta B

Parameters:
  • t_exp (-) – Time values.

  • G_exp (-) – Measured physical quantity (Absorbance, Conductivity, etc.).

Fixed Parameters:
  • alpha (float): Stoichiometric coefficient for A reactant (smallest positive integer). Default is 1.0.

  • beta (float): Stoichiometric coefficient for B product (smallest positive integer). Default is 1.0.

  • a0 (float): Initial concentration. Note: G_theo is independent of a0 for Order 1. Default is 1.0.

Adjustable Variables (Initial Guesses):
  • k_guess (float, optional): Initial estimate for the rate constant. Default is 0.01.

  • G_0_guess (float, optional): Initial estimate for the initial measured value (G at t=0). if None, it will be initialized as G_exp[0]

  • G_inf_guess (float, optional): Initial estimate for the final measured value (G at infinity). if None, it will be initialized as G_exp[-1]

  • b_inf_guess (float, optional): Initial estimate for the final concentration of B ([B] at infinity). if None, it will be initialized as [A](t=0), i.e. a0

Other Args:
  • t_simul_max (float): the maximum time duration for theoretical simulations. It defines the range of the time vector [0, t_simul_max}] used to simulate and plot kinetic curves with simulate_plot

  • verbose (bool): If True defaulk), enables detailed optimization logs (recommended).

  • headers (tuple of strings): headers of the t_exp and G_exp arrays read in the excel file

G0_theo(t, k, G0, Ginf, binf)

Model for Order 0 kinetics

G1_theo(t, k, G0, Ginf)

Model for Order 1 kinetics

G2_theo(t, k, G0, Ginf, binf)

Model for Order 2 kinetics

concentrations(order, t, binf, k)

Calculate the time-dependent concentrations of reactant A and product B.

This method derives the initial concentration (a0) from the fitted final product concentration (binf) using the stoichiometric ratio alpha/beta. It then computes the concentration profiles based on the integrated rate laws for the specified kinetic order.

Parameters:
  • order (int) – Kinetic order (0, 1, or 2).

  • t (array-like) – Time vector for the calculation.

  • binf (float) – Final concentration of product B at t=infinity.

  • k (float) – Rate constant.

Returns:

(a, b) where β€˜a’ is the concentration array of reactant A

and β€˜b’ is the concentration array of product B.

Return type:

tuple

Notes

  • Order 0: Linear decay/formation until reactant exhaustion.

  • Order 1: Exponential decay/formation.

  • Order 2: Hyperbolic progression based on the 1/[A] linear relationship.

fit(k_guess, G_0_guess, G_inf_guess, A_0_guess, order=1)

Fits the selected kinetic model (Order 0, 1, or 2) to the experimental data.

This method uses non-linear least squares (scipy.optimize.curve_fit) to simultaneously optimize the rate constant (k), the initial and final physical property values (G0, Ginf), and the final product concentration (binf). Physical constraints are applied via parameter bounds to ensure k and binf remain positive.

It includes automated β€˜Smart Guessing’ for k, based on initial rates and computes information criteria (AIC/BIC) for model selection.

Parameters:
  • k_guess (float) – Initial estimate for the rate constant (k).

  • G_0_guess (float) – Initial estimate for the physical property at t=0.

  • G_inf_guess (float) – Initial estimate for the physical property at t=infinity.

  • b_inf_guess (float) – Initial estimate for the final product concentration [B].

  • order (int, optional) – Kinetic order of the reaction (0, 1, or 2). Defaults to 1.

Returns:

A dictionary containing the optimized parameters (β€˜k’, β€˜G0’, β€˜Ginf’, β€˜binf’)

and statistical metrics (β€˜RMSE’, β€˜R2’, β€˜t_half’). Returns None if optimization fails to converge.

Return type:

dict

Notes

  • For Order 1, the timing is independent of binf, and alpha is coupled with k; hence binf is kept fixed during optimization.

  • For Orders 0 and 2, binf and stoichiometry (alpha, beta) explicitly define the reaction’s capacity and end-point timing, ensuring physical consistency between the plateau and the slope.

get_best_order(verbose=True)

Determines and prints the best model based on the lowest RMSE.

halflife(order, binf, k)

Calculate the half-life (t1/2) for the reaction based on the kinetic order.

The half-life represents the time required for the reactant concentration to reach half of its initial value (a0/2).

Parameters:
  • order (int) – Kinetic order (0, 1, or 2).

  • k (float) – The optimized or guessed rate constant.

Returns:

The calculated half-life value.

Return type:

float

Notes

  • Order 0: t1/2 = a0 / (2 * alpha * k) -> Dependent on a0.

  • Order 1: t1/2 = ln(2) / (alpha * k) -> Independent of a0.

  • Order 2: t1/2 = 1 / (alpha * k * a0) -> Inversely proportional to a0.

static load_from_excel(file_path, exp_number, sheet_name=0, show_data=True)

Static method to extract data from an Excel file. Selects the pair of columns (t, G) corresponding to the experiment number. Also loads parameters (a0, alpha, beta)

Format:
  • Row 1: Headers for t and G

  • Row 2: [A]0 value (in the G column)

  • Row 3: alpha value (in the G column)

  • Row 4: beta value (in the G column)

  • Row 5+: [t, G] data points

plot_all_fits(save_img=None)

Plots experimental data and all three kinetic models for visual comparison. If save_img is provided, saves the plot (png, svg, jpg, pdf according to the extension). Vectorial svg is recommended

simulate_plot(save_img=None)

Plots the initial guesses for all three kinetic orders (0, 1, 2), for example to visualize the starting point of a fit.

If save_img is provided, saves the plot (png, svg, jpg, pdf according to the extension). Vectorial svg is recommended

pyphyschemtools.nano module

pyphyschemtools.nano.get_coordination_numbers(mol: Atoms, cutoff: float = None)

Calculates the coordination number (CN) for each atom in an ASE Atoms object.

This function determines how many neighbors each atom has based on a distance threshold. If no cutoff is provided, it automatically estimates one based on the 1st percentile of the interatomic distance distribution.

Parameters:
  • mol (ase.Atoms) – The structural model (nanoparticle, molecule, or crystal).

  • cutoff (float, optional) – The distance threshold (in Angstroms) to define a chemical bond. Defaults to None (automatic detection).

Returns:

A tuple containing:
  • cn (numpy.ndarray): An array of integers representing the CN of each atom.

  • used_cutoff (float): The actual cutoff value used for the calculation.

Return type:

tuple

pyphyschemtools.nano.view_coordination(mol: Atoms, cutoff: float = None, stick_radius: float = 0.1, sphere_scale: float = 0.6, w=600, h=400, color_map='YlOrRd')

Visualizes a structure using py3Dmol with atoms color-coded by coordination number.

This function computes the coordination environment and generates a 3D ball-and-stick model where colors represent the connectivity (e.g., surface vs. bulk atoms). A Matplotlib legend is displayed alongside the 3D view.

The color logic is optimized for nanoparticles: - CN < 5 : Pastel (low coordination/isolated) - CN 5-13: Sequential Gradient (surface to bulk transition) - CN > 13: Deep Dark (high density/interstitials)

Parameters:
  • mol (ase.Atoms) – The structural model to visualize.

  • cutoff (float, optional) – Distance threshold for bond detection. Defaults to None (auto-detect).

  • stick_radius (float, optional) – The thickness of the bonds in the 3D view. Defaults to 0.1.

  • sphere_scale (float, optional) – The size multiplier for the atomic spheres. Defaults to 0.6.

  • w (float, optional) – Width of the window Defaults to 600

  • h (float, optional) – Height of the window Defaults to 400

  • color_map (str, optional) – The Matplotlib colormap to use for discrete CN values. Defaults to β€œYlOrRd” (recommended!).

Returns:

The interactive viewer object.

Return type:

py3Dmol.view

pyphyschemtools.spectra module

pyphyschemtools.survey module

class pyphyschemtools.survey.SurveyApp(mode='participant', base_dir='ML-survey')

Bases: object

analyze_text_columns(df=None, columns=None, top_n=20)

Basic textual analysis: show frequent words, word clouds, and per-question summary.

build_admin_dashboard()
build_participant_form()
enable_slider_css()

Inject CSS for hover/active color effects on sliders.

get_or_create_user_id()

Return a persistent anonymous ID (stored in .survey_id).

list_drafts()
load_all_responses()

Load and merge all .csv survey responses into a DataFrame.

load_draft(b)
load_questions()
plot_spider_multi(df, title='Participant and Mean Scores per Block', savepath=None, figsize=(12, 8))

Draw radar (spider) chart with per-participant transparency and block names instead of A–F.

print_questions_summary()

Affiche la liste des questions par bloc et leur type (NumΓ©rique/Texte).

run()
save_draft(b)
semantic_analysis(df=None, columns=None, n_clusters=3)

Perform semantic clustering on open-ended responses using sentence-transformers.

submit_form(b)
summarize_by_block(df)

Compute average score per block (A–F) for numeric questions.

pyphyschemtools.sympyUtilities module

pyphyschemtools.sympyUtilities.PrintLatexStyleSymPyEquation(spe)

Function that displays a SymPy expression (spe) in a jupyter notebbok after its conversion into a LaTeX / Math output

Input: spe= SymPy expression

Output: Pretty printing of spe

pyphyschemtools.sympyUtilities.e2Lists(eigenvectors, sort=False)

returns two separate lists from the list of tuples returned by the eigenvects() function of SymPy

input: - the list of tuples returned by eigenvects - sort (default: False): returns sorted eigenvalues and corresponding eigenvectors if True

output - list of eigenvalues, sorted or not - list of corresponding eigenvectors

pyphyschemtools.units module

class pyphyschemtools.units.Area(value, unit='m2')

Bases: PhysicalQuantity

Area management. Supports SI and Si-related units (m2, hectare) and Imperial units (sq inch, sq ft, acre).

to(target)
class pyphyschemtools.units.Density(value, unit='kg/cm3')

Bases: PhysicalQuantity

Density (Mass per Volume) management. Supports SI (kg/m3) and common lab units (g/cm3, g/mL, lb/ft3).

to(target)
class pyphyschemtools.units.Energy(value, unit='J')

Bases: PhysicalQuantity

to(target)
class pyphyschemtools.units.Length(value, unit='m')

Bases: PhysicalQuantity

Distance and Length management. Supports SI (m) and Imperial units (inch, foot, yard, mile, nautical mile).

to(target)
class pyphyschemtools.units.Mass(value, unit='kg')

Bases: PhysicalQuantity

Mass management.

to(target)
class pyphyschemtools.units.MolarMass(value, unit='kg/mol')

Bases: PhysicalQuantity

Molar Mass management for chemical species. Converts between g/mol, kg/mol, and Da (Daltons/amu).

to(target)
class pyphyschemtools.units.PhysicalQuantity(value, unit, conversion_map)

Bases: object

classmethod parse(query)

Parses strings like β€˜13.6 eV’ or β€˜1013 hPa’.

classmethod show_available_units()

Displays available base units, underlining the SI base unit (factor 1.0).

static show_constants_metadata()

Displays a styled table of the physical constants used for calculations, including CODATA values, units, and uncertainties.

class pyphyschemtools.units.Pressure(value, unit='Pa')

Bases: PhysicalQuantity

Pressure management class (Pa, bar, atm, torr, psi).

to(target)
class pyphyschemtools.units.Temperature(value, unit='K')

Bases: PhysicalQuantity

classmethod show_available_units()

Displays available temperature units as a styled DataFrame, highlighting Kelvin in blue.

to(target)

Converts the absolute temperature to a target scale.

class pyphyschemtools.units.Volume(value, unit='m3')

Bases: PhysicalQuantity

Volume management. Supports SI and SI-related units (m3, L) and Imperial units (gallon, quart, pint, fluid ounce). Note: Uses US liquid measures from SciPy.

to(target)

pyphyschemtools.misc module

class pyphyschemtools.misc.QRCodeGenerator(box_size=40, border=1, version=4)

Bases: object

A utility class to generate QR codes with embedded logos for pyphyschemtools. Initialize the generator with specific QR parameters.

Parameters:
  • box_size (int) – The size of each box in the QR code grid.

  • border (int) – The thickness of the white border.

  • version (int) – The complexity of the QR code (1 to 40).

generate(url, logo_path, fill_color='#1a525f', back_color='white', save_path=None, logo_ratio=4, width=250, flatten=False)

Creates a QR code with a centered logo, saves it to disk, and displays it.

If save_path is not provided, the image is saved in the logo’s directory with a qrcode_ prefix.

Parameters:
  • url (str) – The target URL for the QR code.

  • logo_path (str) – Path to the logo image file.

  • fill_color (str) – Hex code or name for the QR code color.

  • back_color (str) – Background color.

  • save_path (str, optional) – Custom path to save the PNG. Defaults to None.

  • logo_ratio (float) – Ratio of logo size relative to QR code size (default 1/4).

  • width (int) – Display width for Jupyter Notebook rendering.

  • flatten (bool) – If True, removes transparency by placing the logo on a solid white background. Defaults to False.

Returns:

The generated QR code image object.

Return type:

PIL.Image

pyphyschemtools.tools4AS module

pyphyschemtools.visualID_Eng module

pyphyschemtools.visualID_Eng.apply_css_style()

Explicitly reads and applies the visualID CSS stylesheet from the package resources.

class pyphyschemtools.visualID_Eng.bg

Bases: object

DARKRED = '\x1b[38;5;231;48;5;52m'
DARKREDB = '\x1b[38;5;231;48;5;52;1m'
LIGHTBLUE = '\x1b[48;5;117m'
LIGHTBLUEB = '\x1b[48;5;117;1m'
LIGHTGREEN = '\x1b[48;5;156m'
LIGHTGREENB = '\x1b[48;5;156;1m'
LIGHTRED = '\x1b[48;5;217m'
LIGHTREDB = '\x1b[48;5;217;1m'
LIGHTYELLOW = '\x1b[48;5;228m'
LIGHTYELLOWB = '\x1b[48;5;228;1m'
OFF = '\x1b[0m'
pyphyschemtools.visualID_Eng.chrono_show()
pyphyschemtools.visualID_Eng.chrono_start()
pyphyschemtools.visualID_Eng.chrono_stop(hdelay=False)
class pyphyschemtools.visualID_Eng.color

Bases: object

BLUE = '\x1b[94m'
BOLD = '\x1b[1m'
CYAN = '\x1b[96m'
DARKCYAN = '\x1b[36m'
GREEN = '\x1b[92m'
OFF = '\x1b[0m'
PURPLE = '\x1b[95m'
RED = '\x1b[91m'
UNDERLINE = '\x1b[4m'
YELLOW = '\x1b[93m'
pyphyschemtools.visualID_Eng.display_md(text)
pyphyschemtools.visualID_Eng.end()

Terminates the notebook session: displays duration, end time, and the termination logo from package resources.

class pyphyschemtools.visualID_Eng.fg

Bases: object

BLACK = '\x1b[30m'
BLUE = '\x1b[94m'
CYAN = '\x1b[96m'
DARKCYAN = '\x1b[36m'
DARKGRAY = '\x1b[90m'
GREEN = '\x1b[92m'
LIGHTGRAY = '\x1b[37m'
OFF = '\x1b[0m'
PURPLE = '\x1b[95m'
RED = '\x1b[91m'
WHITE = '\x1b[38;5;231m'
YELLOW = '\x1b[93m'
pyphyschemtools.visualID_Eng.hdelay(sec)
pyphyschemtools.visualID_Eng.hdelay_ms(delay)
class pyphyschemtools.visualID_Eng.hl

Bases: object

BOLD = '\x1b[1m'
ITALIC = '\x1b[3m'
OFF = '\x1b[0m'
UNDERL = '\x1b[4m'
bold = '\x1b[21m'
italic = '\x1b[23m'
underl = '\x1b[24m'
pyphyschemtools.visualID_Eng.init(which=None)

Initializes the notebook environment: applies CSS, displays the banner, and shows hostname/time.