diffgrammar 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. diffgrammar/__init__.py +6 -0
  2. diffgrammar/adapters/__init__.py +21 -0
  3. diffgrammar/adapters/peak_npz.py +114 -0
  4. diffgrammar/align.py +195 -0
  5. diffgrammar/analysis.py +744 -0
  6. diffgrammar/attribute.py +445 -0
  7. diffgrammar/calibrate.py +279 -0
  8. diffgrammar/cli.py +659 -0
  9. diffgrammar/cluster.py +439 -0
  10. diffgrammar/config.py +213 -0
  11. diffgrammar/contrast.py +223 -0
  12. diffgrammar/effects.py +317 -0
  13. diffgrammar/export.py +185 -0
  14. diffgrammar/expression.py +399 -0
  15. diffgrammar/jaspar.py +185 -0
  16. diffgrammar/marginalize/__init__.py +4 -0
  17. diffgrammar/marginalize/backgrounds.py +107 -0
  18. diffgrammar/marginalize/cooperativity.py +344 -0
  19. diffgrammar/marginalize/design.py +209 -0
  20. diffgrammar/marginalize/plots.py +546 -0
  21. diffgrammar/marginalize/predictor.py +109 -0
  22. diffgrammar/marginalize/readout.py +86 -0
  23. diffgrammar/marginalize/run.py +223 -0
  24. diffgrammar/marginalize/store.py +191 -0
  25. diffgrammar/pair_regression.py +323 -0
  26. diffgrammar/plotting.py +1186 -0
  27. diffgrammar/scan.py +151 -0
  28. diffgrammar/selection.py +174 -0
  29. diffgrammar/seqlets.py +376 -0
  30. diffgrammar/sequence.py +22 -0
  31. diffgrammar/summaries.py +140 -0
  32. diffgrammar/toy.py +129 -0
  33. diffgrammar/view/__init__.py +0 -0
  34. diffgrammar/view/app.py +1942 -0
  35. diffgrammar/view/data.py +1950 -0
  36. diffgrammar/view/figures.py +400 -0
  37. diffgrammar/view/network/index.html +232 -0
  38. diffgrammar/view/network.py +21 -0
  39. diffgrammar/view/pages.py +257 -0
  40. diffgrammar/view/tracks/index.html +459 -0
  41. diffgrammar/view/tracks.py +153 -0
  42. diffgrammar-0.1.0.dist-info/METADATA +204 -0
  43. diffgrammar-0.1.0.dist-info/RECORD +47 -0
  44. diffgrammar-0.1.0.dist-info/WHEEL +5 -0
  45. diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
  46. diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
  47. diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
