Microarray Differential Expression in Python: GSE32018 (B-cell lymphoma)

Python companion to Lessons 2.1–2.5, run chunk by chunk

How to use this notebook

Open this file in RStudio and run it one chunk at a time with the green ▶ button on each chunk (or Cmd + Shift + Enter with your cursor inside it). Read the text above each chunk first, run it, then check the output against the ✅ Checkpoint before moving on.

If a checkpoint doesn’t match, stop there. Every later chunk depends on the earlier ones, so a problem in Step 1 will show up as a confusing error in Step 3.

NoteFirst-time setup in RStudio (run once)

RStudio runs Python chunks through the reticulate package. Run these lines once in the R console (prompt >), not in a Python chunk:

#| eval: false
install.packages("reticulate")
reticulate::virtualenv_create("r-reticulate")
reticulate::py_install(c("GEOparse", "pandas", "numpy", "scipy", "scikit-learn",
                         "matplotlib", "seaborn"),
                       envname = "r-reticulate", pip = TRUE)

⚠️ Now restart R: Session → Restart R. RStudio only picks up the new Python environment after a restart. (The install itself can take a few minutes.)

Then restart R (Session → Restart R). The install can take a few minutes.

Don’t use pip in a separate Terminal. It often installs into a different Python, and then you get ModuleNotFoundError here.

Part 1: Load and clean the data

1.0 Imports and the shared colour palette

These are the same libraries as the R lesson’s library() calls. The palette is the one we used in R, so your Python plots will match your R plots group for group.

from pathlib import Path

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import seaborn as sns
from scipy import special, stats
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import GEOparse

GROUP_COLORS = {
    "Healthy": "#4CAF50",
    "DLBCL":   "#E91E63",
    "CLL":     "#2196F3",
    "FL":      "#FF9800",
    "MALT":    "#9C27B0",
    "MCL":     "#F44336",
    "NMZL":    "#00BCD4",
}
GROUPS = list(GROUP_COLORS)                       # Healthy first, then the diseases
DISEASES = [g for g in GROUPS if g != "Healthy"]

OUT = Path("results_GSE32018")                    # where tables and figures are saved
FIGDIR = OUT / "figures"
FIGDIR.mkdir(parents=True, exist_ok=True)

print("pandas", pd.__version__, "| numpy", np.__version__, "| GEOparse", GEOparse.__version__)
pandas 3.1.1 | numpy 2.5.5 | GEOparse 2.0.4

✅ Checkpoint: You see version numbers and no errors. A ModuleNotFoundError means a package is missing from the Python interpreter RStudio is using. See the setup note above.

1.1 Load the GEO series

GEO packages a whole study as a family SOFT file: every sample’s values, the sample descriptions, and the platform’s probe annotation. Point SOFT_PATH at the copy you downloaded.

SOFT_PATH = Path.home() / "Downloads" / "GSE32018_family.soft"

if SOFT_PATH.exists():
    print("Loading saved copy:", SOFT_PATH)
    gse = GEOparse.get_GEO(filepath=str(SOFT_PATH), silent=True)
else:
    raise FileNotFoundError(f"Not found: {SOFT_PATH}")

print(gse.name, "|", len(gse.gsms), "samples |", len(gse.gpls), "platform(s)")
Loading saved copy: /Users/tinacole/Downloads/GSE32018_family.soft
/Users/tinacole/.virtualenvs/r-reticulate/lib/python3.12/site-packages/GEOparse/GEOparse.py:401: DtypeWarning:

Columns (2: CONTROL_TYPE) have mixed types. Specify dtype option on import or set low_memory=False.
GSE32018 | 127 samples | 1 platform(s)

✅ Checkpoint: GSE32018, the number of samples, and 1 platform(s).

WarningCommon error

FileNotFoundError: the path is wrong. Check whether your file ends in .soft or .soft.gz and edit SOFT_PATH to match.

1.2 Build the expression matrix

Each sample (GSM) carries a VALUE column. pivot_samples lines them up side by side: rows are probes, columns are samples. This is the same layout as exprs(eset) in R.

expr = gse.pivot_samples("VALUE")

print("Shape (probes x samples):", expr.shape)
expr.iloc[:5, :4]
Shape (probes x samples): (40999, 127)
name GSM793379 GSM793380 GSM793381 GSM793382
ID_REF
A_23_P100001 -1.516611 -0.992768 -0.747590 0.075629
A_23_P100011 0.043817 -0.144624 -0.450573 0.164694
A_23_P100022 2.833167 1.505817 2.800788 1.026755
A_23_P100056 -1.972608 -1.995727 -1.949528 -1.801383
A_23_P100074 0.505328 -0.086854 -0.377399 -0.205484

✅ Checkpoint: Tens of thousands of rows (probes), one column per sample, and values that are small numbers centred around 0, some negative.

Why negative? GSE32018 is an Agilent two-colour array (GPL6480). Each sample (Cy5) was hybridised against the same Universal Human Reference RNA (Cy3), so each value is a log-ratio versus that reference, not an intensity. Because every array shares the same reference, comparing log-ratios between groups is valid. It also means we do not log-transform again. These values are already on the log scale.

1.3 Probe annotation (feature data)

The platform table maps each Agilent probe ID (A_23_P...) to a gene and tells us which spots are controls. It is the Python equivalent of fData(eset).

gpl = list(gse.gpls.values())[0]
fdata = gpl.table.set_index("ID")

