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[source]
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
Subpackages
- pyphyschemtools.quantumChem_corner package
- Submodules
- pyphyschemtools.quantumChem_corner.GScan_Analyzis module
- pyphyschemtools.quantumChem_corner.cif2pos module
- pyphyschemtools.quantumChem_corner.pos2cif module
- pyphyschemtools.quantumChem_corner.pos2xxx module
- pyphyschemtools.quantumChem_corner.pos2xyz module
- pyphyschemtools.quantumChem_corner.wrappers module
- pyphyschemtools.utils package
Submodules
pyphyschemtools.Chem3D module
- class pyphyschemtools.Chem3D.XYZData(symbols, positions)[source]
Bases:
objectObject containing molecular coordinates and symbols extracted by molView. Allows for geometric calculations without reloading data.
- get_bounding_sphere(include_vdw=True, scale=1.0)[source]
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)[source]
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)[source]
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)
- 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)[source]
Bases:
objectInitializes 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, MDL mol/SDF…)
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)[source]
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)[source]
Calculates and displays the VdW bounding sphere in one go.
- show_cage_cavity(grid_spacing=0.5, color='cyan', opacity=0.5)[source]
Calculates cavity with CageCavityCalc and displays it as a single model.
- classmethod view_grid(mol_list, n_cols=3, titles=None, **kwargs)[source]
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)[source]
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.PeriodicTable module
- class pyphyschemtools.PeriodicTable.TableauPeriodique[source]
Bases:
objectClasse 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()[source]
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()[source]
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)[source]
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)[source]
Bases:
objectA 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)[source]
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)[source]
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)[source]
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:
Scans data files and parses Temperature/Pressure/Energy grids.
Traces individual 3D surfaces with mapped color scales.
Calculates and plots intersection boundaries between surface phases.
Overlays experimental markers (e.g., specific T/P conditions).
Optionally exports and crops the resulting image using Pillow.
pyphyschemtools.cheminformatics module
- class pyphyschemtools.cheminformatics.easy_rdkit(smiles, canonical=True, lang='En')[source]
Bases:
objectA 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()[source]
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()[source]
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')[source]
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()[source]
Retrieves CID and IUPAC name from PubChem based on the current SMILES. Useful for molecules initialized directly via SMILES.
- classmethod from_cid(cid)[source]
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)[source]
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)[source]
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_isomers(mols_per_row=4, size=(250, 250), save_img=None)[source]
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)[source]
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.
pyphyschemtools.core module
- pyphyschemtools.core.centertxt(content=None, style=None, font=None, size=None, weight=None, bgc=None, fgc=None)[source]
Centers and renders text as HTML in the notebook.
input: - content = text to render (default: None) - style = predefined style name (default: None). See STYLES below.
Any explicit parameter overrides the style.
font = font family (default: ‘sans’)
size = font size in px (default: 12)
weight = font weight (default: ‘normal’)
bgc = background color, name or hex (default: ‘#ffffff’)
fgc = foreground color, name or hex (default: ‘#000000’)
- pyphyschemtools.core.crop_images(input_files, process_folder=False)[source]
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)[source]
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)[source]
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)[source]
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)[source]
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)[source]
Bases:
objectInitialize 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
- concentrations(order, t, binf, k)[source]
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)[source]
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)[source]
Determines and prints the best model based on the lowest RMSE.
- halflife(order, binf, k)[source]
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)[source]
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
- class pyphyschemtools.kinetics.kbasic[source]
Bases:
objectRecherche pédagogique de la constante de vitesse k.
- Utilisation typique :
kb = kbasic() kb.read(“mesures.xlsx”) # 1) lire les données kb.fit(ordre=1) # 2) chercher le meilleur k kb.plot() # 3) tracer le résultat
La grandeur mesurée G décroît avec le temps depuis sa valeur initiale G0. La forme de G(t) dépend de l’ordre de la réaction :
ordre 0 : décroissance LINÉAIRE
ordre 1 : décroissance EXPONENTIELLE (le cas le plus courant)
ordre 2 : décroissance HYPERBOLIQUE
- fit(ordre=1, G0=None, k_depart=0.1)[source]
Trouve la valeur de k qui minimise le RMSD pour l’ordre choisi.
Si G0 n’est pas donné, on le prend égal à la première valeur mesurée. Sinon, on utilise la valeur fournie par l’utilisateur.
Retourne : (k_optimal, rmsd_au_minimum)
- read(fichier=None, colab=False)[source]
Lit un fichier Excel à deux colonnes (temps, G) et affiche un récapitulatif sous forme de DataFrame pandas.
Détecte automatiquement si la première ligne est un en-tête. Si oui, les noms de colonnes serviront de labels pour les axes du tracé.
Retourne le DataFrame des données lues.
- Arguments :
- fichierchemin (ou URL) du fichier Excel à lire.
Inutile si colab=True (on choisit le fichier à l’upload).
- colabsi True, ouvre le bouton d’upload de Google Colab
et lit le fichier choisi. Défaut False.
pyphyschemtools.misc module
- class pyphyschemtools.misc.QRCodeGenerator(box_size=40, border=1, version=4)[source]
Bases:
objectA 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)[source]
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.nano module
- pyphyschemtools.nano.get_coordination_numbers(mol: Atoms, cutoff: float = None)[source]
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')[source]
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.orgachem module
- class pyphyschemtools.orgachem.FunctionalGroupExplorer[source]
Bases:
objectA comprehensive educational tool for organic chemistry within the pyphyschemtools suite.
This class provides an interactive interface for: - Exploring functional groups using SMARTS patterns. - Retrieving IUPAC nomenclature via PubChem API. - Visualizing molecules in 2D (with highlighting) and 3D. - Training via a Quiz system with fuzzy logic validation and survival mechanics.
pyphyschemtools.spectro module
- class pyphyschemtools.spectro.QuantitativeAnalysis(x=None, y=None, x_label='Concentration', y_label='Area')[source]
Bases:
objectA comprehensive tool for chemical analysis calibration (e.g., Chromatography, Spectroscopy).
This class handles data ingestion from multiple sources, performs linear regression, provides statistical diagnostics (R², LOD, LOQ), and generates publication-quality plots including residual analysis and confidence intervals.
- x
Independent variable data (usually concentration or amount).
- Type:
numpy.ndarray
- y
Dependent variable data (usually peak area, absorbance, or signal).
- Type:
numpy.ndarray
- x_label
Label for the x-axis used in plotting.
- Type:
str
- y_label
Label for the y-axis used in plotting.
- Type:
str
- model
Storage for the regression parameters after fitting.
- Type:
scipy.stats._stats_mstats_common.LinregressResult or None
- fit_linear()[source]
Perform ordinary least squares (OLS) linear regression and compute analytical diagnostics.
This method calculates the best-fit line (y = ax + b) for the calibration data. It computes standard statistical metrics (Slope, Intercept, R²) and specific analytical chemistry performance indicators (MAE, LOD, LOQ) to evaluate the method’s sensitivity and reliability.
The results are printed to the console in a formatted table and stored within the self.diagnostics dictionary for programmatic access.
- model
The full regression result object containing slope, intercept, rvalue, pvalue, and stderr.
- Type:
scipy.stats._stats_mstats_common.LinregressResult
- diagnostics
A dictionary containing key analytical performance indicators:
‘slope_err’: Standard error of the slope.
‘intercept_err’: Standard error of the intercept.
‘r_squared’: Coefficient of determination.
‘mae’: Mean Absolute Error.
‘lod’: Limit of Detection.
‘loq’: Limit of Quantification.
‘sy_x’: Residual standard deviation.
- Type:
dict
Notes
The following diagnostics are calculated:
MAE (Mean Absolute Error): Average of the absolute residuals, expressed in the same units as the signal (y).
LOD (Limit of Detection): The lowest concentration detectable with statistical significance ($3 sigma / ext{slope}$).
LOQ (Limit of Quantification): The lowest concentration that can be quantified with acceptable precision ($10 sigma / ext{slope}$).
sy_x: Residual standard deviation, used as an estimate for experimental noise.
Example
>>> calib = Calibration(conc, area) >>> results = calib.fit_linear() >>> print(calib.diagnostics['lod'])
- classmethod from_excel(file_path, x_col=1, y_col=2, sheet_name=0)[source]
Classmethod to create a QuantitativeAnalysis instance from an Excel or ODS file.
- Parameters:
file_path (str or Path) – Path to the .xlsx or .ods file.
x_col (int or str, optional) – Column number (starting at 1) or Name (str) for X. Default is 1.
y_col (int or str, optional) – Column number (starting at 1) or Name (str) for Y. Default is 2.
sheet_name (str or int, optional) – The specific sheet to read from. Default is 0 (the first sheet).
- plot_calibration(save_img=None, figsize=(20, 20), scientific=True, marker='o', color_marker='#780000', color_fit='#0b78b3', linestyle='-', fontsize=12)[source]
Generates a diagnostic plot featuring the calibration curve and residual analysis.
The figure consists of two subplots:
Top Panel: Regression Line & Uncertainty Displays the experimental data points (x, y), the calculated OLS regression line, and a 95% Prediction Interval. The interval is calculated as 1.96 * sigma, where sigma (sy_x) is the Standard Deviation of the Residuals.
Bottom Panel: Residual Analysis Plots the residuals (y_exp - y_calc) against concentration. This panel is essential for checking homoscedasticity. A random distribution around the zero-line validates the linear model, whereas a structured pattern (e.g., U-shape) indicates non-linearity.
- Parameters:
save_img (str, optional) – Path or filename to save the figure (e.g., ‘plot.png’, ‘report.svg’). If the file exists, a manual confirmation will be requested. Vectorial formats (.svg, .pdf) are recommended for publications.
figsize (tuple, default (20, 20)) – Width and height of the figure, in cm.
scientific (bool, default True) – If True, forces scientific notation (e.g., 1e+05) on the Y-axis.
marker (str, default "o") – Style of the experimental data points.
color_marker (str, default "#780000") – Color of the experimental scatter points.
color_fit (str, default "#0b78b3") – Color of the regression line and the prediction interval.
linestyle (str, default "-") – Line style for the linear fit.
fontsize (int, default 12) – Base font size for all text elements in the figure. The titles are set to fontsize + 2, while the axis labels use fontsize. The legend and tick labels are automatically scaled to fontsize - 2 and fontsize - 1 respectively.
- Raises:
ValueError – If the method is called before fitting the model with fit_linear().
Notes
The 95% Prediction Interval represents the range within which a new single observation is expected to fall. It is wider than a Confidence Interval as it accounts for both the model uncertainty and the inherent variance (sigma) of the residuals.
- predict(signals, sample_name='Sample')[source]
Prediction of concentration statistics from analytical signals.
Calculates the mean and standard deviation of the provided signals, applies the inverse linear model, prints a formatted analysis report, and store values in attributes.
- Parameters:
signals (float or list/numpy.ndarray) – The analytical signal(s) measured (e.g., Absorbance, Area).
sample_name (str, optional) – A name for the sample for the report (default is “Sample”).
Notes
This method updates the following instance attributes:
mean_conc: The calculated mean concentration.
std_conc: The estimated uncertainty of the concentration.
mean_signal: The average value of the input signals.
- class pyphyschemtools.spectro.SpectrumSimulator(sigma_ev=0.3, plotWH=(12, 8), fontSize_axisText=14, fontSize_axisLabels=14, fontSize_legends=12, fontsize_peaks=12, colorS='#3e89be', colorVT='#469cd6')[source]
Bases:
objectInitializes the spectrum simulator
- Parameters:
sigma_ev (-) – Gaussian half-width at half-maximum in electron-volts (eV). Default is 0.3 eV (GaussView default is 0.4 eV).
plotWH (-) – Width and Height of the matplotlib figures in inches. Default is (12,8).
colorS (-) – color of the simulated spectrum (default =’#3e89be’)
colorVT (-) – color of the vertical transition line (default = ‘#469cd6’)
- Returns:
This method initializes the instance attributes.
- Return type:
None
- Calculates:
sigmanm = half-width of the Gaussian band, in nm
- plotAbs_lambda_TDDFT(datFiles=None, C0=1e-05, lambdamin=200, lambdamax=800, Amax=2.0, titles=None, linestyles=[], annotateP=[], tP=0.1, resetColors=False, save_img=None)[source]
Plots a simulated TDDFT VUV absorbance spectrum (transitions summed with gaussian functions) between lambdamin and lambdamax (sum of states done in the range [lambdamin-50, lambdamlax+50] nm)
- Parameters:
datFiles – list of pathway/name to files generated by ‘GParser Gaussian.log -S’
C0 – list of concentrations needed to calculate A = epsilon x l x c (in mol.L-1)
lambdamin – plot range (x axis)
lambdamax – plot range (x axis)
Amax – y axis graph limit
titles – list of titles (1 per spectrum plot)
linestyles – list of line styles(default = “-”, i.e. a continuous line)
annotateP – list of Boolean (annotate lambda max True or False. Default = True)
tP – threshold for finding the peaks (default = 0.1)
resetColors (bool) – If True, resets the matplotlib color cycle to the first color. This allows different series (e.g., gas phase vs. solvent) to share the same color coding for each molecule across multiple calls. Default: False
save – saves in a png file (300 dpi) if True (default = False)
save_img – saves figure in a 300 dpi png file if not None (default), with save_img=full pathway
- plotAbs_lambda_exp(csvFiles, C0, lambdamin=200, lambdamax=800, Amax=2.0, titles=None, linestyles=[], annotateP=[], tP=0.1, save_img=None)[source]
Plots an experimental VUV absorbance spectrum read from a csv file between lambdamin and lambdamax
- Parameters:
superpose (-) – False = plots a new graph, otherwise the plot is superposed to a previously created one (probably with plotAbs_lambda_TDDFT())
csvfiles (-) – list of pathway/name to experimental csvFiles (see examples for the format)
C0 (-) – list of experimental concentrations, i.e. for each sample
lambdamin (-) – plot range (x axis)
lambdamax – plot range (x axis)
Amax (-) – graph limit (y axis)
titles (-) – list of titles (1 per spectrum plot)
linestyles (-) – list of line styles(default = “–”, i.e. a dashed line)
annotateP (-) – list of Boolean (annotate lambda max True or False. Default = True)
tP (-) – threshold for finding the peaks (default = 0.1)
save (-) – saves in a png file (300 dpi) if True (default = False)
save_img (-) – saves figure in a 300 dpi png file if not None (default), with save_img=full pathway
- plotEps_lambda_TDDFT(datFile, lambdamin=200, lambdamax=800, epsMax=None, titles=None, tP=10, ylog=False, save_img=None)[source]
Plots a TDDFT VUV simulated spectrum (vertical transitions and transitions summed with gaussian functions) between lambdamin and lambdamax
The sum of states is done in the range [lambdamin-50, lambdamax+50] nm.
- Parameters:
datFile – list of pathway/names to “XXX_ExcStab.dat” files generated by ‘GParser Gaussian.log -S’
lambdamin – plot range
lambdamax – plot range
epsMax – y axis graph limit
titles – list of titles (1 per spectrum plot)
tP – threshold for finding the peaks (default = 10 L. mol-1 cm-1)
ylog – y logarithmic axis (default: False).
save – saves in a png file (300 dpi) if True (default = False)
save_img – saves figure in a 300 dpi png file if not None (default), with save_img=full pathway
- plotTDDFTSpectrum(wavel, sumInt, wavelTAB, feTAB, tP, ylog, labelSpectrum, colorS='#0000ff', colorT='#0000cf')[source]
Called by plotEps_lambda_TDDFT. Plots a single simulated UV-Vis spectrum, i.e. after gaussian broadening, together with the TDDFT vertical transitions (i.e. plotted as lines)
- Parameters:
wavel – array of gaussian-broadened wavelengths, in nm
sumInt – corresponding molar absorptiopn coefficients, in L. mol-1 cm-1
wavelTAB – wavelength of TDDFT, e.g. discretized, transitions
ylog – log plot of epsilon
tP – threshold for finding the peaks
feTAB – TDDFT oscillator strength for each transition of wavelTAB
labelSpectrum – title for the spectrum
pyphyschemtools.survey module
- class pyphyschemtools.survey.SurveyApp(mode='participant', base_dir='ML-survey')[source]
Bases:
object- analyze_text_columns(df=None, columns=None, top_n=20)[source]
Basic textual analysis: show frequent words, word clouds, and per-question summary.
- plot_spider_multi(df, title='Participant and Mean Scores per Block', savepath=None, figsize=(12, 8))[source]
Draw radar (spider) chart with per-participant transparency and block names instead of A–F.
- print_questions_summary()[source]
Affiche la liste des questions par bloc et leur type (Numérique/Texte).
pyphyschemtools.sympyUtilities module
- pyphyschemtools.sympyUtilities.PrintLatexStyleSymPyEquation(spe)[source]
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)[source]
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.tools4AS module
- pyphyschemtools.tools4AS.ApplySecondeChance(df, nomCC, nomCCSC, nomCCdelaSC)[source]
modification du dataframe df
- entrée :
df = dataframe auquel on va ajouter une nouvelle colonne nomCCSC qui va contenir la note de la colonne nomCC soit celle de la colonne nomCCdelaSC, si cell-ci est supérieure à la notede nomCC
nomCC = nom de la colonne à laquelle on applique la seconde chance
nomCCSC = nom de la nouvelle colonne qui contient la note du CC après application de la seconde chance
nomCCdelaSC = nom de la colonne qui contient la note “seconde chance
- sortie :
moyenne après application de la seconde chance
écart-type après application de la seconde chance
- pyphyschemtools.tools4AS.BoiteAMoustachesByMentionEtParcours(df, Moyenne, Mention, Parcours, NomGraphique)[source]
- pyphyschemtools.tools4AS.BoiteAMoustachesByMentionEtParcoursHue(df, Moyenne, Mention, Parcours, NomGraphique)[source]
- pyphyschemtools.tools4AS.ComparaisonMoyennesDMCC(df, nomCC1, nomCC2, SeuilBadDMCC1, SeuilGoodDMCC1)[source]
- entrée :
df = dataframe avec uniquement les étudiants AJ ou ADM, c’est-à-dire qu’il n’y a aucun fantôme
nomCC1 = en-tête de la colonne de df qui contient la note du premier CC
nomCC2 = en-tête de la colonne de df qui contient la note du 2nd CC
SeuilBadDMCC1 = Seuil en-dessous duquel la note au nomCC1 est considérée comme médiocre
SeuilGoodDMCC1 = Seuil au-deçà duquel la note au nomCC1 est considérée comme bonne
- affichage :
- moyenne au nomCC2 de la cohorte d’étudiant(e)s
en-dessous du SeuilBadDMCC1 au nomCC1
au-dessus du SeuilGoodDMCC1 au nomCC1
entre les deux seuils au nomCC1
jointplot entre nomCC1 et nomCC2 uniquement pour les étudiant(e)s dont la note au CC1 est considérée comme médiocre
- pyphyschemtools.tools4AS.CreationDfADMAJGH(df, note, Seuil, prefix, MD, Parc, IDApoG)[source]
- entrée :
df = dataframe avec les mentions/parcours/moyennes
note = nom de la colonne qui contient la moyenne globale
Seuil = seuil de réussite pour départager ADM & AJ
prefix = préfixe du nom de fichier temporaire, incluant ou nom le nom d’un sous-répertoire de sauvegarde
MD = nom de la colonne qui contient la dénomination simplifiée de la mention de diplôme (“MentionD”)
Parc = nom de la colonne qui contient le parcours
IDApoG = nom de la colonne qui contient l’ID des étudiants
- sortie :
dfADM = dataframe des admis
dfAJ = dataframe des ajournés
dfGhosts = dataframe des fantômes (aka Ghosts ; i.e. n’ont passé aucun des CC)
affichage : stats rapides (describe & sum) de chacun des sous-ensembles ADM, AJ, Ghosts
sauvegarde : fichier excel tmp{Note}.xlsx avec 3 onglets (ADM, AJ, Ghosts)
- pyphyschemtools.tools4AS.Histogrammes(df, nomCC, Moyenne, NomGraphique, w, moy, std, moyT, stdT, legende)[source]
- entrée :
df = dataframe qui contient ID, Noms, Prénoms, notes de CC, et Moyenne pondérée
nomCC = liste qui contient noms d’en-têtes des colonnes qui contiennent les notes de CC
Moyenne = nom de l’en-tête de la colonne qui contient la moyenne
NomGraphique = nom du fichier png qui va contenir la figure
w = liste qui contient les coeffs des CC
moy = liste qui contient la moyenne de chaque CC
std = liste qui contient l’écart-type calculé pour chaque CC
moyT = moyenne des 4 CC
stdT = écart-type calculé pour la note globale
legende = titre qui sera affiché sur l’histogramme principal
- affichage :
1 petit histogramme /CC
1 grand histogramme avec la moyenne
- sauvegarde :
fichier graphique ‘NomGraphique’ avec 1 petit histogramme par CC + 1 grand histogramme avec la moyenne
- pyphyschemtools.tools4AS.MentionAuModule(note, Seuil)[source]
- entrée :
note = valeur numérique ou NaN
Seuil = seuil de réussite
- sortie :
m = mention au module (AJ, P, AB, B, TB ou PB!! dans le cas où la colonne contiendrait une valeur numérique non comprise entre 0 et 20, ou bien toute autre contenu (caractères etc)
- pyphyschemtools.tools4AS.RenameDfHeader(dfCC, dfCCname, labelNoteCC, nomCC)[source]
- entrée :
dfCC = dataframe dont 1 colonne contient les notes de CC
dfCCname = nom (string) du dataframe. Il est recommandé d’utiliser f’{dfCC=}’.split(‘=’)[0]
labelNoteCC = label de la colonne qui contient les notes
nomCC = label de l’épreuve de CC (ex CC1), utilisé pour l’affichage
sortie : aucune
la fonction change le nom ‘labelNoteCC’ en ‘nomCC’
- pyphyschemtools.tools4AS.ReplaceABSByNan(df, nomCC)[source]
- entrée :
dataframe qui contient les notes
nom des colonnes qui contiennent les notes
- sortie
nouveau dataframe où toutes les notes des colonnes nomCC = ABS sont remplacées par des nan
- pyphyschemtools.tools4AS.ReplaceNanBy0OLD(df, nomCC)[source]
- entrée :
df = dataframe avec les notes
nomCC = liste des en-têtes de colonnes qui contiennt les notes
- sortie :
le dataframe avec Nan remplacé par 0 pour chaque étudiant qui a au moins une note de CC
- pyphyschemtools.tools4AS.StackedBarPop(df, ListCols, ylabel, NomGraphique)[source]
- entrée :
df : dataframe contenant l’analyse statistique globale, dont les moyennes, effectifs, etc. i.e. le dataframe renvoyé par StatsRéussiteParMentionOuParcours()
ListCols = liste avecles labels des colonnes contenant les valeurs numériques qu’on veut tracer comme un histogramme empilé
ylabel = label de l’axe des y
NomGraphique = nom du fichier png qui va être sauvé
- affichage :
bar plot empilé de pandas
- sauvegarde :
fichier graphique ‘NomGraphique’ au format png
- pyphyschemtools.tools4AS.StackedBarPopPO(dfRef, Mention, Parcours, NomGraphique)[source]
- entrée :
dfRef : dataframe contenant la liste des étudiants avec leur Mention et leur otpion, tel que généré par mentionD()
Mention = nom de la colonne qui contient le nom simplifié d’une Mention
Parcours = nom de la colonne qui contient la version simplifiée d’un Parcours
NomGraphique = nom du fichier png qui va être sauvé
- affichage :
histplot “hue” de seaborn, càd les effectifs par Parcours empilés pour chaque Mention
- sauvegarde :
fichier graphique ‘NomGraphique’ au format png
- pyphyschemtools.tools4AS.StatsRéussiteParMentionOuParcours(dfT, dfADM, dfAJ, dfGhosts, Category, note)[source]
- entrée :
dfT = dataframe qui contient toutes les notes, ainsi qu’au moins une catégorisation (exemple : Mention ou Parcours ou Section etc…)
dfADM = dataframe qui contient uniquement les étudiants admis
dfAJ = dataframe qui contient uniquement les étudiants ajournés (sans les fantômes)
dfGhosts = dataframe qui contient la liste des fantômes
Category = nom de la colonne sur laquelle on veut faire des analyses statistiques
note = nom de la colonne qui contient la note qu’on veut analyser par catégorie (généralement la moyenne finale)
- sortie :
dfStats
affichage :
- pyphyschemtools.tools4AS.StatsRéussiteParMentionOuParcoursWithAb(dfT, dfADM, dfAJ, dfGhosts, dfAb, Category, note)[source]
- entrée :
dfT = dataframe qui contient toutes les notes, ainsi qu’au moins une catégorisation (exemple : Mention ou Parcours ou Section etc…)
dfADM = dataframe qui contient uniquement les étudiants admis
dfAJ = dataframe qui contient uniquement les étudiants ajournés (sans les fantômes)
dfGhosts = dataframe qui contient la liste des fantômes
dfAb = dataframe qui contient la liste des étudiants qui ont abandonné
Category = nom de la colonne sur laquelle on veut faire des analyses statistiques
note = nom de la colonne qui contient la note qu’on veut analyser par catégorie (généralement la moyenne finale)
- sortie :
dfStats
affichage :
- pyphyschemtools.tools4AS.concat2ApoG(df2Complete, ID_ApoG, dfCC, Col2SaveInCC, IDCC, nomCC)[source]
- entrée :
- df2Complete = dataframe à compléter (merge = ‘left’)
au premier appel, ce soit être le fichier de Référence
ensuite c’est le fichier de notes lui-même, en cours d’update
ID_ApoG = label de la colonne qui contient les numéros étudiants dans le fichier de référence
dfCC = dataframe dont 1 colonne contient les notes de CC
Col2SaveInCC = liste avec les en-têtes de colonnes qui contiennent les colonnes de dfCC à reporter dans dfNotes
IDCC = label de la colonne qui contient les numéros étudiants dans le fichier de notes
nomCC = à ce stade, c’est aussi bien le label de la colonne qui contient les notes que le label de l’épreuve de CC (ex CC1), utilisé pour l’affichage
- sortie :
le dataframe dfNotes. Contient la version concaténée du dataframe d’entrée df2complete et certaines colonnes du dataframe des notes dfCC ([Col2SaveInCC + IDCC + nomCC])
un dataframe dfnotFoundInRef qui contient la liste des étudiants qui sont dans le fichier de notes et pas dans le fichier de référence
- affichages :
liste des étudiants qui sont dans le fichier de notes et pas dans le fichier de référence
- pyphyschemtools.tools4AS.dropColumnsByIndex(df, idropC)[source]
- entrée :
df = dataframe dont on veut supprimer des colonnes
idropC = indices des colonnes dont on veut se débarasser
- sortie :
dfCleaned = dataframe originel dont les colonnes indexées par idropC ont été supprimées
- pyphyschemtools.tools4AS.kdePlotByMentionEtParcours(df, Moyenne, Mention, Parcours, NomGraphique)[source]
- entrée :
df = dataframe qui contient ID, Noms, Prénoms, notes de CC, Moyenne pondérée, Mention et Parcours
Mention = nom de l’en-tête de la colonne qui contient la Mention de diplôme simplifiée d’un étudiant
Parcours = nom de l’en-tête de la colonne qui contient le parcours suivi par un étudiant
- affichage :
1 graphe avec des plots kde par Mention
1 graphe avec des plots kde par Parcours
- sauvegarde :
fichier graphique ‘NomGraphique’ avec les 2 graphes
- pyphyschemtools.tools4AS.plotTauxADMasBars(dfwoSC, dfwSC, xCol, hueCol, NomGraphique)[source]
- entrée :
dfwoSC = dataframe contenant les stats ADM/AJ/Ghosts avant l’application de la seconde chance
dfwSC = dataframe contenant les stats ADM/AJ/Ghosts après l’application de la seconde chance
xCol = nom de la colonne qui contient les taux de réussite
hueCol = nom de la colonne qui contient les paramètres avant ou après seconde chance
NomGraphique = nom du fichier png qui va être sauvé
- affichage :
bar plot de seaborn
- sauvegarde :
fichier graphique ‘NomGraphique’ au format png
- pyphyschemtools.tools4AS.read_excel(xlFile, decimal, name)[source]
- entrée :
xlFile = nom du ficher excel
decimal = “.” ou “,” selon le cas
name = label du dataframe, utilisé pour l’affichage
- sortie :
le dataframe qui contient l’intégralité du fichier excel
le nombre de lignes de ce tableau (à l’exclusion de l’en-tête des colonnes)
- affichage :
statistiques descriptives (describe) de toutes les colonnes, y compris celles qui ne contiennent pas de valeurs numériques
- pyphyschemtools.tools4AS.verifNotes(dfCC, labelNoteCC, nomCC, NI, absents='aabs')[source]
- Parameters:
CC (- nomCC = label de l'épreuve de)
notes (- labelNoteCC = label de la colonne qui contient les)
CC
module (- NI = nombre d'inscrits dans le)
absents (-) –
‘aabs’ : analyser s’il y a des étudiants qui n’ont pas été pointés au CC (défaut)
- ’noabs’ne pas analyser s’il y a des étudiants qui n’ont pas été pointés au CC
(ça n’a plus de sens une fois les fichiers concaténés)
- Returns:
la moyenne et la déviation standard de liste de notes contenues dans le dataframe dfCC
le nombre d’étudiants qui n’ont pas composé au CC
Note
Affiche le nombre d’étudiants avec le label ‘ABS’ et signale les étudiants sans note ni label, ce qui nécessite une vérification du PV.
pyphyschemtools.units module
- class pyphyschemtools.units.Area(value, unit='m2')[source]
Bases:
PhysicalQuantityArea management. Supports SI and Si-related units (m2, hectare) and Imperial units (sq inch, sq ft, acre).
- class pyphyschemtools.units.Density(value, unit='kg/cm3')[source]
Bases:
PhysicalQuantityDensity (Mass per Volume) management. Supports SI (kg/m3) and common lab units (g/cm3, g/mL, lb/ft3).
- class pyphyschemtools.units.Energy(value, unit='J')[source]
Bases:
PhysicalQuantity
- class pyphyschemtools.units.Length(value, unit='m')[source]
Bases:
PhysicalQuantityDistance and Length management. Supports SI (m) and Imperial units (inch, foot, yard, mile, nautical mile).
- class pyphyschemtools.units.Mass(value, unit='kg')[source]
Bases:
PhysicalQuantityMass management.
- class pyphyschemtools.units.MolarMass(value, unit='kg/mol')[source]
Bases:
PhysicalQuantityMolar Mass management for chemical species. Converts between g/mol, kg/mol, and Da (Daltons/amu).
- class pyphyschemtools.units.PhysicalQuantity(value, unit, conversion_map)[source]
Bases:
object
- class pyphyschemtools.units.Pressure(value, unit='Pa')[source]
Bases:
PhysicalQuantityPressure management class (Pa, bar, atm, torr, psi).
- class pyphyschemtools.units.Temperature(value, unit='K')[source]
Bases:
PhysicalQuantity
- class pyphyschemtools.units.Volume(value, unit='m3')[source]
Bases:
PhysicalQuantityVolume management. Supports SI and SI-related units (m3, L) and Imperial units (gallon, quart, pint, fluid ounce). Note: Uses US liquid measures from SciPy.
pyphyschemtools.visualID module
pyphyschemtools.visualID_Eng module
- pyphyschemtools.visualID_Eng.apply_css_style()[source]
Explicitly reads and applies the visualID CSS stylesheet from the package resources.
- class pyphyschemtools.visualID_Eng.bg[source]
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'
- class pyphyschemtools.visualID_Eng.color[source]
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.end()[source]
Terminates the notebook session: displays duration, end time, and the termination logo from package resources.
- class pyphyschemtools.visualID_Eng.fg[source]
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'