01 / 31
AI for Materials Science  ·  Lecture 01 (Complete Zero-to-Cheminformatics Edition)

Python, Tabular Data Analysis, Scientific Plotting &
Molecular Representations for Materials Science

Zesheng Liu
Laboratory of Organic Electronics, Linköping University
Modules 01a–01d  |  Zero-Coding Foundations + AqSolDB (N = 9,482) & Organic Semiconductors
Linköping University Laboratory of Organic Electronics

Lecture 01 roadmap: four foundational building blocks

Unifying domain thread: why large π-conjugated cores transport charges well yet dissolve poorly—and how side chains fix it
PART 1 · NOTEBOOK 01a

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.

PART 2 · NOTEBOOK 01b

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.

PART 3 · NOTEBOOK 01c

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.

PART 4 · NOTEBOOK 01d

RDKit Molecular Representations

SMILES & Canonical deduplication, traversing conjugated vs. aliphatic bonds, 200+ physicochemical descriptors, Morgan Bit/Count fingerprints, Murcko scaffolds, and SMARTS substructure search.

Goal of Lecture 01: turn raw chemical structures and messy spreadsheets into clean numerical matrices ready for Lecture 02 ML.
Linköping University Laboratory of Organic Electronics

Getting started: how Jupyter Notebook & Google Colab work

Combining an electronic lab notebook (Markdown text + equations) with an interactive Python execution kernel
M
Markdown Cell — Lab Notes & Physics
Double-click to edit formatted text, chemical hypotheses, and LaTeX equations; press Shift + Enter to render.
1
# Comments after '#' are ignored by Python
topic = "Organic Field-Effect Transistors"
print("Research area:", topic)
Code Cell: Press Shift + Enter to execute; the last expression in a cell automatically displays its value.
⚠️ #1 BEGINNER PITFALL · HIDDEN STATE ORDER

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.

GOLDEN HABIT BEFORE SAVING

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.

Treat every Notebook like a reproducible wet-lab protocol: if Restart & Run All succeeds from top to bottom, your workflow is solid.
Linköping University Laboratory of Organic Electronics

Variables, four core data types, and scientific arithmetic

Storing molecular properties in named variables and understanding binary floating-point precision
Variable Assignmenttype(x)Meaning in Materials
name = "pentacene"strText / SMILES string (in quotes)
homo = -5.0floatContinuous measurement (eV)
n_rings = 5intExact integer count (rings, atoms)
is_p_type = TrueboolLogical 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).

ARITHMETIC OPERATORS

gap = lumo - homo  ·  wl_nm = 1240 / gap
Power uses ** (2 ** 10 → 1024, NOT ^!), integer division //, remainder %, and in-place update n_atoms += 14.

WHY DOES -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.

Check unknown variable types anytime with type(x), remember ** for exponents, and format floats cleanly rather than fearing 1.7999999999999998.
Linköping University Laboratory of Organic Electronics

Strings, f-string formatting, and zero-based indexing on SMILES

Two iron laws of Python indexing: positions always start at 0, and slices [start:stop] exclude stop
f"{name} has HOMO = {homo:.2f} eV, LUMO = {lumo:.2f} eV → Eg = {lumo - homo:.2f} eV"
Output: pentacene has HOMO = -5.00 eV, LUMO = -3.20 eV → Eg = 1.80 eV  (:.2f formats to 2 decimal places automatically)
Thiophene SMILES: s = "c1ccsc1" (length = 7) c1c csc1 012 3456 (or −1) s[1:4] → "1cc" (stops BEFORE index 4!)
Essential string tools for chemistry data:  "s" in s (True)  ·  s.count("c") (4)  ·  "CCCCCC" + s (attach hexyl chain)  ·  line.strip().split(",")
Zero-based indexing (0, 1, 2…) and half-open slicing ([a:b]) apply identically to Python strings, lists, NumPy arrays, and Pandas rows.
Linköping University Laboratory of Organic Electronics

Organizing batches of materials: list, tuple, and dict

Choosing the right Python container—and combining a list of dictionaries to form a prototype data table
1 · LIST [...] (MUTABLE)

Ordered Batch Sequence

acenes = ["benzene", "naphthalene"]
acenes.append("anthracene")
Supports len(), min(), max(), sum(), and sorted() for replicate device measurements.

