Cell Painting Gallery cpg0016: JUMP Cell Painting Production Dataset, 116,000 Compounds and 15,000 Genes: sample notebook

A worked notebook for Cell Painting Gallery cpg0016: JUMP Cell Painting Production Dataset, 116,000 Compounds and 15,000 Genes, with 6 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.

Provider
Chandrasekaran et al., JUMP Cell Painting Consortium
License
CC0-1.0 (source)
Format
NumPy (in sampled files)
Stored at
Amazon S3, s3://cellpainting-gallery/cpg0016-jump (us-east-1)
Access
Free and public. No account with the data provider is needed.
DOI
10.1101/2023.03.23.534023

The notebook

Start here. Click the grey cell below and press Shift+Enter. It loads the CRISPR knockout profiles from the archive and lists the knockouts whose effect on cell appearance is most like the knockout of GENE. Then change GENE (for example "KIF23", "ATP6V1A" or "POLR2A") and run it again.

import os
import duckdb
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

GENE = "PSMA1"

ROOT = os.environ.get("SCIGANTIC_MOUNT_PATH", "/mnt/archive")
WORK = f"{ROOT}/source_all/workspace"
META = f"{WORK}/publication_data/2025_Chandrasekaran/datasets/v0.13/parquet"
CRISPR = f"{WORK}/profiles_assembled/CRISPR/v1.0b/profiles_wellpos_var_mad_int_featselect_harmony_PCA_corrected.parquet"
con = duckdb.connect()

# One row per well: where it was, which gene was knocked out, and the profile (columns X_1, X_2, ...).
profiles = con.execute(f"""
    select c.Metadata_Symbol as gene, p.*
    from read_parquet('{CRISPR}') p join read_parquet('{META}/crispr.parquet') c using (Metadata_JCP2022)""").df()
features = [c for c in profiles.columns if c.startswith("X_")]

controls = ["non-targeting", "no-guide"]
consensus = profiles[~profiles.gene.isin(controls)].groupby("gene")[features].mean()   # one profile per gene
unit = consensus.to_numpy(copy=True)
unit /= np.linalg.norm(unit, axis=1, keepdims=True)

def neighbors(gene, k=10):
    """The k knockouts whose consensus profile has the highest cosine similarity to this gene's."""
    sim = pd.Series(unit @ unit[consensus.index.get_loc(gene)], index=consensus.index).drop(gene)
    return sim.sort_values(ascending=False).head(k)

print(f"{len(profiles):,} wells, {len(consensus):,} genes, {len(features)} features per profile")
print(f"knockouts most similar to {GENE}:")
print(neighbors(GENE).round(2).to_string())

JUMP Cell Painting (cpg0016)

Cell Painting is a microscopy assay: cells are stained with six dyes that mark eight parts of the cell (nucleus, nucleoli, endoplasmic reticulum, Golgi, actin, plasma membrane, mitochondria, cytoplasmic RNA), imaged in five channels, and measured by image analysis software that reports thousands of numbers per cell (sizes, shapes, intensities, textures). The numbers for a well, taken together, are its "profile". Perturbations that do similar things to the cell give similar profiles, which is how the assay is used to guess what an uncharacterized compound or gene does.

The JUMP Cell Painting Consortium (the Broad Institute with pharmaceutical company and non-profit partners) ran the assay on U2OS cells with three kinds of perturbation: compounds, gene overexpression (ORF) and CRISPR knockout. The counts of each are printed further down. This archive is the cpg0016-jump folder of the Cell Painting Gallery, which holds all of it, from raw images to finished profiles.

top = sorted(os.listdir(ROOT))
print(f"{len(top)} folders: {', '.join(top)}\n")
print("source_N is one data-generating site; source_all holds the tables assembled across sites:")
for kind in sorted(os.listdir(f"{WORK}/profiles_assembled")):
    versions = sorted(os.listdir(f"{WORK}/profiles_assembled/{kind}"))
    last = f"{WORK}/profiles_assembled/{kind}/{versions[-1]}"
    files = sorted(os.listdir(last), key=lambda f: os.path.getsize(f"{last}/{f}"))
    sizes = [os.path.getsize(f"{last}/{f}") / 1e9 for f in files]
    print(f"  {kind + '/' + versions[-1]:38} {len(files):2} files, {sizes[0]:5.2f} to {sizes[-1]:5.2f} GB")