print("Platform:", gpl.name)
print("Columns:", list(fdata.columns))
fdata.head()
Platform: GPL6480
Columns: ['SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']
SPOT_ID CONTROL_TYPE REFSEQ GB_ACC GENE GENE_SYMBOL GENE_NAME UNIGENE_ID ENSEMBL_ID TIGR_ID ACCESSION_STRING CHROMOSOMAL_LOCATION CYTOBAND DESCRIPTION GO_ID SEQUENCE
ID
A_23_P100001 A_23_P100001 False NM_207446 NM_207446 400451.0 FAM174B family with sequence similarity 174, member B Hs.27373 ENST00000557398 NaN ref|NM_207446|ens|ENST00000557398|ens|ENST0000... chr15:93160848-93160789 hs|15q26.1 Homo sapiens family with sequence similarity 1... GO:0016020(membrane)|GO:0016021(integral to me... ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCG...
A_23_P100011 A_23_P100011 False NM_005829 NM_005829 10239.0 AP3S2 adaptor-related protein complex 3, sigma 2 sub... Hs.632161 NaN NaN ref|NM_005829|ref|NM_001199058|ref|NR_023361|r... chr15:90378743-90378684 hs|15q26.1 Homo sapiens adaptor-related protein complex 3... GO:0005794(Golgi apparatus)|GO:0006886(intrace... TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAG...
A_23_P100022 A_23_P100022 False NM_014848 NM_014848 9899.0 SV2B synaptic vesicle glycoprotein 2B Hs.21754 ENST00000557410 NaN ref|NM_014848|ref|NM_001167580|ens|ENST0000055... chr15:91838329-91838388 hs|15q26.1 Homo sapiens synaptic vesicle glycoprotein 2B ... GO:0001669(acrosomal vesicle)|GO:0006836(neuro... ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAG...
A_23_P100056 A_23_P100056 False NM_194272 NM_194272 348093.0 RBPMS2 RNA binding protein with multiple splicing 2 Hs.436518 ENST00000300069 NaN ref|NM_194272|ens|ENST00000300069|gb|AK127873|... chr15:65032375-65032316 hs|15q22.31 Homo sapiens RNA binding protein with multiple... GO:0000166(nucleotide binding)|GO:0003676(nucl... CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAA...
A_23_P100074 A_23_P100074 False NM_020371 NM_020371 57099.0 AVEN apoptosis, caspase activation inhibitor Hs.555966 ENST00000306730 NaN ref|NM_020371|ens|ENST00000306730|gb|AF283508|... chr15:34158739-34158680 hs|15q14 Homo sapiens apoptosis, caspase activation inh... GO:0005515(protein binding)|GO:0005622(intrace... GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTAT...

✅ Checkpoint: The platform is GPL6480, and you can see a CONTROL_TYPE column and a gene-symbol column. We use both below.

1.4 Look at the sample descriptions before labelling them

Don’t hard-code group labels from memory. First, look at what GEO actually calls each sample.

sources = pd.Series(
    {gsm_id: gsm.metadata.get("source_name_ch1", [""])[0] for gsm_id, gsm in gse.gsms.items()}
)
sources.value_counts()
Mantle Cell Lymphoma patient                24
Follicular Lymphoma patient                 23
Diffuse Large B cell Lymphoma patient       22
Chronic Lymphocytic Leukemia patient        17
marginal zone lymphoma-MALT type patient    15
Nodal Marginal Zone Lymphoma patient        13
Lymph-node                                   7
Reactive Tonsils                             6
Name: count, dtype: int64

✅ Checkpoint: Eight distinct source names: six lymphoma types, Lymph-node (7) and Reactive Tonsils (6).

1.5 Map source names to short group labels

Now that we’ve seen the exact spelling, we can write the mapping. Lymph nodes and tonsils are both normal tissue, so both become Healthy.

SOURCE_TO_GROUP = {
    "Diffuse Large B cell Lymphoma patient":    "DLBCL",
    "Chronic Lymphocytic Leukemia patient":     "CLL",
    "Follicular Lymphoma patient":              "FL",
    "marginal zone lymphoma-MALT type patient": "MALT",
    "Mantle Cell Lymphoma patient":             "MCL",
    "Nodal Marginal Zone Lymphoma patient":     "NMZL",
    "Lymph-node":                               "Healthy",   # 7 normal lymph nodes
    "Reactive Tonsils":                         "Healthy",   # 6 reactive tonsils
}

meta = pd.DataFrame({
    "title":  {g: s.metadata.get("title", [""])[0] for g, s in gse.gsms.items()},
    "source": sources,
})
meta["disease_type"] = meta["source"].map(SOURCE_TO_GROUP)
meta = meta.loc[expr.columns]          # same sample order as the expression matrix

print("Unlabelled samples:", meta["disease_type"].isna().sum())
meta.head()
Unlabelled samples: 0
title source disease_type
GSM793379 Diffuse Large B cell Lymphoma (DLBCL_60528) Diffuse Large B cell Lymphoma patient DLBCL
GSM793380 Follicular Lymphoma (FL_31266) Follicular Lymphoma patient FL
GSM793381 Follicular Lymphoma (FL_11094) Follicular Lymphoma patient FL
GSM793382 Follicular Lymphoma (FL_1013) Follicular Lymphoma patient FL
GSM793383 Follicular Lymphoma (FL_10064) Follicular Lymphoma patient FL

✅ Checkpoint: Unlabelled samples: 0. If it’s not 0, a source name in the dictionary doesn’t exactly match GEO’s spelling. Compare it with the output of 1.4. Capital letters and hyphens count.

ImportantWhy .loc[expr.columns] matters

The metadata rows must be in the same order as the expression columns. If they’re out of order, every sample gets the wrong label, and nothing errors. The results are just wrong. Check it:

assert list(meta.index) == list(expr.columns), "metadata and expression are out of order!"
print("Sample order matches.")
Sample order matches.

1.6 Choose your healthy controls

Reactive tonsils contain squamous epithelium (SPRR3, SPINK5, KRT13…), which lymph nodes don’t. With tonsils in the control group, those genes appear “down in every lymphoma”, but that difference comes from the tissue type, not the disease. The R lesson keeps all 13 controls. Switch to "lymph-node" to see how the results change.

CONTROLS = "all"            # or "lymph-node"

if CONTROLS == "lymph-node":
    meta = meta[meta["source"] != "Reactive Tonsils"]
    expr = expr[meta.index]

print("Samples kept:", expr.shape[1])
Samples kept: 127

1.7 Remove control probes and missing values

Agilent arrays include positive and negative control spots that don’t measure genes. First look at what CONTROL_TYPE contains, then keep only the real probes.

fdata["CONTROL_TYPE"].astype(str).value_counts()
CONTROL_TYPE
False     32768
FALSE      8232
pos          92
ignore        1
neg           1
Name: count, dtype: int64
is_gene_probe = fdata["CONTROL_TYPE"].astype(str).str.lower() == "false"
keep_ids = fdata.index[is_gene_probe].intersection(expr.index)

n_before = len(expr)
expr = expr.loc[keep_ids].dropna()
print(f"Probes: {n_before:,} -> {len(expr):,} after removing control spots and missing values")
Probes: 40,999 -> 40,999 after removing control spots and missing values

✅ Checkpoint: The probe count can drop here but remains constant at 40,999 >> 40,999. In other cases if it drops to 0, the CONTROL_TYPE values are spelled differently than "false". Check the output of the chunk above.

1.8 Sanity-check the normalisation

The submitters applied LOWESS normalisation, so every array should be centred near 0. Check this. Don’t re-normalise.

print(f"Median log-ratio across arrays: {expr.median().median():.3f}  (should be close to 0)")

fig, ax = plt.subplots(figsize=(12, 4))
ax.boxplot(expr.values, showfliers=False, widths=0.6)
ax.axhline(0, color="red", lw=0.8)
ax.set_xticks([])
ax.set_xlabel("Arrays")
ax.set_ylabel("log2 ratio vs reference")
ax.set_title("Per-array distributions after cleaning", fontweight="bold")
plt.show()
Median log-ratio across arrays: 0.005  (should be close to 0)

✅ Checkpoint: The boxes sit at roughly the same height around the red line. An array whose box is far off from the others is worth a closer look before modelling.

1.9 Final group counts

meta["disease_type"] = pd.Categorical(meta["disease_type"], categories=GROUPS)
meta["disease_type"].value_counts().reindex(GROUPS)
disease_type
Healthy    13
DLBCL      22
CLL        17
FL         23
MALT       15
MCL        24
NMZL       13
Name: count, dtype: int64

✅ Checkpoint: All seven groups are listed, and Healthy is 13 (or 7 if you chose "lymph-node"). These group sizes matter in Part 2. Small groups are why we use limma.

Part 2: limma, one model with six contrasts

In R this step is four function calls: lmFit → contrasts.fit → eBayes → topTable. Here we write out what each of them does in numpy, one chunk per function, so you can see what’s going on at each step.

2.1 The design matrix (model.matrix(~ 0 + group))

One column per group, one row per sample. A 1 marks which group the sample belongs to. With ~ 0 + group (no intercept), each coefficient is simply that group’s mean.

design = pd.get_dummies(meta["disease_type"]).astype(float)[GROUPS]
design.index = expr.columns

print("Design shape (samples x groups):", design.shape)
print("\nSamples per column:")
print(design.sum().astype(int).to_string())
design.head()
Design shape (samples x groups): (127, 7)

Samples per column:
Healthy    13
DLBCL      22
CLL        17
FL         23
MALT       15
MCL        24
NMZL       13
Healthy DLBCL CLL FL MALT MCL NMZL
name
GSM793379 0.0 1.0 0.0 0.0 0.0 0.0 0.0
GSM793380 0.0 0.0 0.0 1.0 0.0 0.0 0.0
GSM793381 0.0 0.0 0.0 1.0 0.0 0.0 0.0
GSM793382 0.0 0.0 0.0 1.0 0.0 0.0 0.0
GSM793383 0.0 0.0 0.0 1.0 0.0 0.0 0.0

✅ Checkpoint: Each row has exactly one 1, and the column sums match the group counts from 1.9.

2.2 The contrast matrix (makeContrasts)

We want each disease minus Healthy. Each column is one comparison: +1 for the disease and -1 for Healthy.

C = pd.DataFrame(0.0, index=GROUPS, columns=[f"{d}_vs_Healthy" for d in DISEASES])
for d in DISEASES:
    C.loc[d, f"{d}_vs_Healthy"] = 1
    C.loc["Healthy", f"{d}_vs_Healthy"] = -1
C
DLBCL_vs_Healthy CLL_vs_Healthy FL_vs_Healthy MALT_vs_Healthy MCL_vs_Healthy NMZL_vs_Healthy
Healthy -1.0 -1.0 -1.0 -1.0 -1.0 -1.0
DLBCL 1.0 0.0 0.0 0.0 0.0 0.0
CLL 0.0 1.0 0.0 0.0 0.0 0.0
FL 0.0 0.0 1.0 0.0 0.0 0.0
MALT 0.0 0.0 0.0 1.0 0.0 0.0
MCL 0.0 0.0 0.0 0.0 1.0 0.0
NMZL 0.0 0.0 0.0 0.0 0.0 1.0

2.3 Fit a linear model to every probe at once (lmFit)

Ordinary least squares, solved for all probes in one matrix operation:

\[\hat\beta = (X^\top X)^{-1} X^\top y\]

X = design.values                     # samples x groups
Y = expr.values                       # probes  x samples

XtX_inv = np.linalg.inv(X.T @ X)
B = Y @ X @ XtX_inv                   # coefficients: probes x groups (= group means)
resid = Y - B @ X.T

df_residual = X.shape[0] - X.shape[1]                 # n samples - n groups
sigma2 = (resid ** 2).sum(axis=1) / df_residual       # each probe's own variance

coef = pd.DataFrame(B, index=expr.index, columns=GROUPS)
print("Residual degrees of freedom:", df_residual)
coef.head()
Residual degrees of freedom: 120
Healthy DLBCL CLL FL MALT MCL NMZL
ID_REF
A_23_P100001 -0.769252 -1.254745 0.623819 -0.270020 -0.313251 -0.795264 -0.559885
A_23_P100011 -0.600602 0.023361 -0.235572 -0.307086 -0.166192 -0.413766 0.055312
A_23_P100022 2.489104 1.276544 1.372260 2.451444 1.453901 1.778245 2.322801
A_23_P100056 -2.349639 -1.681118 -1.965759 -2.190601 -1.828489 -2.585496 -2.190866
A_23_P100074 -0.403669 0.213380 0.162533 -0.305678 0.037963 -0.641031 -0.174375

✅ Checkpoint: prove the coefficients are group means. Pick any probe and compute its Healthy mean by hand:

probe = expr.index[0]
by_hand = expr.loc[probe, meta["disease_type"] == "Healthy"].mean()
print(f"By hand: {by_hand:.6f}   From the model: {coef.loc[probe, 'Healthy']:.6f}")
By hand: -0.769252   From the model: -0.769252

2.4 Turn group means into comparisons (contrasts.fit)

Multiplying by the contrast matrix turns 7 group means into 6 differences (disease − Healthy). These differences are the log fold changes. We transform the coefficient covariance the same way, so we can compute standard errors next.

coef_c = coef @ C
cov_c = C.T @ pd.DataFrame(XtX_inv, index=GROUPS, columns=GROUPS) @ C

coef_c.head()
DLBCL_vs_Healthy CLL_vs_Healthy FL_vs_Healthy MALT_vs_Healthy MCL_vs_Healthy NMZL_vs_Healthy
ID_REF
A_23_P100001 -0.485492 1.393072 0.499232 0.456001 -0.026012 0.209367
A_23_P100011 0.623963 0.365030 0.293516 0.434410 0.186836 0.655914
A_23_P100022 -1.212560 -1.116844 -0.037659 -1.035203 -0.710859 -0.166302
A_23_P100056 0.668521 0.383880 0.159038 0.521150 -0.235857 0.158773
A_23_P100074 0.617049 0.566202 0.097991 0.441632 -0.237362 0.229293

✅ Checkpoint: 6 columns, one per disease. Check one value by hand: coef.loc[probe, "DLBCL"] - coef.loc[probe, "Healthy"] should equal coef_c.loc[probe, "DLBCL_vs_Healthy"].

2.5 Borrow strength across probes (eBayes)

This step is what makes limma work with small groups. Some probes have very small variances just by chance, which would give them huge t-statistics. eBayes shrinks each probe’s variance toward a typical value shared by all probes:

\[s^2_{\text{post}} = \frac{d_0 s_0^2 + d\, s^2}{d_0 + d}\]

First we estimate the prior (\(d_0\), \(s_0^2\)) from the distribution of all the probe variances. These two helpers are direct translations of limma’s fitFDist:

def trigamma_inverse(x):
    """Solve trigamma(y) = x for y (Newton's method, as in limma)."""
    y = 0.5 + 1.0 / x
    for _ in range(50):
        tri = special.polygamma(1, y)
        dif = tri * (1 - tri / x) / special.polygamma(2, y)
        y = y + dif
        if -dif / y < 1e-8:
            break
    return y


def fit_f_dist(s2, df):
    """limma::fitFDist: estimate prior df (d0) and prior variance (s0^2)."""
    z = np.log(s2)
    e = z - special.digamma(df / 2) + np.log(df / 2)
    emean = e.mean()
    evar = ((e - emean) ** 2).sum() / (len(e) - 1) - special.polygamma(1, df / 2)
    if evar > 0:
        d0 = 2 * trigamma_inverse(evar)
        s02 = np.exp(emean + special.digamma(d0 / 2) - np.log(d0 / 2))
    else:
        d0, s02 = np.inf, np.exp(emean)
    return float(d0), float(s02)


d0, s02 = fit_f_dist(sigma2, df_residual)
print(f"Prior df d0 = {d0:.2f}   Prior variance s0^2 = {s02:.4f}   Residual df = {df_residual}")
Prior df d0 = 2.66   Prior variance s0^2 = 0.1105   Residual df = 120

Now shrink the variances and see what that does:

if np.isinf(d0):                     # all probes look alike: every variance becomes s0^2
    s2_post = np.full_like(sigma2, s02)
else:
    s2_post = (d0 * s02 + df_residual * sigma2) / (d0 + df_residual)

fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(sigma2, s2_post, s=2, alpha=0.3)
lim = [sigma2.min(), sigma2.max()]
ax.plot(lim, lim, color="grey", ls="--", lw=0.8, label="no shrinkage")
ax.axhline(s02, color="red", lw=0.8, label="prior s0²")
ax.set_xscale("log"); ax.set_yscale("log")
ax.set_xlabel("Raw probe variance"); ax.set_ylabel("Moderated variance")
ax.set_title("eBayes pulls variances toward the prior", fontweight="bold")
ax.legend(frameon=False)
plt.show()

✅ Checkpoint: The points are pulled off the diagonal toward the red line. The smallest variances get pulled up the most, which is exactly the protection against false positives described above.

Now compute the moderated t-statistics and p-values, plus a moderated F, which asks whether a probe differs in any disease:

df_total = min(df_residual + d0, df_residual * len(expr))
se_unscaled = np.sqrt(np.diag(cov_c.values))                    # one per contrast

t_mod = coef_c / (se_unscaled * np.sqrt(s2_post)[:, None])
p_mod = pd.DataFrame(2 * stats.t.sf(np.abs(t_mod), df_total),
                     index=expr.index, columns=coef_c.columns)

R = cov_c.values / np.outer(se_unscaled, se_unscaled)
T = t_mod.values
q = T.shape[1]
F_mod = np.einsum("ij,jk,ik->i", T, np.linalg.inv(R), T) / q
F_p = stats.f.sf(F_mod, q, df_total)

ave_expr = expr.mean(axis=1)
print("Moderated t computed for", t_mod.shape[0], "probes x", t_mod.shape[1], "contrasts")
Moderated t computed for 40999 probes x 6 contrasts

2.6 Rank and adjust (topTable)

We test tens of thousands of probes, so raw p-values will produce many false positives. Benjamini–Hochberg adjusts them to control the false discovery rate.

def bh(p):
    """Benjamini-Hochberg adjusted p-values."""
    p = np.asarray(p)
    n = len(p)
    order = np.argsort(p)
    adj = np.empty(n)
    adj[order] = np.minimum.accumulate((p[order] * n / np.arange(1, n + 1))[::-1])[::-1]
    return np.minimum(adj, 1)


def top_table(coef=None, number=None):
    """limma::topTable. coef=None ranks by the moderated F across all contrasts."""
    if coef is None:
        res = pd.concat([coef_c, pd.DataFrame({"F": F_mod, "P_Value": F_p}, index=expr.index)], axis=1)
    else:
        res = pd.DataFrame({"logFC": coef_c[coef], "AveExpr": ave_expr,
                            "t": t_mod[coef], "P_Value": p_mod[coef]}, index=expr.index)
    res["adj_P_Val"] = bh(res["P_Value"])
    res = res.sort_values("P_Value")
    return res if number is None else res.head(number)


top_table("DLBCL_vs_Healthy", number=10)
logFC AveExpr t P_Value adj_P_Val
ID_REF
A_23_P24997 1.376142 -1.005893 11.827793 5.244438e-22 2.150167e-17
A_24_P304449 1.235467 -0.935312 9.949189 1.855134e-17 3.802931e-13
A_23_P206830 1.003601 -0.651256 9.800212 4.244541e-17 4.426373e-13
A_23_P254288 1.105445 -1.212727 9.797100 4.318518e-17 4.426373e-13
A_23_P45396 0.959611 -0.435294 9.317917 6.126888e-16 5.023925e-12
A_23_P55149 1.356707 -0.707796 9.198548 1.182874e-15 7.445265e-12
A_24_P292831 0.818736 -0.568442 9.185470 1.271174e-15 7.445265e-12
A_23_P28538 1.062691 -0.615204 9.084317 2.217081e-15 1.136227e-11
A_32_P210252 -1.441782 0.429173 -8.926272 5.275749e-15 2.403338e-11
A_23_P324490 -1.160616 0.443502 -8.810060 9.961767e-15 3.552833e-11

✅ Checkpoint: our BH matches scipy’s.

check = top_table("DLBCL_vs_Healthy")
print("Matches scipy:", np.allclose(check["adj_P_Val"],
                                    stats.false_discovery_control(check["P_Value"])))
Matches scipy: True

How many probes pass FDR < 0.05 and at least a 2-fold change (|logFC| > 1) in each disease?

for d in DISEASES:
    res = top_table(f"{d}_vs_Healthy")
    n = int(((res["adj_P_Val"] < 0.05) & (res["logFC"].abs() > 1)).sum())
    print(f"  {d:6s} vs Healthy: {n:5,d} probes")
  DLBCL  vs Healthy: 1,595 probes
  CLL    vs Healthy: 3,125 probes
  FL     vs Healthy:   546 probes
  MALT   vs Healthy: 1,027 probes
  MCL    vs Healthy: 1,496 probes
  NMZL   vs Healthy:   628 probes
TipThink about it

Which disease differs most from Healthy? Re-run Part 1 with CONTROLS = "lymph-node". Which counts change, and why?

2.7 Probe IDs → gene symbols

Probe IDs aren’t readable in a figure. Map them to gene symbols, and fall back to the probe ID when a probe has no symbol.

sym_col = next(c for c in fdata.columns if c.lower().replace("_", " ") in ("gene symbol", "symbol"))
p2s = fdata.reindex(expr.index)[sym_col].fillna("").astype(str)
p2s = p2s.str.replace(r"\s*///.*", "", regex=True)       # keep the first symbol only
missing = p2s.isin(["", "nan", "None"])
p2s[missing] = p2s.index[missing]

print("Symbol column:", sym_col, "| probes without a symbol:", int(missing.sum()))
p2s.head()
Symbol column: GENE_SYMBOL | probes without a symbol: 10064
ID_REF
A_23_P100001    FAM174B
A_23_P100011      AP3S2
A_23_P100022       SV2B
A_23_P100056     RBPMS2
A_23_P100074       AVEN
Name: GENE_SYMBOL, dtype: str

Label probes that have no gene symbol

About 1 in 4 probes on this array has no GENE_SYMBOL. Rather than show a bare probe ID, we label them by chromosome band, and use a real gene name only where the platform’s DESCRIPTION confirms it. The probe ID stays in brackets so every label can be traced back.

band = (fdata.reindex(expr.index)["CYTOBAND"].fillna("")
          .str.replace("hs|", "", regex=False))
p2s = p2s.where(~missing, band.where(band != "", "unannotated") + " (" + p2s.index + ")")

MANUAL_LABELS = {                       # confirmed from DESCRIPTION
    "A_24_P519504": "IGLV3-1",          # immunoglobulin lambda variable 3-1
    "A_24_P109921": "IGHE",             # immunoglobulin heavy constant epsilon
    "A_32_P85593":  "TMSB15",           # thymosin beta 15
}
p2s.update({p: f"{n} ({p})" for p, n in MANUAL_LABELS.items() if p in p2s.index})
p2s[list(MANUAL_LABELS)]
ID_REF
A_24_P519504    IGLV3-1 (A_24_P519504)
A_24_P109921       IGHE (A_24_P109921)
A_32_P85593       TMSB15 (A_32_P85593)
Name: GENE_SYMBOL, dtype: str

✅ Checkpoint: three labels such as IGLV3-1 (A_24_P519504).

Part 3: Visualization and downstream analysis

3.1 Top 5 up and down genes per disease

frames = []
for d in DISEASES:
    res = top_table(f"{d}_vs_Healthy")
    sig = res[res["adj_P_Val"] < 0.05]
    if sig.empty:
        print(f"  ! No FDR < 0.05 genes for {d}; using top 10 by |logFC|.")
        sig = res.reindex(res["logFC"].abs().sort_values(ascending=False).index).head(10)
    up = sig[sig["logFC"] > 0].nlargest(5, "logFC").assign(direction="Up")
    down = sig[sig["logFC"] < 0].nsmallest(5, "logFC").assign(direction="Down")
    frames += [up.assign(disease=d), down.assign(disease=d)]

top = pd.concat(frames).rename_axis("probe").reset_index()
top["gene"] = p2s.reindex(top["probe"]).values

top[["disease", "direction", "gene", "probe", "logFC", "adj_P_Val"]] \
    .rename(columns={"adj_P_Val": "adj.P.Val"}) \
    .to_csv(OUT / "top5_genes_per_disease.csv", index=False)

top[["disease", "direction", "gene", "logFC", "adj_P_Val"]].round({"logFC": 2})
disease direction gene logFC adj_P_Val
0 DLBCL Up MAGEA9 2.21 1.194547e-03
1 DLBCL Up POSTN 2.07 3.767961e-05
2 DLBCL Up CTAG1A 2.02 2.222405e-03
3 DLBCL Up CD70 1.89 1.223356e-04
4 DLBCL Up KLHL23 1.86 5.636080e-10
5 DLBCL Down SPINK5 -3.44 4.395369e-05
6 DLBCL Down PLAC8 -3.37 4.992309e-08
7 DLBCL Down SPRR3 -3.34 2.307474e-06
8 DLBCL Down PLAC8 -3.31 3.731199e-07
9 DLBCL Down unannotated (A_23_P435390) -3.27 6.858506e-05
10 CLL Up 1q32.1 (A_32_P234405) 4.45 7.866527e-14
11 CLL Up PIGR 3.58 8.246488e-08
12 CLL Up 10p12.33 (A_23_P35546) 3.53 1.286011e-10
13 CLL Up PCDH9 3.35 8.117969e-06
14 CLL Up MGC16075 3.35 1.853259e-06
15 CLL Down CSTA -4.39 7.960047e-14
16 CLL Down IGJ -3.78 1.514112e-06
17 CLL Down RGS13 -3.73 2.067123e-06
18 CLL Down HOPX -3.70 2.398646e-09
19 CLL Down SPRR3 -3.39 1.845448e-06
20 FL Up IGHE (A_24_P109921) 2.78 5.576050e-05
21 FL Up TMEM155 2.04 2.402958e-04
22 FL Up LOC100652917 2.03 1.209132e-03
23 FL Up SLC30A4 1.89 7.172633e-06
24 FL Up C3 1.87 2.957453e-05
25 FL Down IGLV3-1 (A_24_P519504) -4.10 3.992118e-07
26 FL Down SPINK5 -3.44 9.358885e-05
27 FL Down SPRR3 -2.90 7.357052e-05
28 FL Down SPRR1A -2.82 7.645563e-04
29 FL Down PLAC8 -2.78 3.088952e-05
30 MALT Up HTRA3 2.60 1.185072e-05
31 MALT Up FBLN1 2.58 5.184673e-05
32 MALT Up FAM101A 2.42 1.041991e-04
33 MALT Up POSTN 2.35 3.328825e-05
34 MALT Up VCAN 2.28 7.622630e-08
35 MALT Down SPRR3 -3.51 9.084346e-06
36 MALT Down SPRR1A -3.02 7.685425e-04
37 MALT Down PLAC8 -2.86 6.871893e-05
38 MALT Down PLAC8 -2.83 2.923124e-05
39 MALT Down HIST1H4L -2.79 1.848926e-10
40 MCL Up SOX11 5.37 2.389333e-25
41 MCL Up 2p25.2 (A_32_P113784) 5.02 2.354265e-20
42 MCL Up PPP1R17 4.35 4.646989e-16
43 MCL Up CCND1 4.20 4.813572e-32
44 MCL Up WNT3 4.19 7.138598e-11
45 MCL Down IGJ -3.77 1.223821e-06
46 MCL Down AICDA -3.55 3.027878e-06
47 MCL Down RGS13 -3.48 7.274272e-06
48 MCL Down SPINK5 -3.44 4.263455e-05
49 MCL Down KIAA0125 -3.34 1.510474e-07
50 NMZL Up CD70 1.92 1.218722e-03
51 NMZL Up SNX17 1.67 5.474766e-06
52 NMZL Up OSBPL10 1.66 1.321376e-03
53 NMZL Up FCRLA 1.65 3.111885e-02
54 NMZL Up TMEM155 1.63 1.300106e-02
55 NMZL Down SPRR3 -3.11 1.897620e-04
56 NMZL Down SPINK5 -3.03 2.946242e-03
57 NMZL Down SPRR1A -2.89 2.834177e-03
58 NMZL Down S100A2 -2.59 4.966668e-03
59 NMZL Down SERPINB2 -2.48 1.249009e-04

✅ Checkpoint: Up to 10 rows per disease, and top5_genes_per_disease.csv appears in your results folder. Do any genes appear as “Down” in every disease? If so, look back at 1.6 for one likely reason.

3.2 Heatmap of top DE genes (z-scored)

We combine the top 50 probes by moderated F with the top-5 genes above. Each row is z-scored (mean 0, SD 1), so the colours show where a gene is high or low relative to its own average.

f_top = top_table(None, number=50)
probes = [p for p in dict.fromkeys(list(f_top.index) + list(top["probe"])) if p in expr.index]

order = meta.sort_values("disease_type").index               # group the columns by disease
mat = expr.loc[probes, order]
z = mat.sub(mat.mean(axis=1), axis=0).div(mat.std(axis=1, ddof=1), axis=0)
z.index = p2s.reindex(z.index).values

col_colors = meta.loc[order, "disease_type"].map(GROUP_COLORS).rename("Disease")
g = sns.clustermap(z, row_cluster=True, col_cluster=False, cmap="RdBu_r",
                   center=0, vmin=-3, vmax=3, col_colors=col_colors,
                   xticklabels=False, yticklabels=True,
                   figsize=(12, max(12, 0.2 * len(probes))),   # taller when there are more rows
                   dendrogram_ratio=(0.10, 0.06),
                   cbar_pos=(0.02, 0.90, 0.02, 0.06))
g.ax_heatmap.tick_params(axis="y", labelsize=7)
g.ax_heatmap.set_xlabel(""); g.ax_heatmap.set_ylabel("")
g.ax_col_colors.set_yticks([])                                  # drop the overlapping "Disease" label
g.figure.suptitle("Top DE Genes: Disease vs Healthy (z-scored)", y=1.0, fontweight="bold")

# legend in the empty strip above the heatmap (no column dendrogram is drawn there)
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in GROUP_COLORS.values()]
g.ax_col_dendrogram.legend(handles, GROUP_COLORS.keys(), ncol=len(GROUP_COLORS),
                           loc="center", frameon=False, fontsize=9)

g.savefig(OUT / "heatmap_disease_vs_healthy.pdf", bbox_inches="tight")
g.savefig(FIGDIR / "heatmap_disease_vs_healthy.png", dpi=200, bbox_inches="tight", facecolor="white")
plt.show()
print(f"{len(probes)} probes plotted")
/Users/tinacole/.virtualenvs/r-reticulate/lib/python3.12/site-packages/seaborn/matrix.py:560: UserWarning:

Clustering large matrix with scipy. Installing `fastcluster` may give better performance.

89 probes plotted

✅ Checkpoint: Look for blocks of colour that line up with a disease’s colour bar. That’s a gene set that tells that lymphoma apart from the others.

3.3 PCA: do the samples separate by disease?

PCA uses all probes, not just the DE ones. It’s an unsupervised check: if disease type drives expression, samples from the same disease should cluster together. We scale each probe first, the same as prcomp(scale. = TRUE) in R.

Xs = StandardScaler().fit_transform(expr.T.values)
pca = PCA(n_components=10).fit(Xs)
pcs = pca.transform(Xs)
var = pca.explained_variance_ratio_ * 100

pc_df = pd.DataFrame(pcs[:, :3], columns=["PC1", "PC2", "PC3"], index=expr.columns)
pc_df["Disease"] = meta["disease_type"].values
print("Variance explained, PC1-PC3:", ", ".join(f"{v:.1f}%" for v in var[:3]))
Variance explained, PC1-PC3: 13.5%, 9.3%, 7.6%

Plotting helpers (75% normal-theory ellipses, like stat_ellipse() in ggplot2):

def confidence_ellipse(ax, x, y, color, level=0.75):
    if len(x) < 3:
        return
    vals, vecs = np.linalg.eigh(np.cov(x, y))
    order = vals.argsort()[::-1]
    vals, vecs = vals[order], vecs[:, order]
    angle = np.degrees(np.arctan2(*vecs[:, 0][::-1]))
    w, h = 2 * np.sqrt(vals * stats.chi2.ppf(level, 2))
    ax.add_patch(Ellipse((np.mean(x), np.mean(y)), w, h, angle=angle,
                         fill=False, ls="--", lw=0.8, color=color))


def pca_panel(ax, a, b, title, legend=False):
    for grp, color in GROUP_COLORS.items():
        sub = pc_df[pc_df["Disease"] == grp]
        ax.scatter(sub[a], sub[b], s=32, alpha=0.85, color=color, label=grp, edgecolor="none")
        confidence_ellipse(ax, sub[a].values, sub[b].values, color)
    ax.set_xlabel(f"{a} ({var[int(a[2]) - 1]:.1f}% variance)")
    ax.set_ylabel(f"{b} ({var[int(b[2]) - 1]:.1f}% variance)")
    ax.set_title(title, fontweight="bold")
    ax.grid(alpha=0.3)
    if legend:
        ax.legend(title="Disease Type", fontsize=8, frameon=False)


def scree_panel(ax):
    ax.bar(range(1, 11), var, color="#2196F3", alpha=0.75)
    ax.plot(range(1, 11), var, color="black", lw=0.8, marker="o", ms=4)
    ax.set_xticks(range(1, 11))
    ax.set_xlabel("Principal Component"); ax.set_ylabel("% Variance Explained")
    ax.set_title("Scree Plot", fontweight="bold")
    ax.grid(alpha=0.3)
fig, axs = plt.subplots(2, 2, figsize=(14, 10))
pca_panel(axs[0, 0], "PC1", "PC2", "PCA: Gene Expression by Disease Type", legend=True)
pca_panel(axs[0, 1], "PC2", "PC3", "PCA: PC2 vs PC3")
scree_panel(axs[1, 0])
axs[1, 1].axis("off")
fig.tight_layout()
fig.savefig(OUT / "pca_disease_types.pdf")
fig.savefig(FIGDIR / "pca_disease_types.png", dpi=200, bbox_inches="tight", facecolor="white")
plt.show()

✅ Checkpoint: Which diseases separate cleanly and which overlap? Compare the scree plot: if PC1 explains only a modest share of the variance, no single axis captures “disease”, and that’s normal for tumour data.

3.4 Violin plots of the strongest genes

For each disease and direction, take the gene with the largest |logFC| and plot its expression in every group. This checks the statistics against the raw data: does the group difference look real?

rep = (top.assign(absFC=top["logFC"].abs())
          .sort_values("absFC", ascending=False)
          .groupby(["disease", "direction"], sort=False).head(1))
vprobes = list(dict.fromkeys(rep["probe"]))
long = (expr.loc[vprobes].T
           .rename(columns=dict(zip(vprobes, p2s.reindex(vprobes).values)))
           .assign(Disease=meta["disease_type"].values)
           .melt(id_vars="Disease", var_name="Gene", value_name="Expression"))
genes = list(dict.fromkeys(long["Gene"]))

ncol = 3
nrow = int(np.ceil(len(genes) / ncol))
fig, axs = plt.subplots(nrow, ncol, figsize=(13, 3.0 * nrow), squeeze=False)
pos = np.arange(len(GROUPS))
for ax, gene in zip(axs.flat, genes):
    d = long[long["Gene"] == gene]
    data = [d.loc[d["Disease"] == g, "Expression"].values for g in GROUPS]
    vp = ax.violinplot(data, positions=pos, widths=0.8, showextrema=False)
    for body, g in zip(vp["bodies"], GROUPS):
        body.set_facecolor(GROUP_COLORS[g]); body.set_edgecolor("black")
        body.set_linewidth(0.3); body.set_alpha(0.7)
    ax.boxplot(data, positions=pos, widths=0.12, patch_artist=True,
               boxprops=dict(facecolor="white", linewidth=0.5),
               medianprops=dict(color="black", linewidth=0.8),
               whiskerprops=dict(linewidth=0.5), capprops=dict(linewidth=0.5),
               flierprops=dict(markersize=1.5, markeredgewidth=0.3))
    ax.set_xticks([])                                        # groups shown in the legend instead
    ax.set_title(gene.replace(" (", "\n("), fontweight="bold", fontsize=10)  # name on top, probe ID below
    ax.set_ylabel("log2 ratio vs reference", fontsize=8)
    ax.grid(axis="y", alpha=0.3)

# one legend for every panel, in the first empty slot (or above the grid if there is none)
handles = [plt.Rectangle((0, 0), 1, 1, color=GROUP_COLORS[g], alpha=0.7) for g in GROUPS]
spare = axs.flat[len(genes):]
for ax in spare:
    ax.axis("off")
if len(spare):
    spare[0].legend(handles, GROUPS, title="Disease (left to right)", loc="center",
                    frameon=False, fontsize=10, title_fontsize=10)
else:
    fig.legend(handles, GROUPS, ncol=len(GROUPS), loc="upper center",
               bbox_to_anchor=(0.5, 0.97), frameon=False, fontsize=9)

fig.suptitle("Expression of Top DE Genes by Disease Type", fontweight="bold", y=1.0)
fig.tight_layout(rect=[0, 0, 1, 0.95])                      # leave room for the main title
fig.savefig(OUT / "violin_top_de_genes.pdf")
fig.savefig(FIGDIR / "violin_top_de_genes.png", dpi=200, bbox_inches="tight", facecolor="white")
plt.show()
print(f"{len(genes)} genes plotted")

11 genes plotted

✅ Checkpoint: For each panel, the disease named in its row of the top-5 table should be clearly higher or lower than Healthy. If a “significant” gene looks driven by a few outlier samples, that’s worth noting before you trust it.

print("Outputs in", OUT.resolve())
for f in sorted(OUT.rglob("*.*")):
    print("  ", f.relative_to(OUT))
Outputs in /Users/tinacole/Downloads/results_GSE32018
   .DS_Store
   GSE32018_family.soft.gz
   figures/heatmap_disease_vs_healthy.pdf
   figures/heatmap_disease_vs_healthy.png
   figures/pca_disease_types.png
   figures/pca_pc1_vs_pc2.pdf
   figures/pca_pc1_vs_pc2.png
   figures/pca_pc2_vs_pc3.pdf
   figures/pca_pc2_vs_pc3.png
   figures/scree_plot.pdf
   figures/scree_plot.png
   figures/violin_top_de_genes.pdf
   figures/violin_top_de_genes.png
   heatmap_disease_vs_healthy.pdf
   pca_disease_types.pdf
   top5_genes_per_disease.csv
   violin_top_de_genes.pdf

What’s next: from step-by-step to one command

You just ran the whole analysis one chunk at a time. That’s how you learn it: you saw what each step does, checked every result against a checkpoint, and can now explain why limma shrinks variances or why the tonsils skew the controls.

In real work, you don’t re-run an analysis chunk by chunk. Once you trust each step, you package them into a single script that runs the whole pipeline in one command. That’s how analyses get repeated, shared and applied to new datasets.

Lesson 3.1 does exactly that with this same analysis: the companion script microarray_GSE32018.py runs everything you just did in about 20 seconds from a terminal, and produces the same tables and figures.