2 · TUPLE (...) (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.

3 · DICT {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!

molecules = [ {"name": "pentacene", "homo": -5.0, "lumo": -3.2}, {"name": "rubrene", "homo": -5.4, "lumo": -3.1} ]
Bridge to Section 01b: A list of dictionaries (rows of named properties) is the exact conceptual blueprint of a pandas.DataFrame!
Use list for ordered collections, tuple for fixed dimensions, and dict for self-documenting key–value records.
Linköping University Laboratory of Organic Electronics

Control flow: if screening, for loops & list comprehensions

Automating candidate filtering and repetitive batch calculations—mind the trailing colon : and 4-space indent!
CONDITIONAL SCREENING (if / elif / else)
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!).

4-LINE LOOP → 1-LINE LIST COMPREHENSION
# 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).

Indentation is syntax in Python: every block inside if:, for:, or def: is defined by its 4-space indent.
Linköping University Laboratory of Organic Electronics

Reusable functions (def) and vectorized NumPy arrays

Replacing slow element-by-element Python loops with C-speed array arithmetic: gaps = lumos - homos
Reusable functions (def) and vectorized NumPy arrays
Converting Python lists into np.array(...) unlocks element-wise math, boolean filtering (gaps < 2.2), and ~100× faster execution.
Linköping University Laboratory of Organic Electronics

Reading Python error tracebacks without panic

Always read a red traceback from the very bottom line upward: error type + exact offending line arrow ---->
Error TypeTypical Beginner TriggerInstant 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).
Red tracebacks are diagnostic instruments, not failures—90% of beginner bugs fall into these five one-line fixes.
Linköping University Laboratory of Organic Electronics

From plain-text files (with open) to pandas.DataFrame

In real ML projects, ~80% of engineering effort goes into reading, auditing, filtering, and cleaning experimental tables
RAW TEXT LOGS & INSTRUMENT OUTPUTS

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.

PROGRAMMABLE EXCEL FOR 10⁴+ ROWS

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.

Use with open() + .strip() for raw text files, and pd.read_csv() / pd.read_excel() for structured spreadsheets.
Linköping University Laboratory of Organic Electronics

First contact with a dataset: auditing AqSolDB (N = 9,482)

Always run df.shape, df.info(), and df.describe() to inspect ranges, units, and skewness before modeling
First contact with a dataset: auditing AqSolDB (N = 9,482)
Comparing mean vs. median (50%) immediately reveals left-skewed insoluble tails in logS and right-skewed tails in MolWt/TPSA.
Linköping University Laboratory of Organic Electronics

Selecting columns, row indexing (iloc vs. loc) & boolean filtering

