pyphyschemtools package
Subpackages
Submodules
pyphyschemtools.Chem3D module
- class pyphyschemtools.Chem3D.XYZData(symbols, positions)
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)
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='file', 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:
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…)
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.
viewer (bool, optional) – If True (default), initializes the py3Dmol viewer and renders the molecule. If False, operates in ‘headless’ mode: only coordinates are processed for calculations (default: True).
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()
- 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- afficher()
- 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)
- 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:
objectA class to handle thermodynamic surface stability analysis and visualization within the tools4pyPhysChem framework.
- 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:
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)
Bases:
objectA helper class to analyze and visualize molecules using RDKit. Provides tools for Lewis structure analysis and advanced 2D drawing.
- 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
- 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, rep3D: bool = False, macrocycle: bool = False, highlightAtoms: list = [], legend: str = '')
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.
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.
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.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, G_exp, headers, A0=1.0, alpha=1.0, k_guess=0.01, verbose=False)
Bases:
object- G0_theo(t, k, G0, Ginf)
Model for Order 0 kinetics.
- G1_theo(t, k, G0, Ginf)
Model for Order 1 kinetics.
- G2_theo(t, k, G0, Ginf)
Model for Order 2 kinetics.
- fit(order=1, k_guess=None)
Fits the chosen kinetic model to the experimental data, with order=order (Default: 1) verbose=True: prints the initial guess vector p0
- get_best_order()
Determines and prints the best model based on the lowest RMSD.
- 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.
- plot_all_fits()
Plots experimental data and all three kinetic models for visual comparison.
pyphyschemtools.spectra module
- class pyphyschemtools.spectra.SpectrumSimulator(sigma_ev=0.3, plotWH=(12, 8), fontSize_axisText=14, fontSize_axisLabels=14, fontSize_legends=12, fontsize_peaks=12, colorS='#3e89be', colorVT='#469cd6')
Bases:
object- plotAbs_lambda_TDDFT(datFiles=None, C0=1e-05, lambdamin=200, lambdamax=800, Amax=2.0, titles=None, linestyles=[], annotateP=[], tP=0.1, resetColors=False, filename=None)
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)
filename – saves figure in a 300 dpi png file if not None (default), with filename=full pathway
- plotAbs_lambda_exp(csvFiles, C0, lambdamin=200, lambdamax=800, Amax=2.0, titles=None, linestyles=[], annotateP=[], tP=0.1, filename=None)
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)
filename (-) – saves figure in a 300 dpi png file if not None (default), with filename=full pathway
- plotEps_lambda_TDDFT(datFile, lambdamin=200, lambdamax=800, epsMax=None, titles=None, tP=10, ylog=False, filename=None)
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)
filename – saves figure in a 300 dpi png file if not None (default), with filename=full pathway
- plotTDDFTSpectrum(wavel, sumInt, wavelTAB, feTAB, tP, ylog, labelSpectrum, colorS='#0000ff', colorT='#0000cf')
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')
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.tools4AS module
- pyphyschemtools.tools4AS.ApplySecondeChance(df, nomCC, nomCCSC, nomCCdelaSC)
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)
- pyphyschemtools.tools4AS.BoiteAMoustachesByMentionEtParcoursHue(df, Moyenne, Mention, Parcours, NomGraphique)
- pyphyschemtools.tools4AS.ComparaisonMoyennesDMCC(df, nomCC1, nomCC2, SeuilBadDMCC1, SeuilGoodDMCC1)
- 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)
- 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)
- 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)
- 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)
- 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)
- 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.ReplaceNanBy0(df, nomCC)
- pyphyschemtools.tools4AS.ReplaceNanBy0OLD(df, nomCC)
- 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)
- 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)
- 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)
- 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)
- 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.checkNoID_DuplicateID(df, dfname, ID, nom, NomPrenom)
- pyphyschemtools.tools4AS.concat2ApoG(df2Complete, ID_ApoG, dfCC, Col2SaveInCC, IDCC, nomCC)
- 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.css_styling()
- pyphyschemtools.tools4AS.dropColumnsByIndex(df, idropC)
- 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)
- 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.mentionD(row, Mention)
- pyphyschemtools.tools4AS.parcours(row, Parcours)
- pyphyschemtools.tools4AS.plotTauxADMasBars(dfwoSC, dfwSC, xCol, hueCol, NomGraphique)
- 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)
- 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')
- 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.visualID module
- pyphyschemtools.visualID.chrono_show()
- pyphyschemtools.visualID.chrono_start()
- pyphyschemtools.visualID.chrono_stop(hdelay=False)
- class pyphyschemtools.visualID.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.css_styling(pwy)
- pyphyschemtools.visualID.display_md(text)
- pyphyschemtools.visualID.end(pwy)
- pyphyschemtools.visualID.hdelay(sec)
- pyphyschemtools.visualID.hdelay_ms(delay)
- pyphyschemtools.visualID.init(pwy)
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- BLINK = '\x1b[5m'
- BOLD = '\x1b[1m'
- ITALIC = '\x1b[3m'
- OFF = '\x1b[0m'
- UNDERL = '\x1b[4m'
- blink = '\x1b[25m'
- bold = '\x1b[21m'
- italic = '\x1b[23m'
- underl = '\x1b[24m'
- pyphyschemtools.visualID_Eng.init(Research=False)
Initializes the notebook environment: applies CSS, displays the banner, and shows hostname/time.