Open Targets: sample notebook

A worked notebook for Open Targets, 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
Open Targets
License
https://creativecommons.org/publicdomain/zero/1.0/
Format
JSON, Parquet (in sampled files)
Stored at
Amazon S3, s3://open-targets-public-data-releases (eu-west-1)
Access
Free and public. No account with the data provider is needed.

The notebook

Start here. Click the grey cell below and press Shift+Enter. It finds a disease by name and prints the ten genes with the strongest overall evidence for it. Then change DISEASE (for example "asthma", "heart failure" or "Alzheimer disease") and run it again.

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

DISEASE = "ulcerative colitis"
RELEASE = "26.12"

ROOT = os.environ.get("SCIGANTIC_MOUNT_PATH", "/mnt/archive")
OUT = f"{ROOT}/platform/{RELEASE}/output"
con = globals().get("con") or duckdb.connect()     # keep the connection, and what it has loaded, when this cell is rerun
con.execute("SET threads = 32")                    # files are read over the network, so more readers than CPUs helps
con.execute("SET enable_progress_bar = false")

def table(name):
    """A table in the release is a folder of parquet files; this is how DuckDB reads one."""
    return f"read_parquet('{OUT}/{name}/*.parquet')"

def q(sql, params=None):
    return con.execute(sql, params or []).df()

found = q(f"select id, name from {table('disease')} where lower(name) = lower(?)", [DISEASE])
if found.empty:
    raise SystemExit(f"No disease is named exactly {DISEASE!r}. Try: " + ", ".join(
        q(f"select name from {table('disease')} where name ilike ? limit 8", [f"%{DISEASE}%"]).name))
DISEASE_ID, DISEASE_NAME = found.iloc[0]

# The association table is 64 files. Read its four small columns once and keep them in memory,
# so that changing DISEASE and running this cell again is immediate.
con.execute(f"""create table if not exists overall as
    select diseaseId, targetId, associationScore, evidenceCount from {table('association_overall_direct')}""")

top = q(f"""
    select t.approvedSymbol as gene, t.approvedName as name, round(a.associationScore, 3) as score, a.evidenceCount as evidence
    from overall a join {table('target')} t on t.id = a.targetId
    where a.diseaseId = ? order by a.associationScore desc limit 10""", [DISEASE_ID])
print(f"{DISEASE_NAME} ({DISEASE_ID}): top 10 targets by overall association score")
print(top.to_string(index=False))

Open Targets Platform

The Open Targets Platform brings together public evidence that links human genes ("targets") to diseases: genetic associations, somatic mutations, known drugs, expression, animal models, pathways and text mining. Each piece of evidence is scored, and the scores are combined into one association score per target and disease. It is the standard open resource for choosing and checking drug targets.

The archive is the platform's full data download. Each release is a folder under platform/, and each table in a release is a folder of parquet files under output/. The cells below read them where they are with DuckDB, which fetches only the columns a query needs. The two association tables used here are spread over 64 files each, so the notebook reads their small columns into memory once (the overall table in the first cell, by_datatype below) and queries those.

releases = sorted(os.listdir(f"{ROOT}/platform"))
tables = sorted(os.listdir(OUT))
print(f"{len(releases)} releases, {releases[0]} to {releases[-1]}; this notebook reads {RELEASE}")
print(f"{len(tables)} tables in {RELEASE}, of which {sum(t.startswith('evidence_') for t in tables)} hold evidence from one source each\n")

for name in ["target", "disease", "drug_molecule", "association_overall_direct", "association_by_datatype_direct",
             "clinical_indication", "clinical_target", "target_tractability"]:
    files = os.listdir(f"{OUT}/{name}")
    size = sum(os.path.getsize(f"{OUT}/{name}/{f}") for f in files) / 1e6
    n = con.execute(f"select count(*) from {table(name)}").fetchall()[0][0]
    print(f"  {name:32} {n:>10,} rows  {len(files):3} files  {size:7.1f} MB")

Output:

5 releases, 25.12 to 26.12; this notebook reads 26.12
64 tables in 26.12, of which 20 hold evidence from one source each

  target                               78,733 rows    1 files     21.5 MB
  disease                              46,288 rows    1 files      6.7 MB
  drug_molecule                        19,411 rows    1 files      7.0 MB
  association_overall_direct        4,367,603 rows   64 files    332.8 MB
  association_by_datatype_direct    4,591,855 rows   64 files    341.2 MB
  clinical_indication                  67,972 rows    1 files      4.3 MB
  clinical_target                      17,280 rows    1 files      2.7 MB
  target_tractability                 528,332 rows    1 files      0.1 MB

target has one row per human gene (Ensembl id), disease one row per disease or phenotype (ontology ids such as MONDO_0005101), and drug_molecule one row per drug (ChEMBL id). The association_* tables hold the scores. "Direct" means evidence annotated to that exact disease; the _indirect tables also count evidence for its subtypes.