Mastering multi-condition chemical queries without tripping over Pandas operator precedence
OperationPandas SyntaxKey Rule to Remember
Single / Multi Columndf["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 Searchdf[df["Name"].str.contains("benzene", case=False)]Access vectorized string methods through the .str accessor
⚠️ CLASSIC PANDAS SYNTAX TRAP · MULTI-CONDITION FILTERING
pahs = df[ (df["NumAromaticRings"] >= 3) & (df["NumHeteroatoms"] == 0) ]
In Pandas, NEVER write and / or—you must use & (AND), | (OR), ~ (NOT), and wrap every individual condition in parentheses (...)!
Boolean masking lets you filter 10,000 compounds down to target candidate families (e.g., pure PAHs or hydrophobic dyes) in one line.
Linköping University Laboratory of Organic Electronics

Group-by statistics: verifying “more aromatic rings → lower solubility”

df.groupby("NumAromaticRings")["Solubility"].agg(["count", "mean", "std"]) across 9,482 compounds
Group-by statistics: verifying “more aromatic rings → lower solubility”
Mean logS drops steadily from −2.25 (0 rings) to −6.42 (5 rings), but groups with ≥6 rings have tiny N (<30)—always inspect count!
Linköping University Laboratory of Organic Electronics

Merging tables (merge), missing values (NaN), and clean export

Cross-referencing candidate lists against reference databases without corrupting scientific integrity
RELATIONAL JOIN · pd.merge(..., how="left")

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.

🚫 SCIENTIFIC DATA INTEGRITY RULE

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"]).

CLEAN DISK EXPORT

Always save with df.to_csv("clean.csv", index=False) so Pandas does not write row numbers as a spurious Unnamed: 0 column!

Missing values (NaN) often reflect physical measurement limits (e.g., ultra-low solubility) rather than random clerical typos.
Linköping University Laboratory of Organic Electronics

Scientific visualization: anatomy of a publication-grade Matplotlib plot

Summary statistics hide multimodality, nonlinearity, and outliers—always visualize distributions and relationships first
MULTI-PANEL OBJECT-ORIENTED TEMPLATE
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+.

Prefer fig, axes = plt.subplots(...) for multi-panel journal figures and export vector .svg/.pdf for razor-sharp typography.
Linköping University Laboratory of Organic Electronics

Empirical curve fitting and our first extrapolation warning

Fitting Acene optical gaps (N = 1–5) via np.polyfit(1/N, gap, deg=1) → Egap ≈ 1.01 + 3.92 / N eV
Empirical curve fitting and our first extrapolation warning
Empirical equations fit N = 1–5 cleanly, yet extrapolating to N ≥ 6 fails as open-shell diradical character and air oxidation emerge!
Linköping University Laboratory of Organic Electronics

Exploring 9,482 compounds: 1D distributions and 3-variable scatter

Encoding three dimensions simultaneously: x = hydrophobicity (MolLogP), y = solubility (logS), color = aromatic rings
Exploring 9,482 compounds: 1D distributions and 3-variable scatter
As aromatic ring count rises (blue → red), molecules systematically shift toward high MolLogP and ultra-low water solubility.
Linköping University Laboratory of Organic Electronics

Statistical visualization: why boxplots reveal what averages hide

Inspecting within-group dispersion via sns.boxplot (a) and bivariate linear trend via sns.regplot (b)
Statistical visualization: why boxplots reveal what averages hide
Even among 2-ring molecules, logS spans 11 orders of magnitude (+1 to −10)—proving a single descriptor cannot predict solubility accurately!
Linköping University Laboratory of Organic Electronics

The ceiling nobody mentions: how noisy is logS itself?

AqSolDB kept SD and Ocurrences—the spread across the independent sources it merged—so our label error is measurable, not hypothetical
Distribution of inter-source disagreement across the 2,140 AqSolDB compounds measured by two or more sources Eight well-known compounds whose reported aqueous solubility differs by more than one log unit between sources
No model can be more accurate than its labels: RMS SD = 0.52 logS units is the floor every RMSE in Lecture 02 must be read against—and the 7,342 single-source compounds are not cleaner, merely unaudited.
Linköping University Laboratory of Organic Electronics

Correlation matrix heatmap: spotting top predictors & collinearity

Pairwise Pearson correlation r ∈ [−1, +1] across Solubility and seven core physicochemical descriptors
Correlation matrix heatmap: spotting top predictors & collinearity
MolLogP correlates most strongly with logS (r = −0.65), while strong feature–feature correlations (r = 0.86) foreshadow OLS multicollinearity.
Linköping University Laboratory of Organic Electronics

SMILES syntax: encoding 2D molecular graphs into 1D strings

Simplified Molecular Input Line Entry System—and how RDKit validates chemical valence rules automatically
Chemical FeatureSMILES RuleExample
Aliphatic AtomsUppercase symbols (implicit H)"CCO" (Ethanol), "CCCCCC" (Hexane)
Double / Triple Bonds= and # symbols"C=O" (Formaldehyde), "C#N" (Nitrile)
Side BranchesParentheses (...)"CC(=O)O" (Acetic acid)
RingsMatching digit pair opens/closes ring"C1CCCCC1" (Cyclohexane)
AromaticityLowercase c, n, o, s (Hückel π-ring)"c1ccccc1" (Benzene), "c1ccsc1" (Thiophene)
Salts / MixturesDisconnected components joined by ."[Na+].[Cl-]" (Sodium chloride)
VALID PARSING → Mol OBJECT

mol = Chem.MolFromSmiles("c1ccsc1")
Builds an internal mathematical graph of Atom nodes, Bond edges, valence, and aromaticity.

INVALID CHEMISTRY → RETURNS None!

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!

RDKit acts as a built-in chemical referee: any SMILES violating valence or Kekulé aromaticity returns None upon parsing.
Linköping University Laboratory of Organic Electronics

Organic semiconductor gallery & Canonical SMILES deduplication

"c1ccsc1", "s1cccc1", and "C1=CSC=C1" all map via Chem.MolToSmiles(mol) to unique Canonical "c1ccsc1"
Organic semiconductor gallery & Canonical SMILES deduplication
Always canonicalize SMILES when merging literature datasets—otherwise duplicate molecules split across train & test cause data leakage!
Linköping University Laboratory of Organic Electronics

Inside an RDKit Mol graph: conjugated core vs. solubilizing chain

Dissecting 3-hexylthiophene (P3HT monomer) via mol.GetAtoms() and bond.GetIsConjugated()
Inside an RDKit Mol graph: conjugated core vs. solubilizing chain
RDKit directly separates delocalized π-conjugated transport bonds (coral) from flexible sp³ alkyl side-chain bonds (blue) that enable ink processing.
Linköping University Laboratory of Organic Electronics

Molecules to numbers (I): global physicochemical descriptors

Quantifying side-chain engineering on Pentacene → TIPS-Pentacene and BTBT → C8-BTBT (210+ RDKit descriptors)
 Molecules to numbers (I): global physicochemical descriptors
Grafting TIPS or C8 chains jumps NumRotatableBonds (0 → 8 / 14) and lipophilicity MolLogP (5.3 → 11.1) while keeping core π-rings intact.
Linköping University Laboratory of Organic Electronics

Molecules to numbers (II): Morgan circular fingerprints (ECFP)

Encoding local atomic neighborhoods of radius r = 0, 1, 2 into a fixed-length 2048-dimensional numerical vector
RADIUS r = 0 · ATOM IDENTITY

Central Heavy Atom

Records element, hybridization, charge, and ring membership of each atom (e.g., aromatic sp² carbon vs. sulfur atom in thiophene).

RADIUS r = 1 → 2 · NEIGHBORHOODS

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).

