Skip to content

crispr_analysis_utils.pairs

crispr_analysis_utils.pairs

The guide-gene pairs a screen tests: discovery and positive control.

Built from the IGVF per-guide table alone, so the pairs name exactly the elements and genes the submission does.

  • positive_control: a guide typed positive control with each gene in its putative_target_genes. Those genes are the ones the design measured the element against, so a gene outside the readout panel is kept and flagged rather than dropped.
  • discovery: a targeting guide with each readout gene whose TSS lies within max_distance of the element's midpoint. Where that element and gene are a positive control's, the pair is labelled positive_control instead, so a promoter still pairs with its other neighbours as discovery.

Control guides get no pairs; the inference calibrates on them.

TARGET_COLUMNS module-attribute

TARGET_COLUMNS = ('intended_target_name', 'intended_target_chr', 'intended_target_start', 'intended_target_end')

The element's identity, as the per-guide table and the pipeline name it.

COLUMNS module-attribute

COLUMNS = {'guide_id': 'The guide, as guide_metadata.tsv names it.', 'gene_id': 'ENSEMBL gene id, without its version.', 'gene_symbol': "The gene's symbol in the annotation store.", 'intended_target_name': 'The element, as guide_metadata.tsv names it.', 'intended_target_chr': 'Chromosome of the element.', 'intended_target_start': 'Start of the element, 0-based.', 'intended_target_end': 'End of the element, half-open.', 'pair_type': 'positive_control: the gene the design measured this element against. discovery: a readout gene whose TSS is within the distance limit.', 'distance_to_tss': "Bases from the element's midpoint to the gene's TSS, signed in the gene's orientation: negative upstream, positive downstream.", 'in_panel': 'TRUE when the gene is in the readout panel given to --genes.'}

Every column of the pairs table, and what it holds.

TABLE module-attribute

TABLE = 'pairs_to_test.csv'

Comma-separated, like the CRISPR pipeline's own pairs file.

PairsError

Bases: RuntimeError

The inputs cannot be turned into pairs.

Source code in src/crispr_analysis_utils/pairs.py
74
75
class PairsError(RuntimeError):
    """The inputs cannot be turned into pairs."""

RunResult dataclass

What run produced.

Source code in src/crispr_analysis_utils/pairs.py
78
79
80
81
82
83
84
@dataclass
class RunResult:
    """What `run` produced."""

    outdir: Path
    pairs: pd.DataFrame
    metadata: dict = field(default_factory=dict)

read_panel

read_panel(path: str | PathLike[str], gene_column: str = 'gene_id') -> pd.Index

The readout genes, as unversioned ENSEMBL ids.

Parameters:

  • path (str | PathLike[str]) –

    A CSV or TSV, as read_columns reads it.

  • gene_column (str, default: 'gene_id' ) –

    The column of ENSEMBL gene ids. A row with it empty is skipped.

Returns:

  • Index –

    Unique ids, in file order.

Raises:

  • PairsError –

    The panel names no gene.

  • ValueError –

    The suffix names no separator, or gene_column is missing.

Source code in src/crispr_analysis_utils/pairs.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def read_panel(path: str | os.PathLike[str], gene_column: str = "gene_id") -> pd.Index:
    """The readout genes, as unversioned ENSEMBL ids.

    Parameters
    ----------
    path
        A CSV or TSV, as `read_columns` reads it.
    gene_column
        The column of ENSEMBL gene ids. A row with it empty is skipped.

    Returns
    -------
    pandas.Index
        Unique ids, in file order.

    Raises
    ------
    PairsError
        The panel names no gene.
    ValueError
        The suffix names no separator, or `gene_column` is missing.
    """
    genes = read_columns(path, [gene_column], "readout panel")[gene_column]
    if genes.empty:
        raise PairsError(f"The readout panel {path} names no gene.")
    return pd.Index(_unversioned(genes).unique())

gene_tss

gene_tss(store) -> pd.DataFrame

One TSS per gene, from the transcript the annotation chooses.

Parameters:

  • store –

    A loaded guide_annotation.db.Store.