What kind of evidence supports each target

The overall score hides where the evidence comes from. association_by_datatype_direct splits it by data type. The cell below loads that table and takes the 15 top targets for the disease chosen above and shows the score from each data type.

con.execute(f"""create table if not exists by_datatype as
    select diseaseId, targetId, aggregationValue as datatype, associationScore from {table('association_by_datatype_direct')}""")

by_type = q(f"""
    with top as (select targetId, associationScore as overall from overall
                 where diseaseId = ? order by associationScore desc limit 15)
    select t.approvedSymbol as gene, top.overall, d.datatype, d.associationScore as score
    from top join {table('target')} t on t.id = top.targetId
    left join by_datatype d on d.targetId = top.targetId and d.diseaseId = ?""",
    [DISEASE_ID, DISEASE_ID])
order = by_type.drop_duplicates("gene").sort_values("overall", ascending=False).gene
grid = by_type.pivot(index="gene", columns="datatype", values="score").reindex(order)
grid = grid[grid.notna().sum().sort_values(ascending=False).index]
print(grid.round(2).astype(object).where(grid.notna(), "").to_string())

fig, ax = plt.subplots(figsize=(7.5, 5), dpi=85)
im = ax.imshow(grid.fillna(0).to_numpy(), cmap="Blues", vmin=0, vmax=1, aspect="auto")
ax.set_xticks(range(grid.shape[1])); ax.set_xticklabels([c.replace("_", " ") for c in grid.columns], rotation=35, ha="right")
ax.set_yticks(range(grid.shape[0])); ax.set_yticklabels(grid.index)
ax.set_title(f"{DISEASE_NAME}: association score by data type")
fig.colorbar(im, ax=ax, shrink=0.8, label="score")
plt.tight_layout(); plt.show()

Output:

datatype known_drug literature rna_expression genetic_association somatic_mutation
gene                                                                              
JAK2           0.97       0.85           0.04                0.83              0.3
IL12B          0.98       0.64                               0.87                 
JAK3           0.97       0.23           0.11                                 0.46
IL23R          0.46       0.88           0.03                0.94                 
TNF            0.99       0.99           0.02                                     
PPARG          0.99       0.86           0.15                                     
TNFSF15        0.66       0.38           0.04                0.86                 
NR3C1          0.99       0.75           0.01                                     
IL23A          0.98       0.77           0.21                                     
PTGS2          0.99       0.62           0.22                                     
PTGS1          0.99       0.32           0.01                                     
ALOX5          0.99       0.15           0.07                                     
ITGA4          0.98       0.33           0.01                                     
...

A blank cell means the platform holds no evidence of that type for the pair. Targets whose score comes from known_drug are ones a drug for this disease already acts on; targets scoring on genetic_association are supported by human genetics, the evidence type that published analyses of past trials have linked to a higher chance of approval.

Drugs in the clinic for this disease

clinical_indication lists each drug and disease pair with the furthest clinical stage it reached, and clinical_target lists the targets each drug acts on. Joining them gives the drugs developed for the disease and what they hit.

drugs = q(f"""
    select m.name as drug, m.drugType as type, i.maxClinicalStage as stage,
           string_agg(distinct t.approvedSymbol, ', ' order by t.approvedSymbol) as targets
    from {table('clinical_indication')} i
    join {table('drug_molecule')} m on m.id = i.drugId
    left join {table('clinical_target')} ct on ct.drugId = i.drugId
    left join {table('target')} t on t.id = ct.targetId
    where i.diseaseId = ? group by all""", [DISEASE_ID])
stage_order = ["APPROVAL", "PREAPPROVAL", "PHASE_4", "PHASE_3", "PHASE_2_3", "PHASE_2", "PHASE_1_2", "PHASE_1",
               "EARLY_PHASE_1", "IND", "PRECLINICAL", "WITHDRAWAL", "UNKNOWN"]
print(f"{len(drugs)} drugs with a clinical record for {DISEASE_NAME}")
print(drugs.stage.value_counts().reindex([s for s in stage_order if s in set(drugs.stage)]).to_string())

approved = drugs[drugs.stage == "APPROVAL"].sort_values("drug")
print(f"\nApproved ({len(approved)}):")
print(approved[["drug", "type", "targets"]].fillna("").to_string(index=False, max_colwidth=60))

Output:

207 drugs with a clinical record for ulcerative colitis
stage
APPROVAL         34
PREAPPROVAL       1
PHASE_3          32
PHASE_2_3         9
PHASE_2          99
PHASE_1_2         8
PHASE_1          13
EARLY_PHASE_1     4
PRECLINICAL       1
UNKNOWN           6

Approved (34):
                          drug           type                    targets
...

Genetically supported targets with no drug yet