HASHING INTO 2048 SLOTS

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!

fpgen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
bit_fp = fpgen.GetFingerprint(mol)       # Binary 0/1 vector (2048,)
cnt_fp = fpgen.GetCountFingerprint(mol)  # Integer counts (2048,)
Descriptors summarize macroscopic whole-molecule physics; Morgan fingerprints catalog every local atomic fragment without human bias.
Linköping University Laboratory of Organic Electronics

Tanimoto similarity and the binary fingerprint blind spot

T(A, B) = |A ∩ B| / |A ∪ B| ∈ [0, 1]  ·  Pairwise similarity across 8 organic electronic molecules
Tanimoto similarity and the binary fingerprint blind spot
Binary Bit FP gives Tetracene vs. Pentacene a false 1.00 similarity (same local fragments!)—Count FP restores distinction (0.85).
Linköping University Laboratory of Organic Electronics

Extracting the conjugated core: Bemis–Murcko scaffolds

MurckoScaffold.GetScaffoldForMol(mol) prunes terminal side chains while preserving all ring systems and linkers
Extracting the conjugated core: Bemis–Murcko scaffolds
Stripping hexyl, C8, and TIPS chains recovers pure Thiophene, BTBT, and Pentacene cores—the basis of Murcko Scaffold Splitting in Lecture 02e!
Linköping University Laboratory of Organic Electronics

Real-world data hygiene: auditing AqSolDB with RDKit + Pandas

Public databases always contain formatting defects and multi-component salts—clean first, model second!
STANDARD CLEANING PIPELINE ON solubility.csv
# 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())
DEFECT 1 · 2 INVALID VALENCE RECORDS

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.

DEFECT 2 · 1,044 IONIC SALTS & MIXTURES

Over 10% of rows contain disconnected counter-ions (.)—explaining why neutral 2D lipophilicity misclassifies charged metal soaps in Lecture 02d!

Combining Pandas .apply() with RDKit validation transforms raw solubility.csv (9,482 rows) into our verified 9,480-molecule dataset.
Linköping University Laboratory of Organic Electronics

SMARTS substructure search: proving our conjugated-core hypothesis

Graph matching via mol.HasSubstructMatch(Chem.MolFromSmarts("c1ccc2cc3ccccc3cc2c1")) across 9,480 molecules
SMARTS substructure search: proving our conjugated-core hypothesis
Compounds containing a rigid 3-ring anthracene core average ΔlogS = −4.04 lower (~10,000× less soluble!) than the rest of AqSolDB.
Linköping University Laboratory of Organic Electronics

Five discoveries in Lecture 01 that directly shape Lecture 02

Every data quirk we uncovered during exploratory analysis becomes a central modeling principle in Supervised Learning
Discovery in Lecture 01Where FoundConsequence & 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).
Good exploratory data analysis (Lecture 01) already anticipates 80% of the modeling pitfalls in machine learning (Lecture 02).
Linköping University Laboratory of Organic Electronics

Summary (Take home notes)

  • Python & NumPy essentials (01a): Master 0-based indexing, half-open slicing [a:b], dictionaries, list comprehensions, reusable functions, and vectorized np.array operations.
  • Pandas table wrangling (01b): Inspect datasets first with describe(), wrap multi-condition filters in (cond1) & (cond2), check sample count alongside groupby means, 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 / .pdf with physical units.
  • RDKit molecular representations (01d): Sanitize SMILES (catching None), 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).
Linköping University Laboratory of Organic Electronics

Thanks for your listening

Any question contact: Zesheng.liu@liu.se
AI for Materials Science  ·  Interactive Notebooks 01a–01e
Linköping University Laboratory of Organic Electronics