Returns:

  • DataFrame –

    Indexed by gene_id: gene_symbol, chr, tss (0-based) and strand. The reference transcript is MANE Select, else Ensembl canonical, else the longest CDS; a gene without one falls back to its own row.

Source code in src/crispr_analysis_utils/pairs.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def gene_tss(store) -> pd.DataFrame:
    """One TSS per gene, from the transcript the annotation chooses.

    Parameters
    ----------
    store
        A loaded `guide_annotation.db.Store`.

    Returns
    -------
    pandas.DataFrame
        Indexed by ``gene_id``: ``gene_symbol``, ``chr``, ``tss`` (0-based) and
        ``strand``. The reference transcript is MANE Select, else Ensembl
        canonical, else the longest CDS; a gene without one falls back to its
        own row.
    """
    transcripts = store.rows("transcript", reference_only=True, primary=False)
    genes = store.rows("gene", primary=False)
    rows = pd.concat(
        [transcripts, genes[~genes["ensg"].isin(transcripts["ensg"])]],
        ignore_index=True,
    ).drop_duplicates("ensg")
    plus = rows["Strand"] == "+"
    return pd.DataFrame(
        {
            "gene_symbol": rows["gene_symbol"].to_numpy(),
            "chr": rows["Chromosome"].astype(str).to_numpy(),
            "tss": np.where(plus, rows["Start"], rows["End"] - 1).astype("int64"),
            "strand": rows["Strand"].astype(str).to_numpy(),
        },
        index=pd.Index(rows["ensg"].to_numpy(), name="gene_id"),
    )

build_pairs

build_pairs(guides: DataFrame, panel: Index, tss: DataFrame, *, max_distance: int = DEFAULT_MAX_DISTANCE) -> pd.DataFrame

Every positive-control and discovery pair, one row per guide and gene.

Parameters:

  • guides (DataFrame) –

    The IGVF per-guide table: guide_id, targeting, type, the four TARGET_COLUMNS and putative_target_genes.

  • panel (Index) –

    The readout genes, unversioned.

  • tss (DataFrame) –

    gene_tss output.

  • max_distance (int, default: DEFAULT_MAX_DISTANCE ) –

    The largest distance, in bases, from an element's midpoint to a readout gene's TSS for a discovery pair.

Returns:

  • DataFrame –

    The columns of COLUMNS, positive controls first.

Raises:

  • PairsError –

    A required column is missing, or a panel gene or a positive-control gene is not in the annotation.

Source code in src/crispr_analysis_utils/pairs.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def build_pairs(
    guides: pd.DataFrame,
    panel: pd.Index,
    tss: pd.DataFrame,
    *,
    max_distance: int = DEFAULT_MAX_DISTANCE,
) -> pd.DataFrame:
    """Every positive-control and discovery pair, one row per guide and gene.

    Parameters
    ----------
    guides
        The IGVF per-guide table: ``guide_id``, ``targeting``, ``type``, the
        four `TARGET_COLUMNS` and ``putative_target_genes``.
    panel
        The readout genes, unversioned.
    tss
        `gene_tss` output.
    max_distance
        The largest distance, in bases, from an element's midpoint to a
        readout gene's TSS for a discovery pair.

    Returns
    -------
    pandas.DataFrame
        The columns of `COLUMNS`, positive controls first.

    Raises
    ------
    PairsError
        A required column is missing, or a panel gene or a positive-control
        gene is not in the annotation.
    """
    missing = {
        "guide_id",
        "targeting",
        "type",
        "putative_target_genes",
        *TARGET_COLUMNS,
    } - set(guides)
    if missing:
        raise PairsError(f"The guide table lacks {', '.join(sorted(missing))}.")
    absent = panel.difference(tss.index)
    if len(absent):
        raise PairsError(
            f"{len(absent)} panel genes are not in the annotation, e.g. {', '.join(absent[:3])}."
            " The panel and the annotation must be the same GENCODE release."
        )

    frame = guides.copy()
    frame["targeting"] = frame["targeting"].map(truthy)
    for column in ("intended_target_start", "intended_target_end"):
        frame[column] = pd.to_numeric(frame[column], errors="coerce").astype("Int64")
    targeting = frame[frame["targeting"] & frame["intended_target_start"].notna()]

    positive = _positive_pairs(targeting, tss)
    discovery = _discovery_pairs(targeting, panel, tss, max_distance)
    key = [
        "intended_target_chr",
        "intended_target_start",
        "intended_target_end",
        "gene_id",
    ]
    taken = pd.MultiIndex.from_frame(positive[key])
    discovery.loc[pd.MultiIndex.from_frame(discovery[key]).isin(taken), "pair_type"] = (
        POSITIVE_CONTROL
    )

    pairs = pd.concat([positive, discovery], ignore_index=True)
    pairs = pairs.drop_duplicates(["guide_id", "gene_id"])
    pairs["in_panel"] = pairs["gene_id"].isin(panel)
    return pairs[list(COLUMNS)].reset_index(drop=True)