A common question is the reverse one: which genes have strong human genetic evidence for the disease but no drug in clinical development for any disease, and could a drug be made against them? target_tractability records, for each target, whether it passes checks such as "has a high-quality small-molecule pocket" or "is predicted to be on the cell surface" (reachable by an antibody).

candidates = q(f"""
    with genetic as (select targetId, associationScore as genetic_score from by_datatype
                     where diseaseId = ? and datatype = 'genetic_association'),
    drugged as (select distinct targetId from {table('clinical_target')}),
    tract as (select targetId,
                     bool_or(modality = 'SM' and category in ('High-Quality Pocket', 'High-Quality Ligand', 'Structure with Ligand') and value) as small_molecule,
                     bool_or(modality = 'AB' and category in ('UniProt loc high conf', 'GO CC high conf') and value) as antibody
              from {table('target_tractability')} group by targetId)
    select t.approvedSymbol as gene, round(g.genetic_score, 3) as genetic_score,
           coalesce(tract.small_molecule, false) as small_molecule, coalesce(tract.antibody, false) as antibody, t.approvedName as name
    from genetic g join {table('target')} t on t.id = g.targetId
    left join tract on tract.targetId = g.targetId
    where g.targetId not in (select targetId from drugged)
    order by g.genetic_score desc""", [DISEASE_ID])
n_genetic = q("select count(*) as n from by_datatype where diseaseId = ? and datatype = 'genetic_association'", [DISEASE_ID]).n[0]
print(f"{n_genetic:,} targets have genetic evidence for {DISEASE_NAME}; {len(candidates):,} of them have no drug in the clinical tables")
strong = candidates[candidates.genetic_score >= 0.5]
print(f"{len(strong)} of those score 0.5 or more: {int(strong.small_molecule.sum())} pass a small-molecule check, {int(strong.antibody.sum())} an antibody check\n")
print(candidates.head(15).to_string(index=False, max_colwidth=48))

Output:

1,418 targets have genetic evidence for ulcerative colitis; 1,215 of them have no drug in the clinical tables
58 of those score 0.5 or more: 17 pass a small-molecule check, 15 an antibody check

   gene  genetic_score  small_molecule  antibody                                             name
 NKX2-3          0.754           False     False                                   NK2 homeobox 3
  ADCY7          0.749           False      True                              adenylate cyclase 7
  OTUD3          0.738           False     False                             OTU deubiquitinase 3
  GPR35          0.735            True      True                    G protein-coupled receptor 35
  GPR12          0.731           False      True                    G protein-coupled receptor 12
 RNF186          0.725           False     False                          ring finger protein 186
 TNRC18          0.719           False     False               trinucleotide repeat containing 18
  TMCO4          0.717           False     False          transmembrane and coiled-coil domains 4
  NXPE1          0.715           False     False neurexophilin and PC-esterase domain family m...
   IRF8          0.709           False     False                   interferon regulatory factor 8
   IRF5          0.692           False     False                   interferon regulatory factor 5
...

The tractability flags are screening checks, not a verdict: "small_molecule" here means the target has a high-quality pocket, a high-quality ligand or a structure with a ligand bound, and "antibody" means a high-confidence cell-surface or secreted location.

How the evidence built up over time

Each association row also carries a timeseries: the score recomputed with only the evidence available up to each year. That shows when a target became convincing.

series = q(f"""
    with top as (select targetId, timeseries from {table('association_overall_direct')}
                 where diseaseId = ? order by associationScore desc limit 6)
    select t.approvedSymbol as gene, s.year as year, s.associationScore as score
    from top, unnest(top.timeseries) as u(s) join {table('target')} t on t.id = top.targetId
    where s.year is not null order by 1, 2""", [DISEASE_ID])
fig, ax = plt.subplots(figsize=(7.5, 3.8), dpi=85)
for gene, g in series.groupby("gene"):
    ax.plot(g.year, g.score, lw=1.6, label=gene)
ax.set_xlabel("year"); ax.set_ylabel("association score using evidence up to that year")
ax.set_title(f"{DISEASE_NAME}: the six top targets over time")
ax.legend(frameon=False, fontsize=8, ncol=2); ax.spines[["top", "right"]].set_visible(False)
plt.tight_layout(); plt.show()
print(series.groupby("gene").agg(first_year=("year", "min"), last_year=("year", "max"), score_now=("score", "last")).round(3).to_string())

Output:

       first_year  last_year  score_now
gene                                   
IL12B        2003       2026      0.738
IL23R        2001       2026      0.651
JAK2         1996       2026      0.745
JAK3         1996       2026      0.666
PPARG        1995       2026      0.622
TNF          1985       2026      0.632

Going further

Source: Open Targets Platform, release 26.12, platform.opentargets.org. Data are released under CC0 1.0. Documentation: platform-docs.opentargets.org.

Run it

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