Python, Tabular Data Analysis, Scientific Plotting &
Molecular Representations for Materials Science
Lecture 01 roadmap: four foundational building blocks
Python, Jupyter & NumPy Crash Course
Notebook cell workflow, variables & 4 core types, f-strings & 0-based slicing, list / tuple / dict, if & for loops, reusable functions, NumPy vectorization, and reading error tracebacks.
File I/O & Pandas Data Tables
Safe text I/O with with open(...), loading 9,482 molecules into DataFrame, describe() checkups, iloc / loc & boolean filtering, groupby statistics, table merges, and handling NaN.
Scientific Visualization
Publication-ready Matplotlib figures, empirical 1/N bandgap fitting & extrapolation pitfalls, histograms, 3-variable scatter plots, boxplots of within-group spread, and correlation heatmaps.
RDKit Molecular Representations
SMILES & Canonical deduplication, traversing conjugated vs. aliphatic bonds, 200+ physicochemical descriptors, Morgan Bit/Count fingerprints, Murcko scaffolds, and SMARTS substructure search.
Getting started: how Jupyter Notebook & Google Colab work
Shift + Enter to render.topic = "Organic Field-Effect Transistors"
print("Research area:", topic)
Shift + Enter to execute; the last expression in a cell automatically displays its value.Watch the Bracket Counter [1], [2]!
Python remembers variables in the chronological order you ran the cells—NOT top-to-bottom page order! Running cell 8 before cell 2 causes mysterious errors.
Kernel → Restart & Run All
Whenever variables get tangled—or right before sharing a notebook—click Restart & Run All to verify everything runs cleanly from line 1.
Restart & Run All succeeds from top to bottom, your workflow is solid.Variables, four core data types, and scientific arithmetic
| Variable Assignment | type(x) | Meaning in Materials |
|---|---|---|
name = "pentacene" | str | Text / SMILES string (in quotes) |
homo = -5.0 | float | Continuous measurement (eV) |
n_rings = 5 | int | Exact integer count (rings, atoms) |
is_p_type = True | bool | Logical switch (True / False) |
Naming rules: Use lowercase + underscores (band_gap, mol_3ht). Cannot start with a digit (3ht = ... ❌ SyntaxError) and strictly case-sensitive (homo ≠ HOMO).
gap = lumo - homo · wl_nm = 1240 / gap
Power uses ** (2 ** 10 → 1024, NOT ^!), integer division //, remainder %, and in-place update n_atoms += 14.
-3.2 - (-5.0) PRINT 1.7999999999999998?Computers store decimals in base-2 (binary), causing a tiny ~10−16 rounding tail—not a bug in your code! Use round(gap, 2) or formatted f-strings f"{gap:.2f}" when displaying results.
type(x), remember ** for exponents, and format floats cleanly rather than fearing 1.7999999999999998.Strings, f-string formatting, and zero-based indexing on SMILES
0, and slices [start:stop] exclude stoppentacene has HOMO = -5.00 eV, LUMO = -3.20 eV → Eg = 1.80 eV (:.2f formats to 2 decimal places automatically)"s" in s (True) · s.count("c") (4) · "CCCCCC" + s (attach hexyl chain) · line.strip().split(",")
0, 1, 2…) and half-open slicing ([a:b]) apply identically to Python strings, lists, NumPy arrays, and Pandas rows.Organizing batches of materials: list, tuple, and dict
[...] (MUTABLE)Ordered Batch Sequence
acenes = ["benzene", "naphthalene"]
acenes.append("anthracene")
Supports len(), min(), max(), sum(), and sorted() for replicate device measurements.
(...) (IMMUTABLE)Read-Only Coordinates
lattice = (5.92, 7.68, 15.6)
Cannot be modified accidentally once created! Used for crystal unit-cell constants (a, b, c), 3D (x, y, z), and matrix .shape.
{key: val}Named Property Record
mol = {"name": "rubrene", "homo": -5.4, "lumo": -3.1}
Look up values explicitly by name mol["homo"] instead of guessing which column index is which!
pandas.DataFrame!
list for ordered collections, tuple for fixed dimensions, and dict for self-documenting key–value records.Control flow: if screening, for loops & list comprehensions
: and 4-space indent!if gap < 2.0 and mobility > 0.5:
status = "Promising OFET candidate"
elif gap < 2.5:
status = "Wide-gap backup"
else:
status = "Reject"
Combine rules with and, or, not; test equality with double == (single = is variable assignment!).
# Standard 4-line loop:
gaps = []
for m in molecules:
gaps.append(m["lumo"] - m["homo"])
# Pythonic 1-line List Comprehension:
gaps = [m["lumo"] - m["homo"] for m in molecules]
Loop helpers: range(n) (0 to n−1), enumerate(seq) (index + item), and zip(list1, list2) (pair two lists).
if:, for:, or def: is defined by its 4-space indent.Reusable functions (def) and vectorized NumPy arrays
gaps = lumos - homosnp.array(...) unlocks element-wise math, boolean filtering (gaps < 2.2), and ~100× faster execution.Reading Python error tracebacks without panic
---->| Error Type | Typical Beginner Trigger | Instant Fix |
|---|---|---|
NameError |
name 'hom' is not defined |
Check spelling/capitalization (homo vs hom), OR run the cell above where the variable was defined! |
TypeError |
"Bandgap = " + 1.8 or [1, 2] - [3, 4] |
Use an f-string f"Bandgap = {1.8}" for text; convert lists to np.array(...) before subtracting! |
IndexError |
acenes[5] on a 5-element list |
Remember 0-based indexing: a 5-item list has valid indices 0, 1, 2, 3, 4 (or -1 for last). |
KeyError |
df["Solublity"] (typo in column name) |
Print df.columns or mol.keys() and copy the exact column/key string. |
SyntaxError |
Missing colon :, unmatched ), or 3ht = 1 |
Check the caret ^ pointer (and the line immediately above it for unclosed parentheses). |
From plain-text files (with open) to pandas.DataFrame
Context Manager with open(...)
# Safely write & auto-close file:
with open("osc_names.txt", "w") as f:
f.write("\n".join(osc_list))
# Read lines & strip trailing '\n':
with open("osc_names.txt", "r") as f:
names = [line.strip() for line in f]
Ideal for custom DFT/VASP logs or molecule lists; automatically closes the file even if an error occurs.
pandas.DataFrame & Series
import pandas as pd
df = pd.read_csv("data/solubility.csv")
print(df.shape) # (9482, 26)
df.head(3) # Preview first 3 rows
DataFrame: 2D table with named columns & row index.Series: A single extracted column (df["Solubility"]) supporting fast vectorized stats.
with open() + .strip() for raw text files, and pd.read_csv() / pd.read_excel() for structured spreadsheets.First contact with a dataset: auditing AqSolDB (N = 9,482)
df.shape, df.info(), and df.describe() to inspect ranges, units, and skewness before modelingmean vs. median (50%) immediately reveals left-skewed insoluble tails in logS and right-skewed tails in MolWt/TPSA.Selecting columns, row indexing (iloc vs. loc) & boolean filtering
| Operation | Pandas Syntax | Key Rule to Remember |
|---|---|---|
| Single / Multi Column | df["MolWt"] / df[["Name", "Solubility"]] | Double brackets [[...]] pass a list of column names → returns a sub-DataFrame |
Position Slice (iloc) | df.iloc[0:5, 0:3] | Pure 0-based integer positions (exact same half-open rule as Python lists) |
Label Lookup (loc) | df.loc[idx_max, ["Name", "MolWt"]] | Uses actual index label (e.g. from df["MolWt"].idxmax()) and column names |
| String Search | df[df["Name"].str.contains("benzene", case=False)] | Access vectorized string methods through the .str accessor |
and / or—you must use & (AND), | (OR), ~ (NOT), and wrap every individual condition in parentheses (...)!
Group-by statistics: verifying “more aromatic rings → lower solubility”
df.groupby("NumAromaticRings")["Solubility"].agg(["count", "mean", "std"]) across 9,482 compoundscount!Merging tables (merge), missing values (NaN), and clean export
Why Did Pentacene Turn Into NaN?
When left-joining an organic semiconductor table onto AqSolDB by molecule name, benzene (−1.64) and anthracene (−6.59) match—while pentacene shows Solubility = NaN!
Physical reason: Pentacene is so insoluble in water that AqSolDB has no measured entry. how="left" keeps all left-table candidates; how="inner" keeps only matched rows.
Never Fabricate .fillna(0) on Labels!
Replacing missing solubility NaN with 0 tells your ML model Pentacene dissolves at 1 mol/L! Drop unlabeled rows via df.dropna(subset=["Solubility"]).
Always save with df.to_csv("clean.csv", index=False) so Pandas does not write row numbers as a spurious Unnamed: 0 column!
NaN) often reflect physical measurement limits (e.g., ultra-low solubility) rather than random clerical typos.Scientific visualization: anatomy of a publication-grade Matplotlib plot
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
axes[0].hist(df["TPSA"], bins=40)
axes[0].set_xlabel("TPSA (Ų)") # Include units!
axes[0].set_ylabel("Count")
axes[1].scatter(df["MolLogP"], df["Solubility"],
s=8, alpha=0.4) # Avoid overplotting
axes[1].set_xlabel("MolLogP")
axes[1].set_ylabel("logS (mol/L)")
fig.savefig("figure1.svg") # Vector export!
1. Mandatory Physical Units
Every axis label must state both quantity and unit: Optical gap (eV), MolWt (g/mol), logS (mol/L).
2. Tame Dense Scatter Overplotting
With 9,482 points, default markers fuse into a solid ink blot—shrink marker size s and lower opacity alpha.
3. Vector (.svg / .pdf) vs. Bitmap
Export .svg or .pdf for slides and LaTeX papers (infinite zoom clarity), or .png at dpi=300+.
fig, axes = plt.subplots(...) for multi-panel journal figures and export vector .svg/.pdf for razor-sharp typography.Empirical curve fitting and our first extrapolation warning
np.polyfit(1/N, gap, deg=1) → Egap ≈ 1.01 + 3.92 / N eVExploring 9,482 compounds: 1D distributions and 3-variable scatter
MolLogP), y = solubility (logS), color = aromatic ringsMolLogP and ultra-low water solubility.Statistical visualization: why boxplots reveal what averages hide
sns.boxplot (a) and bivariate linear trend via sns.regplot (b)The ceiling nobody mentions: how noisy is logS itself?
SD and Ocurrences—the spread across the independent sources it merged—so our label error is measurable, not hypotheticalCorrelation matrix heatmap: spotting top predictors & collinearity
Solubility and seven core physicochemical descriptorsMolLogP correlates most strongly with logS (r = −0.65), while strong feature–feature correlations (r = 0.86) foreshadow OLS multicollinearity.SMILES syntax: encoding 2D molecular graphs into 1D strings
| Chemical Feature | SMILES Rule | Example |
|---|---|---|
| Aliphatic Atoms | Uppercase symbols (implicit H) | "CCO" (Ethanol), "CCCCCC" (Hexane) |
| Double / Triple Bonds | = and # symbols | "C=O" (Formaldehyde), "C#N" (Nitrile) |
| Side Branches | Parentheses (...) | "CC(=O)O" (Acetic acid) |
| Rings | Matching digit pair opens/closes ring | "C1CCCCC1" (Cyclohexane) |
| Aromaticity | Lowercase c, n, o, s (Hückel π-ring) | "c1ccccc1" (Benzene), "c1ccsc1" (Thiophene) |
| Salts / Mixtures | Disconnected components joined by . | "[Na+].[Cl-]" (Sodium chloride) |
mol = Chem.MolFromSmiles("c1ccsc1")
Builds an internal mathematical graph of Atom nodes, Bond edges, valence, and aromaticity.
Chem.MolFromSmiles("c1cccc1") (5 aromatic carbons violate Hückel/Kekulé rules!) does not crash Python—it logs a warning and returns None. Always filter None before featurizing!
None upon parsing.Organic semiconductor gallery & Canonical SMILES deduplication
"c1ccsc1", "s1cccc1", and "C1=CSC=C1" all map via Chem.MolToSmiles(mol) to unique Canonical "c1ccsc1"Inside an RDKit Mol graph: conjugated core vs. solubilizing chain
3-hexylthiophene (P3HT monomer) via mol.GetAtoms() and bond.GetIsConjugated()Molecules to numbers (I): global physicochemical descriptors
Pentacene → TIPS-Pentacene and BTBT → C8-BTBT (210+ RDKit descriptors)NumRotatableBonds (0 → 8 / 14) and lipophilicity MolLogP (5.3 → 11.1) while keeping core π-rings intact.Molecules to numbers (II): Morgan circular fingerprints (ECFP)
Central Heavy Atom
Records element, hybridization, charge, and ring membership of each atom (e.g., aromatic sp² carbon vs. sulfur atom in thiophene).
Circular Substructures
Expands 1 and 2 bonds outward around every atom to capture functional groups, ortho/meta/para substitution, and ring junctions (ECFP4 ≈ radius=2).
Bit FP vs. Count FP
Bit FP (GetFingerprint): Marks presence/absence only (0 or 1).
Count FP (GetCountFingerprint): Records how many times each fragment occurs!
bit_fp = fpgen.GetFingerprint(mol) # Binary 0/1 vector (2048,)
cnt_fp = fpgen.GetCountFingerprint(mol) # Integer counts (2048,)
Tanimoto similarity and the binary fingerprint blind spot
Tetracene vs. Pentacene a false 1.00 similarity (same local fragments!)—Count FP restores distinction (0.85).Extracting the conjugated core: Bemis–Murcko scaffolds
MurckoScaffold.GetScaffoldForMol(mol) prunes terminal side chains while preserving all ring systems and linkersReal-world data hygiene: auditing AqSolDB with RDKit + Pandas
# 1. Parse all 9,482 SMILES strings
df["mol"] = df["SMILES"].apply(Chem.MolFromSmiles)
print(df["mol"].isna().sum()) # Catches 2 None rows!
# 2. Drop unparseable structures → 9,480 valid
df = df.dropna(subset=["mol"]).reset_index(drop=True)
# 3. Flag multi-component salts / mixtures ('.')
is_salt = df["SMILES"].str.contains("\.")
print(is_salt.sum()) # 1,044 salt records!
# 4. Compute custom features via lambda
df["n_heavy"] = df["mol"].apply(lambda m: m.GetNumAtoms())
Two raw entries contain malformed formal charges ([NH++], [CH-]) that fail Kekulé sanitization → removing them yields the clean 9,480-molecule benchmark used in Lecture 02.
Over 10% of rows contain disconnected counter-ions (.)—explaining why neutral 2D lipophilicity misclassifies charged metal soaps in Lecture 02d!
.apply() with RDKit validation transforms raw solubility.csv (9,482 rows) into our verified 9,480-molecule dataset.SMARTS substructure search: proving our conjugated-core hypothesis
mol.HasSubstructMatch(Chem.MolFromSmarts("c1ccc2cc3ccccc3cc2c1")) across 9,480 moleculesFive discoveries in Lecture 01 that directly shape Lecture 02
| Discovery in Lecture 01 | Where Found | Consequence & Solution in Lecture 02 |
|---|---|---|
| 1. Empirical 1/N fit breaks for long acenes | 01c Bandgap fit |
Pure statistical models fail at Extrapolation; tree ensembles flatline on Pentacene (020, 02c). |
| 2. Strong feature–feature correlations (r = 0.86) | 01c Heatmap |
Causes opposing OLS weights to explode; solved via Ridge (L2) / Lasso (L1) & Permutation Importance (02a, 02d). |
| 3. Multiple SMILES strings for one molecule | 01d Thiophene |
Canonical SMILES deduplication prevents identical molecules from leaking across train & test sets (02e). |
| 4. Binary Bit FP = 1.00 on Tetracene vs. Pentacene | 01d Tanimoto |
Count Fingerprints beat Bit FP in regression (1.27 vs 1.43) and fix Pentacene’s Applicability Domain trap (02c, 02e). |
| 5. Side chains mask shared conjugated cores | 01d Scaffolds |
Bemis–Murcko Scaffold Split tests true out-of-family generalization beyond close derivatives (02e). |
Summary (Take home notes)
- Python & NumPy essentials (
01a): Master 0-based indexing, half-open slicing[a:b], dictionaries, list comprehensions, reusable functions, and vectorizednp.arrayoperations. - Pandas table wrangling (
01b): Inspect datasets first withdescribe(), wrap multi-condition filters in(cond1) & (cond2), check samplecountalongsidegroupbymeans, and never fabricate.fillna(0)on missing targets. - Publication visualization (
01c): Combine histograms, multi-variable scatter plots, boxplots (revealing within-group spread), and correlation heatmaps; export vector.svg/.pdfwith physical units. - RDKit molecular representations (
01d): Sanitize SMILES (catchingNone), deduplicate via Canonical SMILES, complement macroscopic descriptors with Count Morgan Fingerprints, and extract Murcko scaffolds. - Quantitative domain proof: Across 9,480 AqSolDB compounds, SMARTS graph search confirms rigid anthracene cores lower solubility by ~4 logS units (~10,000×), motivating flexible side-chain design (
C8-BTBT,TIPS-Pentacene).
Thanks for your listening
01a–01e