counts

counts(pairs: DataFrame, panel: Index) -> dict

What the run record and qc.tsv report.

Source code in src/crispr_analysis_utils/pairs.py
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
def counts(pairs: pd.DataFrame, panel: pd.Index) -> dict:
    """What the run record and qc.tsv report."""
    found: dict = {"pairs": len(pairs)}
    for pair_type in PAIR_TYPES:
        part = pairs[pairs["pair_type"] == pair_type]
        found[pair_type] = {
            "pairs": len(part),
            "guides": int(part["guide_id"].nunique()),
            "elements": int(part[list(TARGET_COLUMNS)].drop_duplicates().shape[0]),
            "genes": int(part["gene_id"].nunique()),
            "genes_outside_panel": int(
                part.loc[~part["in_panel"], "gene_id"].nunique()
            ),
        }
    found["panel_genes"] = len(panel)
    found["panel_genes_without_pairs"] = int((~panel.isin(pairs["gene_id"])).sum())
    return found

write_qc_tsv

write_qc_tsv(path: str | PathLike[str], found: dict) -> None

Counts, one per row, in the section/name/value shape the other steps use.

Source code in src/crispr_analysis_utils/pairs.py
293
294
295
296
297
298
299
300
301
302
303
304
def write_qc_tsv(path: str | os.PathLike[str], found: dict) -> None:
    """Counts, one per row, in the section/name/value shape the other steps use."""
    rows = [("pairs", "total", found["pairs"])]
    for pair_type in PAIR_TYPES:
        rows += [(pair_type, name, value) for name, value in found[pair_type].items()]
    rows += [
        ("panel", "genes", found["panel_genes"]),
        ("panel", "genes_without_pairs", found["panel_genes_without_pairs"]),
    ]
    pd.DataFrame(rows, columns=["section", "name", "value"]).to_csv(
        path, sep="\t", index=False
    )

write_columns_yaml

write_columns_yaml(path: str | PathLike[str]) -> None

Write pairs_to_test_columns.yaml, generated from COLUMNS so it cannot drift.

Source code in src/crispr_analysis_utils/pairs.py
307
308
309
310
311
def write_columns_yaml(path: str | os.PathLike[str]) -> None:
    """Write pairs_to_test_columns.yaml, generated from `COLUMNS` so it cannot drift."""
    lines = ["# What each column of this folder's output holds.", "", f"{TABLE}:"]
    lines += [f"  {name}: {yaml_text(text)}" for name, text in COLUMNS.items()]
    Path(path).write_text("\n".join(lines) + "\n", encoding="utf-8")

run

run(guide_metadata: str | PathLike[str], panel: str | PathLike[str], store: str | PathLike[str], outdir: str | PathLike[str], *, max_distance: int = DEFAULT_MAX_DISTANCE, gene_column: str = 'gene_id') -> RunResult

Build the pairs and write them.