Output:

14 folders: source_1, source_10, source_11, source_13, source_15, source_2, source_3, source_4, source_5, source_6, source_7, source_8, source_9, source_all

source_N is one data-generating site; source_all holds the tables assembled across sites:
  ALL/v1.0c                              12 files,  1.03 to 16.07 GB
  COMPOUND/v1.0a                          6 files,  2.81 to 12.17 GB
  CRISPR/v1.0b                            9 files,  0.09 to  1.12 GB
  ORF/v1.0b                               8 files,  0.18 to  1.83 GB
  compound_DL_CPCNN/v1.0                  7 files,  2.51 to  2.58 GB
  compound_DL_CPCNN_no_source7/v1.0       7 files,  2.38 to  2.45 GB
  compound_DL_EFNET/v1.0                  2 files, 23.99 to 24.20 GB
  compound_no_source7/v1.0                7 files,  1.10 to 12.00 GB

Within each folder the files are the same profiles at successive processing steps, and the file name lists the steps applied, in order. The file this notebook reads ends in ..._var_mad_int_featselect_harmony_PCA_corrected: well-position correction, variance filtering, robust scaling per plate, rank normalization, feature selection, batch correction with Harmony, then PCA. It is the smallest file and the one meant for comparing perturbations. The compound profiles are 2.8 to 12 GB per file and are best read a few columns or rows at a time.

The metadata tables

Profiles identify a perturbation only by a JUMP id such as JCP2022_800002. The metadata tables say what each id is.

for name in sorted(os.listdir(META)):
    cols = con.execute(f"describe select * from read_parquet('{META}/{name}')").fetchall()
    n = con.execute(f"select count(*) from read_parquet('{META}/{name}')").fetchall()[0][0]
    shown = ", ".join(c[0].replace("Metadata_", "") for c in cols[:5]) + (", ..." if len(cols) > 5 else "")
    print(f"  {name:30} {n:>9,} rows   {shown}")

print()
print(con.execute(f"""select Metadata_perturbation_modality as modality, count(*) as perturbations
                      from read_parquet('{META}/perturbation.parquet') group by all order by 2 desc""").df().to_string(index=False))

Output:

  cellprofiler_version.parquet          13 rows   Source, CellProfiler_Version
  compound.parquet                 115,796 rows   JCP2022, InChIKey, InChI, SMILES
  compound_source.parquet          126,044 rows   Compound_Source, JCP2022
  crispr.parquet                     7,977 rows   JCP2022, NCBI_Gene_ID, Symbol
  microscope_config.parquet             13 rows   Source, Microscope_Name, Widefield_vs_Confocal, Excitation_Type, Objective_NA, ...
  microscope_filter.parquet              8 rows   Filter_Configuration, Excitation_Low_DNA, Excitation_Low_ER, Excitation_Low_RNA, Excitation_Low_AGP, ...
  orf.parquet                       15,132 rows   JCP2022, broad_sample, Name, Vector, Transcript, ...
  perturbation.parquet             138,906 rows   JCP2022, perturbation_modality
  perturbation_control.parquet          18 rows   JCP2022, pert_type, Name
  plate.parquet                      2,525 rows   Source, Batch, Plate, PlateType
  well.parquet                   1,151,808 rows   Source, Plate, Well, JCP2022

modality  perturbations
compound         115796
     orf          15132
...

well.parquet is the key table: it maps every well on every plate at every site to the perturbation in it. compound.parquet gives each compound's InChIKey and SMILES, crispr.parquet and orf.parquet the gene.

The CRISPR knockout plates

per_gene = profiles[~profiles.gene.isin(controls)].groupby("gene").size()
print(f"{profiles.Metadata_Plate.nunique()} plates from {profiles.Metadata_Source.nunique()} site ({profiles.Metadata_Source.iloc[0]}), {len(profiles):,} wells")
print(f"control wells: {(profiles.gene == 'non-targeting').sum():,} non-targeting guide, {(profiles.gene == 'no-guide').sum():,} no guide")
print(f"{len(per_gene):,} genes knocked out; {(per_gene == 5).mean():.0%} of them have exactly 5 wells, {(per_gene > 20).sum()} has more than 20:")
for gene, n in per_gene[per_gene > 20].items():
    print(f"  {gene}: {n} wells on {profiles.loc[profiles.gene == gene, 'Metadata_Plate'].nunique()} plates")