diffgrammar/export.py ADDED
@@ -0,0 +1,185 @@
1
+ """
2
+ A finished run as one small folder that opens with `diffgrammar view` anywhere: the tables of every step, the
3
+ JASPAR file, the marginalization design and tables (not the store), and the attributions of a few regions.
4
+
5
+ diffgrammar export config.toml -> export_<run name>/ beside the config
6
+ diffgrammar export config.toml --out share --n-regions 20 --n-motifs 5
7
+
8
+ Attributions are the bulk of a run (tens of GB for a large run), so the export keeps a sample: for each region set, the
9
+ `n_motifs` motifs found in most of its regions, and for each of those the `n_regions` regions carrying it with the
10
+ largest predicted difference between the conditions (the seqlet budget). Two sets x 5 motifs x 20 regions = up to
11
+ 200 regions (fewer when a region carries several of the motifs). The viewer says which regions have tracks.
12
+
13
+ The export's config has relative paths only, so the folder can be zipped, downloaded and opened as it is.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ import shutil
20
+ from pathlib import Path
21
+ from typing import List, Optional
22
+
23
+ import pandas as pd
24
+
25
+ from . import config as C
26
+
27
+ #: files and folders of the run directory the viewer reads, copied when present
28
+ RUN_FILES = ['seqlets', 'merged_seqlets', 'merge_map.npy', 'thresholds.csv', 'budgets.csv', 'seqlet_settings.json',
29
+ 'contrasts.json', 'cluster_summary.csv',
30
+ 'cluster_consensus', 'labels.npy',
31
+ 'jaspar_matches.json', 'families', 'report', 'run.json', 'pairs/cooccurrence.csv', 'marginalize',
32
+ 'regions.parquet', 'selection_null.parquet', 'view_cache']
33
+ #: the config sections the viewer reads, copied as they are (paths are rewritten separately)
34
+ KEEP_SECTIONS = ['seqlets', 'cluster', 'report', 'cooccurrence']
35
+
36
+
37
+ def select_regions(an, n_regions: int = 20, n_motifs: int = 5) -> pd.DataFrame:
38
+ """
39
+ The regions whose attributions the export keeps: per set, the n_motifs clusters in most of its regions and,
40
+ per cluster, the n_regions regions of the set carrying it with the largest budget. One row per (set, cluster,
41
+ region); a region picked for several clusters appears once per cluster.
42
+ """
43
+ from .view import data as V
44
+ mt = V.motif_table(an)
45
+ meta = V.seqlet_meta(an)
46
+ thr = an.thresholds
47
+ thr = thr[thr['contrast'] == an.contrast.name].drop_duplicates('coord').set_index('coord')
48
+ rows = []
49
+ for s in an.sets:
50
+ for c in mt.nlargest(n_motifs, f'n_{s}')['cluster'].astype(int):
51
+ coords = meta.loc[(meta['cluster'] == c) & (meta['set_name'] == s), 'coord'].unique()
52
+ budget = thr.reindex(coords)['budget'].dropna().sort_values(ascending=False).head(n_regions)
53
+ rows += [{'set_name': s, 'cluster': c, 'coord': k, 'budget': float(v), 'rank': r + 1}
54
+ for r, (k, v) in enumerate(budget.items())]
55
+ return pd.DataFrame(rows, columns=['set_name', 'cluster', 'coord', 'budget', 'rank'])
56
+
57
+
58
+ def _key(k: str) -> str:
59
+ return k if re.fullmatch(r'[A-Za-z0-9_-]+', k) else json.dumps(k)
60
+
61
+
62
+ def _toml(value) -> str:
63
+ if isinstance(value, bool):
64
+ return 'true' if value else 'false'
65
+ if isinstance(value, (int, float)):
66
+ return repr(value)
67
+ if isinstance(value, (list, tuple)):
68
+ return '[' + ', '.join(_toml(v) for v in value) + ']'
69
+ if isinstance(value, dict):
70
+ return '{ ' + ', '.join(f'{_key(k)} = {_toml(v)}' for k, v in value.items()) + ' }'
71
+ return json.dumps(str(value))
72
+
73
+
74
+ def write_toml(cfg: dict, path: Path) -> None:
75
+ """A config as TOML: one table per section, nested dicts as sub-tables after the section's own keys."""
76
+ lines = []
77
+
78
+ def table(name, d):
79
+ scalars = {k: v for k, v in d.items() if v is not None and not (isinstance(v, dict) and v and
80
+ all(isinstance(x, dict) for x in v.values()))}
81
+ subs = {k: v for k, v in d.items() if k not in scalars and v is not None}
82
+ lines.append(f'[{name}]')
83
+ lines.extend(f'{k} = {_toml(v)}' for k, v in scalars.items())
84
+ lines.append('')
85
+ for k, v in subs.items():
86
+ table(f'{name}.{k}', v)
87
+
88
+ for name, d in cfg.items():
89
+ if isinstance(d, dict):
90
+ table(name, d)
91
+ path.write_text('\n'.join(lines))
92
+
93
+
94
+ def export_config(an, selected: Optional[int]) -> dict:
95
+ """The export's config: the viewer's sections of the run config with every path relative to the export."""
96
+ cfg = an.cfg
97
+ out = {'run': {'name': cfg['run'].get('name', ''), 'out_dir': 'results', 'device': 'cpu'}}
98
+ out['attributions'] = {**{k: v for k, v in cfg['attributions'].items() if k != 'max_regions'}, 'root': 'attributions'}
99
+ out['contrasts'] = {name: {k: c[k] for k in ('a', 'b', 'label_a', 'label_b') if k in c}
100
+ for name, c in cfg['contrasts'].items()}
101
+ for s in KEEP_SECTIONS:
102
+ out[s] = {k: v for k, v in cfg.get(s, {}).items() if not str(k).startswith('_')}
103
+ out['jaspar'] = {k: v for k, v in cfg.get('jaspar', {}).items() if k not in ('meme', 'cache_dir')}
104
+ out['jaspar'].update(meme='jaspar.txt', cache_dir='.')
105
+ if 'marginalize' in cfg:
106
+ from .marginalize.cooperativity import settings_of
107
+ m = settings_of(cfg)
108
+ out['marginalize'] = {k: m[k] for k in ('prediction_space', 'real_space', 'bins', 'heatmap_sigma', 'seq_len')
109
+ if m.get(k) is not None}
110
+ out['marginalize'].update(store='results/marginalize/store', design='design.json')
111
+ if cfg.get('expression'):
112
+ from . import expression as X
113
+ out['expression'] = {'assign': 'stored', 'described': X.describe(cfg)}
114
+ out['export'] = {'source': cfg.get('_path', ''), 'n_regions_with_attributions': selected}
115
+ return out
116
+
117
+
118
+ def run(cfg: dict, out: Optional[str] = None, n_regions: int = 20, n_motifs: int = 5, log=print) -> Path:
119
+ """Write the export folder of a run and return its path."""
120
+ from .analysis import Analysis
121
+ from .view import data as V
122
+ an = Analysis(cfg['_path'])
123
+ missing = [f for f in ('seqlets/meta.parquet', 'cluster_summary.csv', 'jaspar_matches.json') if not (an.out / f).exists()]
124
+ if missing:
125
+ raise SystemExit(f'{an.out} is not a finished run (missing {", ".join(missing)}); run seqlets, cluster and families first')
126
+ from . import calibrate as CAL
127
+ if CAL.needs_settings(an.cfg):
128
+ raise SystemExit(CAL.missing_message(an.cfg, Path(cfg['_path']).name))
129
+ dst = Path(out) if out else Path(cfg['_path']).parent / f"export_{cfg['run'].get('name') or 'run'}"
130
+ if dst.exists():
131
+ raise SystemExit(f'{dst} exists; remove it or give --out')
132
+ res = dst / 'results'
133
+ for f in RUN_FILES:
134
+ src = an.out / f
135
+ if src.is_dir():
136
+ shutil.copytree(src, res / f, ignore=shutil.ignore_patterns('*.pdf', 'store'))
137
+ elif src.exists():
138
+ (res / f).parent.mkdir(parents=True, exist_ok=True)
139
+ shutil.copy2(src, res / f)
140
+ shutil.copy2(cfg['jaspar']['meme'], dst / 'jaspar.txt')
141
+ if 'marginalize' in cfg and V.coop_dir(an) is not None:
142
+ an.design.save(dst / 'design.json')
143
+ (res / 'marginalize' / 'store').mkdir(parents=True, exist_ok=True)
144
+ shutil.copy2(an.store.path / 'store.json', res / 'marginalize' / 'store' / 'store.json')
145
+
146
+ if an.region_table is not None and not (res / 'regions.parquet').exists():
147
+ an.region_table.to_parquet(res / 'regions.parquet') # the candidates' values, without the attributions beside them
148
+ if an.expression_table is not None: # the table and the links, whichever way they were made
149
+ an.expression_table.to_parquet(res / 'expression.parquet')
150
+ an.region_genes.to_parquet(res / 'region_genes.parquet')
151
+ picked = select_regions(an, n_regions, n_motifs)
152
+ picked.to_csv(dst / 'attributions_kept.csv', index=False)
153
+ src_root, n_files = Path(cfg['attributions']['root']), 0
154
+ for coord in picked['coord'].unique():
155
+ try:
156
+ p = an.source.path_for(coord)
157
+ except KeyError:
158
+ log(f'[export] no attribution file for {coord}')
159
+ continue
160
+ target = dst / 'attributions' / p.relative_to(src_root)
161
+ target.parent.mkdir(parents=True, exist_ok=True)
162
+ shutil.copy2(p, target)
163
+ n_files += 1
164
+ write_toml(export_config(an, n_files), dst / 'config.toml')
165
+ (dst / 'README.txt').write_text(README.format(name=cfg['run'].get('name', ''), n=n_files, n_motifs=n_motifs,
166
+ n_regions=n_regions, sets=', '.join(an.sets)))
167
+ C.load(dst / 'config.toml') # the config must read back
168
+ size = sum(f.stat().st_size for f in dst.rglob('*') if f.is_file()) / 1e6
169
+ log(f'[export] {dst}: {size:.0f} MB, attributions of {n_files} regions '
170
+ f'({n_motifs} motifs x {n_regions} regions per set; {len(picked)} picks, some regions shared)')
171
+ return dst
172
+
173
+
174
+ README = '''diffgrammar run "{name}", exported for viewing.
175
+
176
+ Open it: diffgrammar view (in this folder; prints the address to open)
177
+ Install: see "Viewer" in the diffgrammar README; no GPU and no model are needed.
178
+
179
+ results/ the tables of every step (seqlets, clusters, JASPAR matches, report, cooperativity)
180
+ attributions/ the attributions of {n} regions: for each set ({sets}), the {n_motifs} motifs found in most
181
+ of its regions, and for each the {n_regions} regions carrying it with the largest predicted
182
+ difference (attributions_kept.csv lists them). Other regions open without tracks.
183
+ jaspar.txt the JASPAR matrices the motifs were matched against
184
+ config.toml what the viewer reads; every path is relative to this folder
185
+ '''
@@ -0,0 +1,399 @@
1
+ """
2
+ Differential expression next to the motifs, read from a [expression] section of the config.
3
+
4
+ [expression]
5
+ deseq2 = "data/DESeq2.tsv" # delimited text with a gene column, log2FoldChange, padj and baseMean
6
+ direction = "b_over_a" # or "a_over_b", when the table's fold change runs the other way
7
+
8
+ assign = "table" # how regions get their genes: "table" or "closest"
9
+ assignments = "data/abc.csv" # one row per link, by interval (chrom, start, end) or by region (coord)
10
+ assignment_columns = { chrom = "chr", gene = "TargetGene" } # only the names that differ from the defaults
11
+ assignment_filter = { class = "promoter" } # rows to keep: column = value or [values]
12
+
13
+ assign = "closest" # or: the gene whose TSS is nearest to the region's centre
14
+ genes = "data/genes.gtf.gz" # a GTF, or a table with chrom, tss, gene (gene_columns renames them)
15
+ max_distance = 100000 # optional, in bp
16
+
17
+ assign = "contacts" # or: genes in contact with the region, from Hi-C (or HiChIP, Micro-C) loops
18
+ contacts = "data/loops.bedpe" # one contact per row: chrom1, start1, end1, chrom2, start2, end2
19
+ genes = "data/genes.gtf.gz" # as for "closest": where each gene's TSS is
20
+ anchor_padding = 0 # optional, bp added to each side of every anchor
21
+ contact_min = { counts = 5 } # optional, rows to keep: column >= value (contact_max: column <= value)
22
+ fallback = "closest" # optional: regions with no gene by contact get the nearest one
23
+
24
+ A region gets a gene by contact when one anchor of a contact overlaps it and the gene's TSS lies in the other anchor, so
25
+ a contact list replaces the nearest-gene guess with the chromatin's own links. Every seqlet of a region shares the
26
+ region's genes; with anchors of a few kb, a seqlet and its region overlap the same anchors anyway. The list may have a
27
+ header (BEDPE-style or HiCCUPS names: chr1, x1, x2, chr2, y1, y2; contact_columns renames others) or none, when the first
28
+ six columns are read in BEDPE order and the rest are named col7, col8 (BEDPE's score). Chromosomes match with or without
29
+ 'chr', so a loop list or an Ensembl GTF naming them 1, 2, X meets regions named chr1; the genome build must match. A
30
+ binned matrix (.hic, .cool) is not a list: call loops from it first (HiCCUPS, cooltools dots, Mustache) or dump its
31
+ significant pixels as pairs.
32
+
33
+ Two readouts follow. Each motif's candidate TFs (`tf_members`): the TFs of its JASPAR matrices and the best matches of its
34
+ largest cluster, with their fold change. And the genes of the regions carrying a motif (`motif_targets`): their fold change,
35
+ each gene counted once per motif and set. The regions of all contrasts count. Two tests, each BH over the table and needing at least
36
+ 5 genes: against zero (two-sided Wilcoxon), whether those genes moved at all; and against the rest of the set (two-sided
37
+ Mann-Whitney), whether they moved differently from the set's other genes. A set's genes often move together (the row 'All regions'),
38
+ so the first mostly follows the set and the second is the one about the motif. A gene of both a motif's regions and other regions
39
+ counts with the motif. An assigned gene is a linkage, not evidence that the motif regulates it.
40
+
41
+ Gene names are compared without case, so a human JASPAR name finds its mouse symbol, and no other orthology is attempted.
42
+ """
43
+ from __future__ import annotations
44
+
45
+ import gzip
46
+ import re
47
+ from pathlib import Path
48
+ from typing import Dict, List, Optional, Sequence
49
+
50
+ import numpy as np
51
+ import pandas as pd
52
+
53
+ ALL_REGIONS = 'All regions'
54
+ GENE_COLUMNS = ('gene_name', 'gene', 'symbol', 'gene_symbol', 'gene_id', 'TargetGene', 'target_gene')
55
+
56
+
57
+ def settings(cfg: dict) -> Optional[dict]:
58
+ """The [expression] section, or None when the run has none."""
59
+ s = cfg.get('expression')
60
+ return s if s else None
61
+
62
+
63
+ def read_table(path, **kw) -> pd.DataFrame:
64
+ """A table in any delimited text (tab, comma or spaces), parquet, or xlsx when openpyxl is installed."""
65
+ path = Path(path)
66
+ name = path.name.lower()
67
+ if name.endswith('.parquet'):
68
+ return pd.read_parquet(path)
69
+ if name.endswith(('.xlsx', '.xls')):
70
+ try:
71
+ return pd.read_excel(path, **kw)
72
+ except ImportError as e:
73
+ raise SystemExit(f'{path} is an Excel file and this environment has no openpyxl: save it as CSV, or install openpyxl') from e
74
+ head = pd.read_csv(path, nrows=0, sep=None, engine='python', compression='infer') if name.endswith('.gz') else None
75
+ if head is None:
76
+ with open(path) as fh:
77
+ first = fh.readline()
78
+ sep = '\t' if '\t' in first else (',' if ',' in first else r'\s+')
79
+ else:
80
+ sep = '\t' if len(head.columns) > 1 and '\t' not in head.columns[0] and name.endswith(('.tsv.gz', '.txt.gz')) else ','
81
+ return pd.read_csv(path, sep=sep, **kw)
82
+
83
+
84
+ def _column(table: pd.DataFrame, given: Optional[str], candidates: Sequence[str], what: str) -> str:
85
+ if given:
86
+ if given not in table:
87
+ raise SystemExit(f'[expression] no column {given!r} for {what}; the table has {list(table.columns)[:12]}')
88
+ return given
89
+ found = next((c for c in candidates if c in table), None)
90
+ if found is None:
91
+ raise SystemExit(f'[expression] no column for {what} among {list(table.columns)[:12]}; name it in the config')
92
+ return found
93
+
94
+
95
+ def de_table(cfg: dict) -> Optional[pd.DataFrame]:
96
+ """gene, log2fc (of B over A), padj, base_mean: one row per gene, the first where a table repeats it. None without a table."""
97
+ s = settings(cfg)
98
+ if s is None:
99
+ return None
100
+ if s.get('assign') == 'stored':
101
+ return pd.read_parquet(Path(cfg['run']['out_dir']) / 'expression.parquet')
102
+ if not s.get('deseq2'):
103
+ return None
104
+ t = read_table(s['deseq2'])
105
+ names = s.get('columns', {})
106
+ first = t.columns[0] # a DESeq2 table written by R may keep its gene names as an unnamed first column
107
+ gene = names.get('gene') or next((c for c in GENE_COLUMNS if c in t), first)
108
+ lfc = _column(t, names.get('log2fc'), ('log2FoldChange', 'log2fc', 'logFC'), 'the log2 fold change')
109
+ padj = _column(t, names.get('padj'), ('padj', 'FDR', 'qvalue', 'q'), 'the adjusted p-value')
110
+ base = names.get('base') or next((c for c in ('baseMean', 'base_mean', 'AveExpr') if c in t), None)
111
+ sign = {'b_over_a': 1.0, 'a_over_b': -1.0}.get(s.get('direction', 'b_over_a'))
112
+ if sign is None:
113
+ raise SystemExit("[expression] direction must be 'b_over_a' or 'a_over_b'")
114
+ out = pd.DataFrame({'gene': t[gene].astype(str), 'log2fc': sign * pd.to_numeric(t[lfc], errors='coerce'),
115
+ 'padj': pd.to_numeric(t[padj], errors='coerce'),
116
+ 'base_mean': pd.to_numeric(t[base], errors='coerce') if base else np.nan})
117
+ return out.dropna(subset=['log2fc']).drop_duplicates('gene').reset_index(drop=True)
118
+
119
+
120
+ def _parse_coord(coord: str):
121
+ chrom, span = coord.split(':')
122
+ a, b = span.split('-')
123
+ return chrom, int(a), int(b)
124
+
125
+
126
+ def _filtered(t: pd.DataFrame, rules: dict) -> pd.DataFrame:
127
+ for col, want in (rules or {}).items():
128
+ if col not in t:
129
+ raise SystemExit(f'[expression] assignment_filter: no column {col!r}; the table has {list(t.columns)[:12]}')
130
+ t = t[t[col].astype(str).isin([str(v) for v in (want if isinstance(want, (list, tuple)) else [want])])]
131
+ return t
132
+
133
+
134
+ def _by_table(s: dict, coords: Sequence[str]) -> pd.DataFrame:
135
+ t = _filtered(read_table(s['assignments']), s.get('assignment_filter'))
136
+ names = s.get('assignment_columns', {})
137
+ gene = _column(t, names.get('gene'), GENE_COLUMNS, 'the gene of an assignment')
138
+ if names.get('coord') or ('coord' in t and not names.get('chrom')):
139
+ c = names.get('coord', 'coord')
140
+ return t.loc[t[c].isin(set(coords)), [c, gene]].set_axis(['coord', 'gene'], axis=1)
141
+ chrom = _column(t, names.get('chrom'), ('chrom', 'chr', 'seqnames'), 'the chromosome of an assignment')
142
+ start = _column(t, names.get('start'), ('start',), 'the start of an assignment')
143
+ end = _column(t, names.get('end'), ('end',), 'the end of an assignment')
144
+ rows = []
145
+ wanted = pd.DataFrame([(c, *_parse_coord(c)) for c in dict.fromkeys(coords)], columns=['coord', 'chrom', 'start', 'end'])
146
+ for ch, reg in wanted.groupby('chrom'):
147
+ g = t[t[chrom] == ch].sort_values(start)
148
+ if g.empty:
149
+ continue
150
+ lo, hi, genes = g[start].to_numpy(float), g[end].to_numpy(float), g[gene].astype(str).to_numpy()
151
+ longest = float((hi - lo).max())
152
+ for coord, a, b in zip(reg['coord'], reg['start'], reg['end']):
153
+ i, j = np.searchsorted(lo, a - longest), np.searchsorted(lo, b) # starts before the region's end
154
+ hit = i + np.flatnonzero(hi[i:j] > a)
155
+ rows.extend((coord, x) for x in dict.fromkeys(genes[hit]))
156
+ return pd.DataFrame(rows, columns=['coord', 'gene'])
157
+
158
+
159
+ def _tss_table(s: dict) -> pd.DataFrame:
160
+ path = str(s['genes'])
161
+ if re.search(r'\.gtf(\.gz)?$', path) or re.search(r'\.gff3?(\.gz)?$', path):
162
+ g = pd.read_csv(path, sep='\t', comment='#', header=None, usecols=[0, 2, 3, 4, 6, 8], names=['chrom', 'kind', 'a', 'b', 'strand', 'attr'])
163
+ for kind in ('gene', 'transcript'):
164
+ if (g['kind'] == kind).any():
165
+ g = g[g['kind'] == kind]
166
+ break
167
+ name = g['attr'].str.extract(r'gene_name[ =]"?([^";]+)')[0].fillna(g['attr'].str.extract(r'gene_id[ =]"?([^";]+)')[0])
168
+ return pd.DataFrame({'chrom': g['chrom'], 'tss': np.where(g['strand'] == '-', g['b'], g['a']), 'gene': name}).dropna()
169
+ t = read_table(path)
170
+ names = s.get('gene_columns', {})
171
+ out = pd.DataFrame({'chrom': t[_column(t, names.get('chrom'), ('chrom', 'chr'), 'the chromosome of a gene')],
172
+ 'tss': t[_column(t, names.get('tss'), ('tss', 'TSS', 'TargetGeneTSS'), 'the TSS of a gene')],
173
+ 'gene': t[_column(t, names.get('gene'), GENE_COLUMNS, 'the name of a gene')]})
174
+ return out.dropna().drop_duplicates()
175
+
176
+
177
+ def _by_closest(s: dict, coords: Sequence[str]) -> pd.DataFrame:
178
+ tss = _tss_table(s)
179
+ limit = s.get('max_distance')
180
+ rows = []
181
+ wanted = pd.DataFrame([(c, *_parse_coord(c)) for c in dict.fromkeys(coords)], columns=['coord', 'chrom', 'start', 'end'])
182
+ for ch, reg in wanted.groupby('chrom'):
183
+ g = tss[tss['chrom'] == ch].sort_values('tss')
184
+ if g.empty:
185
+ continue
186
+ pos, names = g['tss'].to_numpy(float), g['gene'].astype(str).to_numpy()
187
+ mid = (reg['start'].to_numpy() + reg['end'].to_numpy()) / 2
188
+ right = np.clip(np.searchsorted(pos, mid), 0, len(pos) - 1)
189
+ left = np.clip(right - 1, 0, len(pos) - 1)
190
+ nearest = np.where(np.abs(pos[left] - mid) <= np.abs(pos[right] - mid), left, right)
191
+ for coord, k, m in zip(reg['coord'], nearest, mid):
192
+ if limit is None or abs(pos[k] - m) <= limit:
193
+ rows.append((coord, names[k]))
194
+ return pd.DataFrame(rows, columns=['coord', 'gene'])
195
+
196
+
197
+ CONTACT_COLUMNS = {'chrom1': ('chrom1', 'chr1', '#chr1', 'chrom_1', 'chrA'), 'start1': ('start1', 'x1', 'start_1', 'startA'),
198
+ 'end1': ('end1', 'x2', 'end_1', 'endA'), 'chrom2': ('chrom2', 'chr2', 'chrom_2', 'chrB'),
199
+ 'start2': ('start2', 'y1', 'start_2', 'startB'), 'end2': ('end2', 'y2', 'end_2', 'endB')}
200
+
201
+
202
+ def read_contacts(s: dict) -> pd.DataFrame:
203
+ """chrom1, start1, end1, chrom2, start2, end2 of every contact kept by contact_min and contact_max."""
204
+ path = Path(s['contacts'])
205
+ with (gzip.open if path.name.endswith('.gz') else open)(path, 'rt') as fh:
206
+ first = next((line for line in fh if line.strip()), '')
207
+ fields = re.split(r'[\t,]|\s+', first.strip())
208
+ if len(fields) >= 6 and fields[1].lstrip('-').isdigit(): # no header: BEDPE order
209
+ t = read_table(path, header=None)
210
+ t.columns = list(CONTACT_COLUMNS) + [f'col{k + 1}' for k in range(6, t.shape[1])]
211
+ else:
212
+ t = read_table(path)
213
+ names = s.get('contact_columns', {})
214
+ t = t.rename(columns={_column(t, names.get(k), alts, f'{k} of a contact'): k for k, alts in CONTACT_COLUMNS.items()})
215
+ for key, keep in (('contact_min', lambda v, x: v >= x), ('contact_max', lambda v, x: v <= x)):
216
+ for col, x in (s.get(key) or {}).items():
217
+ if col not in t:
218
+ raise SystemExit(f'[expression] {key}: no column {col!r}; the contacts have {list(t.columns)[:12]}')
219
+ t = t[keep(pd.to_numeric(t[col], errors='coerce'), float(x))]
220
+ t = t.dropna(subset=list(CONTACT_COLUMNS))
221
+ for k in ('start1', 'end1', 'start2', 'end2'):
222
+ t[k] = t[k].astype(np.int64)
223
+ return t[list(CONTACT_COLUMNS)].astype({'chrom1': str, 'chrom2': str}).reset_index(drop=True)
224
+
225
+
226
+ def _by_contacts(s: dict, coords: Sequence[str]) -> pd.DataFrame:
227
+ c = read_contacts(s)
228
+ pad = int(s.get('anchor_padding') or 0)
229
+ key = np.vectorize(lambda ch: str(ch).removeprefix('chr'), otypes=[object]) # 'chr1' and '1' name one chromosome
230
+ # every contact both ways: the anchor that may overlap a region, and the anchor whose genes the region then gets
231
+ near = pd.DataFrame({'chrom': key(np.r_[c['chrom1'], c['chrom2']]), 'start': np.r_[c['start1'], c['start2']] - pad,
232
+ 'end': np.r_[c['end1'], c['end2']] + pad, 'far_chrom': key(np.r_[c['chrom2'], c['chrom1']]),
233
+ 'far_start': np.r_[c['start2'], c['start1']] - pad, 'far_end': np.r_[c['end2'], c['end1']] + pad})
234
+ tss = {key(ch).item(): (g['tss'].to_numpy(float)[o], g['gene'].astype(str).to_numpy()[o])
235
+ for ch, g in _tss_table(s).groupby('chrom') for o in [np.argsort(g['tss'].to_numpy(float))]}
236
+ rows = []
237
+ wanted = pd.DataFrame([(x, *_parse_coord(x)) for x in dict.fromkeys(coords)], columns=['coord', 'chrom', 'start', 'end'])
238
+ for ch, reg in wanted.groupby('chrom'):
239
+ g = near[near['chrom'] == key(ch).item()].sort_values('start')
240
+ if g.empty:
241
+ continue
242
+ lo, hi = g['start'].to_numpy(float), g['end'].to_numpy(float)
243
+ far = g[['far_chrom', 'far_start', 'far_end']].to_numpy(object)
244
+ longest = float((hi - lo).max())
245
+ for coord, a, b in zip(reg['coord'], reg['start'], reg['end']):
246
+ i, j = np.searchsorted(lo, a - longest), np.searchsorted(lo, b) # anchors starting before the region ends
247
+ for k in i + np.flatnonzero(hi[i:j] > a):
248
+ fc, fs, fe = far[k]
249
+ if fc in tss:
250
+ pos, names = tss[fc]
251
+ rows.extend((coord, x) for x in names[np.searchsorted(pos, fs):np.searchsorted(pos, fe, side='right')])
252
+ out = pd.DataFrame(rows, columns=['coord', 'gene']).drop_duplicates(ignore_index=True)
253
+ if s.get('fallback') == 'closest':
254
+ rest = [x for x in dict.fromkeys(coords) if x not in set(out['coord'])]
255
+ out = pd.concat([out, _by_closest(s, rest)], ignore_index=True)
256
+ elif s.get('fallback') not in (None, 'none'):
257
+ raise SystemExit(f'[expression] fallback must be "closest" or "none", got {s.get("fallback")!r}')
258
+ return out
259
+
260
+
261
+ def gene_tss(cfg: dict) -> Optional[pd.DataFrame]:
262
+ """chrom, tss, gene from [expression] genes (a GTF or a table), or None when the run names no gene positions."""
263
+ s = settings(cfg)
264
+ if not s or not s.get('genes'):
265
+ return None
266
+ return _tss_table(s)
267
+
268
+
269
+ def assign_genes(cfg: dict, coords: Sequence[str]) -> pd.DataFrame:
270
+ """coord, gene: the genes of these regions under the config's rule; a region has none, one or several."""
271
+ s = settings(cfg)
272
+ if s is None:
273
+ return pd.DataFrame(columns=['coord', 'gene'])
274
+ how = s.get('assign', 'closest')
275
+ if how == 'stored':
276
+ return pd.read_parquet(Path(cfg['run']['out_dir']) / 'region_genes.parquet')
277
+ if how == 'table':
278
+ if not s.get('assignments'):
279
+ raise SystemExit('[expression] assign = "table" needs `assignments`, a table of region-to-gene links')
280
+ return _by_table(s, coords)
281
+ if how == 'closest':
282
+ if not s.get('genes'):
283
+ raise SystemExit('[expression] assign = "closest" needs `genes`, a GTF or a table of TSS positions')
284
+ return _by_closest(s, coords)
285
+ if how == 'contacts':
286
+ if not s.get('contacts'):
287
+ raise SystemExit('[expression] assign = "contacts" needs `contacts`, a list of contacts (BEDPE or loops)')
288
+ if not s.get('genes'):
289
+ raise SystemExit('[expression] assign = "contacts" needs `genes`, a GTF or a table of TSS positions')
290
+ return _by_contacts(s, coords)
291
+ raise SystemExit(f'[expression] assign must be "closest", "table" or "contacts", got {how!r}')
292
+
293
+
294
+ def describe(cfg: dict) -> str:
295
+ """The assignment rule in words, for captions."""
296
+ s = settings(cfg) or {}
297
+ how = s.get('assign', 'closest')
298
+ if how == 'table':
299
+ rules = '; '.join(f'{k} = {v}' for k, v in (s.get('assignment_filter') or {}).items())
300
+ return f"genes linked in {Path(str(s.get('assignments'))).name}" + (f' ({rules})' if rules else '')
301
+ if how == 'closest':
302
+ lim = s.get('max_distance')
303
+ return 'the gene with the nearest TSS' + (f' within {int(lim):,} bp' if lim else '')
304
+ if how == 'contacts':
305
+ pad = int(s.get('anchor_padding') or 0)
306
+ text = (f"genes whose TSS lies in the other anchor of a contact in {Path(str(s.get('contacts'))).name}"
307
+ + (f' (anchors padded by {pad:,} bp)' if pad else ''))
308
+ return text + ('; for regions without one, the gene with the nearest TSS' if s.get('fallback') == 'closest' else '')
309
+ return s.get('described', 'the assignments stored with this run')
310
+
311
+
312
+ def _key_upper(de: pd.DataFrame) -> Dict[str, str]:
313
+ return {g.upper(): g for g in reversed(de['gene'].tolist())}
314
+
315
+
316
+ def _names(motif_matrices: Sequence[str], hits: Sequence[str]) -> List[str]:
317
+ """A dimer's partner counts when it also has its own matrix in the family; all partners of the best matches count."""
318
+ mono = {n.upper() for n in motif_matrices if '::' not in n}
319
+ out = [part for n in motif_matrices for part in n.split('::') if '::' not in n or part.upper() in mono]
320
+ return out + [part for h in hits for part in h.split('::')]
321
+
322
+
323
+ def tf_members(de: pd.DataFrame, annotations: pd.DataFrame, families: pd.DataFrame, hits: Dict[int, list], level: str,
324
+ motifs: Sequence[str], n_hits: int = 3) -> Dict[str, pd.DataFrame]:
325
+ """motif -> its candidate TFs found in the table with an adjusted p-value: gene, log2fc, padj, base_mean."""
326
+ upper = _key_upper(de)
327
+ rows = de.set_index('gene')
328
+ biggest = families.sort_values('n_seqlets', ascending=False).drop_duplicates(level).set_index(level)['cluster']
329
+ out = {}
330
+ for m in motifs:
331
+ best = hits.get(int(biggest[m]), [])[:n_hits] if m in biggest.index else []
332
+ names = _names(annotations.loc[annotations[level] == m, 'name'].astype(str).tolist(), [h['tf'] for h in best])
333
+ genes = [g for g in dict.fromkeys(upper.get(n.upper()) for n in names) if g is not None]
334
+ got = rows.loc[genes].reset_index() if genes else rows.iloc[:0].reset_index()
335
+ out[m] = got[got['padj'].notna()].reset_index(drop=True)
336
+ return out
337
+
338
+
339
+ def target_values(de: pd.DataFrame, links: pd.DataFrame, coords) -> np.ndarray:
340
+ """The fold changes of the genes of these regions, each gene once."""
341
+ genes = links.loc[links['coord'].isin(set(coords)), 'gene'].unique()
342
+ return de.loc[de['gene'].isin(genes), 'log2fc'].to_numpy(float)
343
+
344
+
345
+ def wilcoxon_p(values: np.ndarray, min_n: int = 5) -> float:
346
+ if len(values) < min_n or not np.any(values):
347
+ return np.nan
348
+ from scipy.stats import wilcoxon
349
+ return float(wilcoxon(values).pvalue)
350
+
351
+
352
+ def rest_test(values: np.ndarray, rest: np.ndarray, min_n: int = 5) -> float:
353
+ """Two-sided Mann-Whitney of a motif's genes against the set's other genes; NaN below min_n in either group."""
354
+ if len(values) < min_n or len(rest) < min_n:
355
+ return np.nan
356
+ from scipy.stats import mannwhitneyu
357
+ return float(mannwhitneyu(values, rest, alternative='two-sided').pvalue)
358
+
359
+
360
+ def motif_targets(an, level: str, motifs: Sequence[str], sets: Sequence[str]) -> tuple:
361
+ """
362
+ (table, values): per motif and set, and for 'All regions' of each set, the fold changes of the genes of the regions
363
+ carrying it. table: motif, set_name, regions, genes, median, p and q against zero, rest_genes, rest_median, p_rest and
364
+ q_rest against the set's other genes. values maps (motif, set) -> array.
365
+ """
366
+ from .attribute import _bh
367
+ from . import summaries as S
368
+ de, links = an.expression_table, an.region_genes
369
+ lab = S.label_seqlets(an.seqlets.meta, an.families, min_cluster_size=an.cfg['report']['min_cluster_size'])
370
+ rows, values = [], {}
371
+ for s in sets:
372
+ in_set = lab[lab['set_name'] == s]
373
+ for m in [ALL_REGIONS, *motifs]:
374
+ coords = in_set['coord'].unique() if m == ALL_REGIONS else in_set.loc[in_set[level] == m, 'coord'].unique()
375
+ v = target_values(de, links, coords)
376
+ values[(m, s)] = v
377
+ row = {'motif': m, 'set_name': s, 'regions': len(coords), 'genes': len(v), 'median': float(np.median(v)) if len(v) else np.nan,
378
+ 'p': wilcoxon_p(v), 'rest_genes': 0, 'rest_median': np.nan, 'p_rest': np.nan}
379
+ if m != ALL_REGIONS:
380
+ mine = set(links.loc[links['coord'].isin(set(coords)), 'gene'])
381
+ others = set(links.loc[links['coord'].isin(set(in_set['coord'])), 'gene']) - mine
382
+ rest = de.loc[de['gene'].isin(others), 'log2fc'].to_numpy(float)
383
+ row.update(rest_genes=len(rest), rest_median=float(np.median(rest)) if len(rest) else np.nan, p_rest=rest_test(v, rest))
384
+ rows.append(row)
385
+ t = pd.DataFrame(rows)
386
+ tested = t['motif'] != ALL_REGIONS
387
+ t['q'], t['q_rest'] = np.nan, np.nan
388
+ t.loc[tested, 'q'] = _bh(t.loc[tested, 'p'].to_numpy())
389
+ t.loc[tested, 'q_rest'] = _bh(t.loc[tested, 'p_rest'].to_numpy())
390
+ return t[['motif', 'set_name', 'regions', 'genes', 'median', 'p', 'q', 'rest_genes', 'rest_median', 'p_rest', 'q_rest']], values
391
+
392
+
393
+ def region_lfc(an) -> pd.DataFrame:
394
+ """coord, gene_lfc (the mean fold change of its genes in the table), genes: what a region can be coloured by."""
395
+ de, links = an.expression_table, an.region_genes
396
+ if de is None or links is None or links.empty:
397
+ return pd.DataFrame(columns=['coord', 'gene_lfc', 'genes'])
398
+ m = links.merge(de[['gene', 'log2fc']], on='gene')
399
+ return m.groupby('coord').agg(gene_lfc=('log2fc', 'mean'), genes=('gene', lambda g: ', '.join(dict.fromkeys(g)))).reset_index()