Parameters:

  • guide_metadata (str | PathLike[str]) –

    guide_metadata.tsv from igvf_export.run.

  • panel (str | PathLike[str]) –

    The readout genes: a CSV or TSV with a column of ENSEMBL gene ids.

  • store (str | PathLike[str]) –

    The annotation store the guide table was built with.

  • outdir (str | PathLike[str]) –

    Where the table goes. Nothing is written outside it.

  • max_distance (int, default: DEFAULT_MAX_DISTANCE ) –

    The largest distance from an element's midpoint to a readout gene's TSS for a discovery pair.

  • gene_column (str, default: 'gene_id' ) –

    The panel's column of ENSEMBL gene ids.

Returns:

  • RunResult –

    The pairs and the run record.

Source code in src/crispr_analysis_utils/pairs.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def run(
    guide_metadata: str | os.PathLike[str],
    panel: str | os.PathLike[str],
    store: str | os.PathLike[str],
    outdir: str | os.PathLike[str],
    *,
    max_distance: int = DEFAULT_MAX_DISTANCE,
    gene_column: str = "gene_id",
) -> RunResult:
    """Build the pairs and write them.

    Parameters
    ----------
    guide_metadata
        ``guide_metadata.tsv`` from `igvf_export.run`.
    panel
        The readout genes: a CSV or TSV with a column of ENSEMBL gene ids.
    store
        The annotation store the guide table was built with.
    outdir
        Where the table goes. Nothing is written outside it.
    max_distance
        The largest distance from an element's midpoint to a readout gene's
        TSS for a discovery pair.
    gene_column
        The panel's column of ENSEMBL gene ids.

    Returns
    -------
    RunResult
        The pairs and the run record.
    """
    from .guide_annotation.db import load_store

    outdir = Path(outdir)
    parameters = {"max_distance": max_distance, "gene_column": gene_column}
    with run_record(outdir, STEP, RESULTS_DIR, parameters, logger, "Pairs") as (
        state,
        _,
    ):
        for name, path in (
            ("guide_metadata", guide_metadata),
            ("panel", panel),
            ("store", store),
        ):
            if not Path(path).is_file():
                raise FileNotFoundError(
                    f"The {name.replace('_', ' ')} {path} does not exist."
                )
            state["inputs"][name] = str(path)
            state["inputs"][f"{name}_md5"] = file_md5(path)

        guides = pd.read_csv(guide_metadata, sep="\t", dtype=str, keep_default_na=False)
        genes = read_panel(panel, gene_column)
        tss = gene_tss(load_store(store))
        logger.info(
            "%d guides, %d panel genes, %d annotated genes",
            len(guides),
            len(genes),
            len(tss),
        )

        pairs = build_pairs(guides, genes, tss, max_distance=max_distance)
        write_table(outdir / RESULTS_DIR / TABLE, pairs)
        write_columns_yaml(outdir / RESULTS_DIR / "pairs_to_test_columns.yaml")
        found = counts(pairs, genes)
        write_qc_tsv(outdir / RESULTS_DIR / "qc.tsv", found)
        unpaired = genes[~genes.isin(pairs["gene_id"])]
        tss.loc[unpaired, ["gene_symbol", "chr", "tss", "strand"]].reset_index().to_csv(
            outdir / RESULTS_DIR / "panel_genes_without_pairs.tsv",
            sep="\t",
            index=False,
        )

        state["counts"] = found
        logger.info(
            "Pairs complete: %d positive control, %d discovery",
            found[POSITIVE_CONTROL]["pairs"],
            found[DISCOVERY]["pairs"],
        )
        return RunResult(outdir=outdir, pairs=pairs, metadata=state)

write_table

write_table(path: str | PathLike[str], pairs: DataFrame) -> None

Write the pairs, with booleans as TRUE and FALSE like the other tables.

Source code in src/crispr_analysis_utils/pairs.py
397
398
399
400
401
def write_table(path: str | os.PathLike[str], pairs: pd.DataFrame) -> None:
    """Write the pairs, with booleans as TRUE and FALSE like the other tables."""
    out = pairs.copy()
    out["in_panel"] = out["in_panel"].map({True: "TRUE", False: "FALSE"})
    out.to_csv(path, index=False)