example = profiles.loc[profiles.gene == GENE, ["Metadata_Plate", "Metadata_Well"]]
print(f"\nthe {len(example)} wells for {GENE}:")
print(example.to_string(index=False))

Output:

148 plates from 1 site (source_13), 51,185 wells
control wells: 2,754 non-targeting guide, 4,724 no guide
7,975 genes knocked out; 84% of them have exactly 5 wells, 1 has more than 20:
  PLK1: 569 wells on 141 plates

the 5 wells for PSMA1:
Metadata_Plate Metadata_Well
  CP-CC9-R1-18           H17
  CP-CC9-R2-18           H17
  CP-CC9-R3-18           H17
  CP-CC9-R4-18           H17
  CP-CC9-R5-18           H17

Most genes have five wells, one on each of five replicate plates, and (as the example shows) in the same well position on each. PLK1, a gene cells need in order to divide, is on most plates; perturbation_control.parquet lists it as the positive control. The well position matters for the next step: wells in the same position share edge and dispensing effects, so replicates of a gene could look alike for reasons that have nothing to do with the gene. The comparison below allows for that.

Which knockouts change how cells look?

If a knockout has a real effect, its five wells should resemble each other more than two unrelated wells do. For each gene the cell below takes the median cosine similarity between its replicate wells. The baseline is pairs of wells that hold different genes but sit in the same well position on plates with a different layout (the last number in the plate name), so whatever a shared position contributes is in the baseline too.

wells = profiles[features].to_numpy(copy=True)
wells /= np.linalg.norm(wells, axis=1, keepdims=True)
gene_of = profiles.gene.to_numpy()

replicate = {}
for gene, idx in profiles.groupby("gene").indices.items():
    if gene in controls or len(idx) < 3 or len(idx) > 20:
        continue
    s = wells[idx] @ wells[idx].T
    replicate[gene] = np.median(s[np.triu_indices(len(idx), 1)])
replicate = pd.Series(replicate).sort_values(ascending=False)

rng = np.random.default_rng(0)
layout = profiles.Metadata_Plate.str.rsplit("-", n=1).str[-1].to_numpy()
is_control = profiles.gene.isin(controls).to_numpy()
null = []
for position, idx in profiles.groupby("Metadata_Well").indices.items():
    i, j = rng.choice(idx, 300), rng.choice(idx, 300)
    keep = (gene_of[i] != gene_of[j]) & (layout[i] != layout[j]) & ~is_control[i] & ~is_control[j]
    null.append((wells[i[keep]] * wells[j[keep]]).sum(1))
null = np.concatenate(null)
threshold = np.percentile(null, 95)
reproducible = replicate[replicate > threshold]

print(f"baseline, {len(null):,} pairs of different genes in the same well position: median similarity {np.median(null):.2f}, 95th percentile {threshold:.2f}")
print(f"replicates of the same knockout: median similarity {replicate.median():.2f}")
print(f"{len(reproducible):,} of {len(replicate):,} genes ({len(reproducible) / len(replicate):.0%}) have replicate similarity above the baseline's 95th percentile")
print(f"\nmost reproducible knockouts: {', '.join(replicate.index[:20])}")

fig, ax = plt.subplots(figsize=(7, 3.4), dpi=85)
bins = np.linspace(-0.6, 1, 65)
ax.hist(null, bins=bins, density=True, color="#9ca3af", alpha=0.8, label="different genes, same well position")
ax.hist(replicate, bins=bins, density=True, color="#1d4ed8", alpha=0.6, label="replicates of the same knockout")
ax.axvline(threshold, color="#111827", lw=1, ls="--")
ax.set_xlabel("cosine similarity"); ax.set_ylabel("density"); ax.legend(frameon=False, fontsize=8)
ax.spines[["top", "right"]].set_visible(False)
plt.tight_layout(); plt.show()

Output:

baseline, 76,489 pairs of different genes in the same well position: median similarity 0.02, 95th percentile 0.47
replicates of the same knockout: median similarity 0.21
1,311 of 7,967 genes (16%) have replicate similarity above the baseline's 95th percentile

most reproducible knockouts: SUPT6H, NXF1, RAN, HSPA5, MDM2, EIF4A3, KIF23, DHX8, WEE1, CDC6, VCP, PSMA1, PSMC2, PCNA, ESPL1, RRM1, PSMD14, POLR2I, PRPF8, PSMB4

By chance 5% of genes would pass that threshold, so the excess over 5% is the share of knockouts with a clear effect on cell appearance in this cell line. The whole replicate distribution also sits to the right of the baseline, so many more knockouts have a small effect that this one-gene-at-a-time test cannot separate from noise. That most knockouts change little is the expected result: U2OS cells do not need most genes to look normal under these stains. The genes at the top of the list are ones cells cannot do without (proteasome, RNA polymerase, splicing, cell division).

Do similar profiles mean related genes?

The start-here cell listed the nearest neighbors of one gene. The cell below asks the question for whole groups: for each family of genes that work together as one machine, how often is a member's single most similar knockout another member of the same family?

families = {
    "proteasome (PSM...)": "PSM",
    "RNA polymerase II (POLR2...)": "POLR2",
    "Mediator (MED...)": "MED",
    "translation initiation factor 3 (EIF3...)": "EIF3",
    "chaperonin (CCT...)": "CCT",
    "V-ATPase (ATP6V...)": "ATP6V",
    "respiratory complex I (NDUF...)": "NDUF",
    "solute carriers (SLC...)": "SLC",
}
sim = unit @ unit.T
np.fill_diagonal(sim, -np.inf)
nearest = consensus.index[sim.argmax(1)]
names = consensus.index.to_series()

print(f"{'family':44} genes  nearest neighbor in family   expected by chance")
for label, prefix in families.items():
    members = names[names.str.startswith(prefix)]
    hit = np.mean([nearest[consensus.index.get_loc(g)].startswith(prefix) for g in members])
    print(f"{label:44} {len(members):5}  {hit:26.0%}   {(len(members) - 1) / (len(names) - 1):18.1%}")

print()
for gene in ["KIF23", "ATP6V1A"]:
    print(f"{gene}: " + ", ".join(f"{g} ({s:.2f})" for g, s in neighbors(gene, 6).items()))

Output:

family                                       genes  nearest neighbor in family   expected by chance
proteasome (PSM...)                             24                         62%                 0.3%
RNA polymerase II (POLR2...)                    12                         75%                 0.1%
Mediator (MED...)                               17                         59%                 0.2%
translation initiation factor 3 (EIF3...)       10                         50%                 0.1%
chaperonin (CCT...)                              8                         38%                 0.1%
V-ATPase (ATP6V...)                             16                         38%                 0.2%
respiratory complex I (NDUF...)                 29                          0%                 0.4%
solute carriers (SLC...)                       253                          4%                 3.2%

KIF23: BIRC5 (0.94), AURKB (0.91), ESPL1 (0.90), CDK1 (0.82), PTTG1 (0.81), IRX2 (0.78)
ATP6V1A: ATP6V1B2 (0.81), PTPMT1 (0.74), ATP6V1E1 (0.74), POLN (0.70), SLC27A3 (0.69), SLC39A1 (0.69)

Families whose loss stops the cell in a specific way (proteasome, RNA polymerase II, Mediator) find each other far more often than chance. Families with little or no visible phenotype in this assay (complex I, most solute carriers) do not, which is consistent with the reproducibility result above: a profile can only say what a gene does if knocking the gene out changes the picture. The solute carriers are a family by name only, not a complex, and are there as a check that a shared prefix alone does not produce a match.

KIF23 shows the kind of answer the assay is good at: its nearest neighbors are other genes needed to separate chromosomes and split the cell in two, and a failed division changes the nucleus in a way that is easy to see in an image.

Going further

Source: Chandrasekaran SN et al. JUMP Cell Painting dataset: morphological impact of 136,000 chemical and genetic perturbations. bioRxiv 2023.03.23.534023. Data are in the Cell Painting Gallery under CC0 1.0.

Run it

Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.