ebin 1.0__tar.gz → 1.0.2__tar.gz

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.
@@ -1,3 +1,17 @@
1
+ Metadata-Version: 2.4
2
+ Name: ebin
3
+ Version: 1.0.2
4
+ Summary: Posterior bin-expectation normalization for sorting-based MPRA
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: jax>=0.4
8
+ Requires-Dist: numpy
9
+ Requires-Dist: scipy
10
+ Requires-Dist: pandas
11
+ Provides-Extra: netcdf
12
+ Requires-Dist: xarray; extra == "netcdf"
13
+ Requires-Dist: h5netcdf; extra == "netcdf"
14
+
1
15
  # EBin: Normalization of MPRA data (FACS bins × replicates × sequences)
2
16
 
3
17
  Raw per-bin read counts are turned into one number per sequence per cell line —
@@ -227,61 +241,6 @@ coherent with the fitted model. A flat effect location is obtained with
227
241
  per-sequence target (for instance the same sequence's consensus across cell
228
242
  lines).
229
243
 
230
- ## Reproducing the shipped tables
231
-
232
- The shipped `activity_zi_full.csv` (30k sequences × 20 cell lines) is the
233
- default configuration:
234
-
235
- ```bash
236
- python -m ebin data.csv -o activity.csv --save-fits fits.pkl
237
- ```
238
-
239
- Cell lines come out in the order they appear in the count table, and every field
240
- is written. The shipped table carried only `activity, activity_sd,
241
- activity_map, tot` in an explicit cell-line order, so
242
-
243
- ```bash
244
- python -m ebin data.csv -o activity.csv \
245
- --fields activity,activity_sd,activity_map,tot --groups A549,HepG2,MCF7,...
246
- ```
247
-
248
- reproduces that exact layout. The extra columns are additional output, not a
249
- change to the numbers.
250
-
251
- Checked against the shipped table three ways:
252
-
253
- * **Readout.** Given the shipped fitted parameters, `readout_table` reproduces
254
- `activity`, `activity_sd`, `activity_map` and `tot` to `4e-16` — exact up to
255
- CSV round-off.
256
- * **Objective.** The log-likelihood and its gradient agree **bit for bit** with
257
- the original implementation at the same parameter point, for zero inflation
258
- and zero truncation, free and Gamma abundance — including the gradient
259
- through the implicit cut-point solve.
260
- * **Full refit.** Most cell lines land on the shipped optimum (`max|Δ|` on
261
- activity ≤ 1e-6). A few of the hardest lines do not: the objective is
262
- multi-modal there, and the optimizer can settle in a neighbouring basin,
263
- which moves individual sequences by up to ~1e-1 (Pearson r ≥ 0.9998 against
264
- the shipped column). This is a property of the problem, not of the
265
- repackaging — the original code has the same instability on the same lines
266
- (re-fitting HCT116 with it lands 13 nats from its own shipped value), and
267
- both implementations reproduce those lines when fitted on their own.
268
-
269
- The external-library (lib2) target used the same fit with a smaller readout
270
- grid, selected with `--grid 61x25`.
271
-
272
- The Gamma-abundance variant was warm-started from the shipped fits, which is
273
- what makes it affordable, and used a shorter finishing schedule:
274
-
275
- ```python
276
- from ebin import activity_table
277
- activity_table("data.csv", out="activity_gamma.csv", warm_from="fits.pkl",
278
- abundance=False, abundance_prior="gamma", n_abund_nodes=30,
279
- max_outer=1, finish_maxiter=2000, finish_rounds=4)
280
- ```
281
-
282
- The CLI runs the same variant on the default schedule:
283
- `--abundance gamma --nodes 30 --warm-from fits.pkl`.
284
-
285
244
  ## Runtime
286
245
 
287
246
  One cell line of 30k sequences × 4 bins takes ~2–4 min on a GPU (fit + readout)
ebin-1.0.2/README.md ADDED
@@ -0,0 +1,261 @@
1
+ # EBin: Normalization of MPRA data (FACS bins × replicates × sequences)
2
+
3
+ Raw per-bin read counts are turned into one number per sequence per cell line —
4
+ the **posterior-mean expected bin**, `E[bin]` — together with the posterior SD
5
+ that states how far it can be trusted. The counts enter a compound NB–Poisson
6
+ likelihood; what is estimated is the sequence's latent expression distribution.
7
+
8
+
9
+
10
+ <img src="http://data.georgy.top/media/ebin_model_layers.png" alt="EBin model"/>
11
+
12
+
13
+ ```MPRA
14
+ X[n,s,b] | T[n,s,b] ~ NB(R[s,b] · T[n,s,b], P[s,b]) reads from cells
15
+ T[n,s,b] ~ Poisson(a_n · Pi[n,b] · lambda_s) cells in bin b
16
+ Pi[n,b] = Phi((q_b − mu_n)/sigma_n) − Phi((q_{b−1} − mu_n)/sigma_n)
17
+ ```
18
+ Each sequence `n` carries a latent Gaussian effect law `N(mu_n, sigma_n²)` — its
19
+ expression distribution over cells — and an abundance `a_n`. The library's
20
+ marginal effect law is the **`N`-component mixture** of those per-sequence
21
+ normals, `G(x) = Σ_n w_n Phi((x − mu_n)/sigma_n)` with `w_n = 1/N`, and the `B`
22
+ sorting bins are its quantile cells: the cut points `q_1 < … < q_{B−1}` solve
23
+ `G(q_j) = j/B`. They are shared, and re-solved at every step, so every sequence
24
+ is tied to the marginal through them. This approach has 2 benefits: first one is that
25
+ it allows us to cut the number of params down to 2 instead of `B-1`, and the second one is that those params are further regularized, both by the normality assumption and the fact that they are all should form the global marginal distribution.
26
+
27
+ The activity that ships is the posterior **mean** of `E[bin] = Σ_b b·Pi[n,b]`,
28
+ integrated over the posterior of `(mu_n, sigma_n)` with the abundance profiled
29
+ per grid point. The plug-in point estimate is a posterior *mode*, and for a
30
+ low-count sequence the mode sits at a simplex vertex — activity exactly 1 or
31
+ `B`, regardless of depth.
32
+
33
+ ## Install
34
+ ```
35
+ pip install ebin
36
+ ```
37
+ or
38
+
39
+ ```bash
40
+ pip install -e /path/to/package # or place this directory on PYTHONPATH
41
+ ```
42
+
43
+ `jax` (GPU-version strongly recommended: `pip install jax[cuda]`), `numpy`, `scipy` and `pandas` are required.
44
+ `xarray` + `h5netcdf` are needed only for the netCDF export and `matplotlib`
45
+ only for the diagnostics. Everything runs in float64 as some parts of the algorithm require high precision, namely the tridiagonal eigenvalue solver for orthogonal polynomials.
46
+
47
+ ## Input
48
+
49
+ One row per sequence, a 3-level column header `(cell line, replicate, bin)`:
50
+
51
+ ```
52
+ seq, A549,A549,A549,A549,A549,...
53
+ rep1,rep1,rep1,rep1,rep2,...
54
+ bin1,bin2,bin3,bin4,bin1,...
55
+ ACGT..., 112, 340, 88, 15, 97, ...
56
+ ```
57
+ (in other words, the tabular should be readable with `pd.read_csv(..., header=[0,1,2])`)
58
+
59
+
60
+ Bins are ordered by the number in their name. Cell lines are fitted
61
+ independently. **Empty fields are read as zero counts, not as missing data** —
62
+ some exports write every zero as a blank, and treating those as missin
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install -e /path/to/package # or place this directory on PYTHONPATH
68
+ ```
69
+
70
+ `jax` (GPU strongly recommended), `numpy`, `scipy` and `pandas` are required.
71
+ `xarray` + `h5netcdf` are needed only for the netCDF export and `matplotlib`
72
+ only for the diagnostics. Everything runs in float64.
73
+
74
+ ## Input
75
+
76
+ One row per sequence, a 3-level column header `(cell line, replicate, bin)`:
77
+
78
+ ```
79
+ seq, A549,A549,A549,A549,A549,...
80
+ rep1,rep1,rep1,rep1,rep2,...
81
+ bin1,bin2,bin3,bin4,bin1,...
82
+ ACGT..., 112, 340, 88, 15, 97, ...
83
+ ```
84
+
85
+ Bins are ordered by the number in their name. Cell lines are fitted
86
+ independently. **Empty fields are read as zero counts, not as missing data** —
87
+ some exports write every zero as a blank, and treating those as missing deletes
88
+ the informative zeros of the low-abundance sequences.
89
+
90
+ ## Use
91
+
92
+ ```bash
93
+ python -m ebin counts.csv -o activity.csv
94
+ ```
95
+
96
+ ```python
97
+ from ebin import activity_table
98
+
99
+ table, results = activity_table("counts.csv", out="activity.csv")
100
+ table[("A549", "activity")] # posterior-mean E[bin] per sequence
101
+ ```
102
+
103
+ The CSV has two header rows, `(cell line, field)`, one row per sequence, and
104
+ carries everything the model estimates per sequence:
105
+
106
+ | field | meaning |
107
+ | --- | --- |
108
+ | `activity` | posterior-mean `E[bin]` — the normalized value intended for downstream use |
109
+ | `activity_sd` | its posterior SD — per-sequence confidence |
110
+ | `activity_map` | plug-in mode, kept for reference only |
111
+ | `mu`, `mu_sd` | posterior-mean effect location and its standard error |
112
+ | `sigma`, `sigma_sd` | posterior-mean effect scale and its standard error |
113
+ | `abundance` | fitted size factor `a_n` |
114
+ | `n_eff` | posterior grid support — large means the estimate is diffuse |
115
+ | `tot` | total observed reads |
116
+
117
+ All of it comes from the same posterior weights, so the columns are mutually
118
+ consistent: `activity` is `Σ_b b·bin_prob`. `mu` and `sigma` are in gauge units
119
+ (median cut 0, first cut −1), so they are comparable across sequences within a
120
+ cell line. A subset is selected with `--fields activity,activity_sd,tot` (or
121
+ `fields=[...]` in the API).
122
+
123
+ The `B−1` cut points are a property of the cell line, not of a sequence, so
124
+ they are not columns: `cuts_table(results)` returns them as one row per cell
125
+ line, and the CLI writes them next to the activity table as
126
+ `<out>_cuts.csv`. The gauge fixes the first two at −1 and 0, so what varies
127
+ between lines is where the upper cuts land (A549 0.990, MDA-MB-231 0.964).
128
+
129
+ Sequences with no reads at all in a cell line keep an activity (they are fitted
130
+ as structural zeros and land near the neutral prior mean, ~2.5 for `B = 4`);
131
+ sequences with no observed cell at all are `NaN`.
132
+
133
+ Useful CLI options:
134
+
135
+ ```
136
+ --groups A549,HepG2 cell lines to run, in output order
137
+ --abundance gamma integrate a_n out instead of fitting it
138
+ --zero-truncation drop all-zero rows instead of fitting them
139
+ --grid 61x25 readout grid (n_mu x n_log_sigma)
140
+ --save-fits fits.pkl keep the fitted parameters
141
+ --warm-from fits.pkl start from an earlier fit of the same data
142
+ --netcdf activity.nc also write the full posterior (see below)
143
+ --plots DIR also write the diagnostic plots
144
+ ```
145
+
146
+ ### Per-bin distribution
147
+
148
+ The one field too wide for a flat table is `bin_prob`, the posterior-mean
149
+ probability of each bin — an `(N, B)` array per cell line. It is returned in
150
+ `results`, and `--netcdf` writes it alongside every scalar field:
151
+
152
+ ```python
153
+ from ebin import activity_table, write_netcdf
154
+
155
+ table, results = activity_table("counts.csv")
156
+ results["A549"]["bin_prob"] # (N, B), rows sum to 1
157
+ write_netcdf("activity.nc", results, table.index)
158
+ ```
159
+
160
+ Readouts can be redone from saved fits without refitting, which is the cheap
161
+ way to try a different grid or prior:
162
+
163
+ ```python
164
+ from ebin import readout_table
165
+ table, results = readout_table("counts.csv", "fits.pkl")
166
+ ```
167
+
168
+ ## Diagnostics
169
+
170
+ Three plots, one panel per cell line, drawn from the table alone (`--plots DIR`
171
+ on the CLI writes all three):
172
+
173
+ ```python
174
+ from ebin import (plot_marginal_distribution, plot_activity_vs_raw,
175
+ plot_gc_vs_abundance)
176
+
177
+ plot_marginal_distribution(table, out="marginal.png")
178
+ plot_activity_vs_raw(table, "counts.csv", out="vs_raw.png")
179
+ plot_gc_vs_abundance(table, out="gc.png")
180
+ ```
181
+
182
+ **`plot_marginal_distribution`** — the marginal effect law: the `N`-component
183
+ mixture `G(x) = Σ_n w_n Phi((x − mu_n)/sigma_n)`, one normal per sequence,
184
+ drawn as the density it defines and sliced into the sorting bins, each in its
185
+ own colour. The x ticks are the cut points with their values. Weights are
186
+ uniform by default, as in the fit; `weights=` takes a per-sequence weight (the
187
+ fitted abundances, say) to see the marginal over cells rather than over
188
+ sequences. Every slice holds exactly `1/B` of the mass by construction, so the
189
+ gauge (cuts at −1 and 0) and any unusual tightness or skew in a cell line's
190
+ effect law are visible here.
191
+
192
+ **`plot_activity_vs_raw`** — fitted activity against the depth-normalized raw
193
+ mass centre (each replicate×bin column divided by its own library size, then
194
+ `Σ_b b·p_b`), coloured by fitted abundance. Well-measured sequences sit on the
195
+ diagonal; the horizontal band at the centre is the low-abundance tail, where the
196
+ raw estimate is noise and the model shrinks toward neutral. A cell line whose
197
+ *high*-abundance sequences leave the diagonal is a real warning sign.
198
+
199
+ **`plot_gc_vs_abundance`** — GC content against the fitted size factor, with the
200
+ binned median trend. A strong trend means `a_n` is absorbing a
201
+ cloning/sequencing bias rather than biological abundance alone. GC is taken from
202
+ the table index when the index is the sequence; otherwise it is supplied through
203
+ `sequences=`.
204
+
205
+ `raw_mass_center(counts)` and `gc_content(seqs)` are exported separately for
206
+ cases where the raw numbers are more appropriate than a picture.
207
+
208
+ ## Configuration
209
+
210
+ Defaults are the shipped configuration; they are not arbitrary and are worth
211
+ understanding before they are changed.
212
+
213
+ | option | default | why |
214
+ | --- | --- | --- |
215
+ | `conditional` | `False` | Zero **inflation**: all-zero rows are fitted with a structural-zero probability `phi`, so they enter the mixture that sets the cuts. Zero **truncation** (`True`) drops them, which sets the cuts on a zero-excluded distribution — measurably worse, both in-library and on transfer to an independent library. |
216
+ | `abundance` | `True` | A free size factor `a_n` per sequence. Without one, every sequence has the same expected latent total, so real depth variation has nowhere to go but `Pi` — which tilts toward the bins with the largest channel scale, and `Pi` stops being a profile. |
217
+ | `abundance_prior` | `None` | `'gamma'` integrates `a_n` out under `Gamma(kappa, mean=1)` instead: 2 parameters per sequence instead of 3, low-count sequences regularized, and the abundance uncertainty propagated into the effect. The activity profile is essentially unchanged (ρ ≈ 0.9996 against free `a_n`), so this is a parameter-economy. Costs ~2× runtime. |
218
+ | `mu_prior` | `1.3` | SD of the prior on the effect location. Bounding the effect *spread* alone still lets a single-bin low-count sequence run `mu_n` large and walk `Pi` to a vertex. The gauge pins Q50 = 0 and Q25 = −1, so the population SD is ≈ 1.5 and the between-sequence SD ≈ 1.1 — the gauge-consistent `tau` is ~1.3. A larger value (2–3) is inconsistent with the gauge and under-regularizes. |
219
+ | `sigma_prior` | `(0.0, 0.5)` | Prior on `log sigma_n`. The per-sequence MLE is unbounded: a sequence whose reads land only in the outer bins wants a two-point mass, reachable only as `sigma → ∞`. Without this, `sigma` hits its bound in several cell lines; those are bad optima, so the prior often *improves* the data likelihood. `(0, 1)` fits marginally better on well-behaved lines but leaves stuck ones stuck. |
220
+ | `lambda_fix` | `50.0` | The latent Poisson level is not identified upward — it rides the `R·lambda` ridge, and only products like `R(1−P)/P · Pi · lambda` are identified. It is held fixed and `R` absorbs the scale. |
221
+ | `a_max` | `15.0` | Bound on `a_n`; also sizes the truncated latent-count grid, so raising it costs runtime and memory. |
222
+ | readout grid | `121 × 33` | `(mu, log sigma)` grid for the posterior mean. Converged in the bulk: doubling to `181 × 49` moves the median activity by 2e-6 (a handful of extreme low-count sequences move by up to 0.04), while halving to `61 × 25` moves it by 5e-3. |
223
+
224
+ The readout re-uses the fit's own priors by default, so the posterior mean is
225
+ coherent with the fitted model. A flat effect location is obtained with
226
+ `readout=dict(tau_within=None)`, and `mu_center=<array>` shrinks toward a
227
+ per-sequence target (for instance the same sequence's consensus across cell
228
+ lines).
229
+
230
+ ## Runtime
231
+
232
+ One cell line of 30k sequences × 4 bins takes ~2–4 min on a GPU (fit + readout)
233
+ and roughly 20× longer on CPU; the Gamma-abundance variant costs ~2× the
234
+ free-`a_n` fit. Memory is dominated by the latent-count grid
235
+ (`a_max · lambda_fix` wide); the likelihood scans over abundance/rate components
236
+ so only one is live at a time. `XLA_PYTHON_CLIENT_PREALLOCATE=false` is set on
237
+ import so JAX does not claim 75% of VRAM.
238
+
239
+
240
+ ## Parameters
241
+
242
+
243
+ | symbol | shape | role | what it is | example (A549) |
244
+ | --- | --- | --- | --- | --- |
245
+ | `X[n,s,b]` | N×S×B | observed | reads counted for sequence n in channel (s,b) | 1686 median total |
246
+ | `T[n,s,b]` | N×S×B | latent | cells of n that landed in bin b — never observed, summed out | ~63 cells |
247
+ | `mu_n`, `sigma_n` | N each | per sequence | the sequence's expression law over cells, in gauge units | σ median 1.46 |
248
+ | `a_n` | N | per sequence | size factor: how many cells n contributes at all. Geometric mean pinned to 1, capped at `a_max` | 1.42 median |
249
+ | `Pi[n,b]` | N×B | derived | bin profile, rows sum to 1. Not free — read off `(mu_n, sigma_n)` and the cuts | — |
250
+ | `q_j` | B−1 | shared | cut points = quantiles of the mixture `G` at `j/B`. Gauge pins `q_1 = −1`, `q_2 = 0` | −1, 0, 0.99 |
251
+ | `lambda_s` | S | fixed | cell level of replicate s. Not identified — rides the `R·lambda` ridge, so held fixed while `R` absorbs the scale | 50 |
252
+ | `R[s,b]` | S×B | per channel | NB size per latent cell: `R·T` is the shape of the read distribution | 12.7 11.4 11.6 20.1 |
253
+ | `P[s,b]` | S×B | per channel | NB probability. Small `P` = a noisier channel at the same depth | .33 .32 .31 .52 |
254
+ | `phi` | 1 | shared | probability a sequence is a structural zero (dropout, never a cell) | 8e−7 |
255
+ | `kappa` | 1 | optional | Gamma shape when `a_n` is integrated out instead of fitted; CV = 1/√κ | 0.9 (variant) |
256
+
257
+ so `X, T, R, P` are 3D arrays:
258
+ <center>
259
+ <img src="http://data.georgy.top/media/ebin_index_cube.png" alt="Index cube: n sequences, s replicates, b bins" width="196">
260
+ </center>
261
+
@@ -29,4 +29,4 @@ from .plots import (plot_marginal_distribution, plot_activity_vs_raw, # noqa: E
29
29
  plot_gc_vs_abundance, plot_all, raw_mass_center,
30
30
  gc_content, marginal_density)
31
31
 
32
- __version__ = "1.0"
32
+ __version__ = "1.0.2"
@@ -0,0 +1,275 @@
1
+ Metadata-Version: 2.4
2
+ Name: ebin
3
+ Version: 1.0.2
4
+ Summary: Posterior bin-expectation normalization for sorting-based MPRA
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: jax>=0.4
8
+ Requires-Dist: numpy
9
+ Requires-Dist: scipy
10
+ Requires-Dist: pandas
11
+ Provides-Extra: netcdf
12
+ Requires-Dist: xarray; extra == "netcdf"
13
+ Requires-Dist: h5netcdf; extra == "netcdf"
14
+
15
+ # EBin: Normalization of MPRA data (FACS bins × replicates × sequences)
16
+
17
+ Raw per-bin read counts are turned into one number per sequence per cell line —
18
+ the **posterior-mean expected bin**, `E[bin]` — together with the posterior SD
19
+ that states how far it can be trusted. The counts enter a compound NB–Poisson
20
+ likelihood; what is estimated is the sequence's latent expression distribution.
21
+
22
+
23
+
24
+ <img src="http://data.georgy.top/media/ebin_model_layers.png" alt="EBin model"/>
25
+
26
+
27
+ ```MPRA
28
+ X[n,s,b] | T[n,s,b] ~ NB(R[s,b] · T[n,s,b], P[s,b]) reads from cells
29
+ T[n,s,b] ~ Poisson(a_n · Pi[n,b] · lambda_s) cells in bin b
30
+ Pi[n,b] = Phi((q_b − mu_n)/sigma_n) − Phi((q_{b−1} − mu_n)/sigma_n)
31
+ ```
32
+ Each sequence `n` carries a latent Gaussian effect law `N(mu_n, sigma_n²)` — its
33
+ expression distribution over cells — and an abundance `a_n`. The library's
34
+ marginal effect law is the **`N`-component mixture** of those per-sequence
35
+ normals, `G(x) = Σ_n w_n Phi((x − mu_n)/sigma_n)` with `w_n = 1/N`, and the `B`
36
+ sorting bins are its quantile cells: the cut points `q_1 < … < q_{B−1}` solve
37
+ `G(q_j) = j/B`. They are shared, and re-solved at every step, so every sequence
38
+ is tied to the marginal through them. This approach has 2 benefits: first one is that
39
+ it allows us to cut the number of params down to 2 instead of `B-1`, and the second one is that those params are further regularized, both by the normality assumption and the fact that they are all should form the global marginal distribution.
40
+
41
+ The activity that ships is the posterior **mean** of `E[bin] = Σ_b b·Pi[n,b]`,
42
+ integrated over the posterior of `(mu_n, sigma_n)` with the abundance profiled
43
+ per grid point. The plug-in point estimate is a posterior *mode*, and for a
44
+ low-count sequence the mode sits at a simplex vertex — activity exactly 1 or
45
+ `B`, regardless of depth.
46
+
47
+ ## Install
48
+ ```
49
+ pip install ebin
50
+ ```
51
+ or
52
+
53
+ ```bash
54
+ pip install -e /path/to/package # or place this directory on PYTHONPATH
55
+ ```
56
+
57
+ `jax` (GPU-version strongly recommended: `pip install jax[cuda]`), `numpy`, `scipy` and `pandas` are required.
58
+ `xarray` + `h5netcdf` are needed only for the netCDF export and `matplotlib`
59
+ only for the diagnostics. Everything runs in float64 as some parts of the algorithm require high precision, namely the tridiagonal eigenvalue solver for orthogonal polynomials.
60
+
61
+ ## Input
62
+
63
+ One row per sequence, a 3-level column header `(cell line, replicate, bin)`:
64
+
65
+ ```
66
+ seq, A549,A549,A549,A549,A549,...
67
+ rep1,rep1,rep1,rep1,rep2,...
68
+ bin1,bin2,bin3,bin4,bin1,...
69
+ ACGT..., 112, 340, 88, 15, 97, ...
70
+ ```
71
+ (in other words, the tabular should be readable with `pd.read_csv(..., header=[0,1,2])`)
72
+
73
+
74
+ Bins are ordered by the number in their name. Cell lines are fitted
75
+ independently. **Empty fields are read as zero counts, not as missing data** —
76
+ some exports write every zero as a blank, and treating those as missin
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ pip install -e /path/to/package # or place this directory on PYTHONPATH
82
+ ```
83
+
84
+ `jax` (GPU strongly recommended), `numpy`, `scipy` and `pandas` are required.
85
+ `xarray` + `h5netcdf` are needed only for the netCDF export and `matplotlib`
86
+ only for the diagnostics. Everything runs in float64.
87
+
88
+ ## Input
89
+
90
+ One row per sequence, a 3-level column header `(cell line, replicate, bin)`:
91
+
92
+ ```
93
+ seq, A549,A549,A549,A549,A549,...
94
+ rep1,rep1,rep1,rep1,rep2,...
95
+ bin1,bin2,bin3,bin4,bin1,...
96
+ ACGT..., 112, 340, 88, 15, 97, ...
97
+ ```
98
+
99
+ Bins are ordered by the number in their name. Cell lines are fitted
100
+ independently. **Empty fields are read as zero counts, not as missing data** —
101
+ some exports write every zero as a blank, and treating those as missing deletes
102
+ the informative zeros of the low-abundance sequences.
103
+
104
+ ## Use
105
+
106
+ ```bash
107
+ python -m ebin counts.csv -o activity.csv
108
+ ```
109
+
110
+ ```python
111
+ from ebin import activity_table
112
+
113
+ table, results = activity_table("counts.csv", out="activity.csv")
114
+ table[("A549", "activity")] # posterior-mean E[bin] per sequence
115
+ ```
116
+
117
+ The CSV has two header rows, `(cell line, field)`, one row per sequence, and
118
+ carries everything the model estimates per sequence:
119
+
120
+ | field | meaning |
121
+ | --- | --- |
122
+ | `activity` | posterior-mean `E[bin]` — the normalized value intended for downstream use |
123
+ | `activity_sd` | its posterior SD — per-sequence confidence |
124
+ | `activity_map` | plug-in mode, kept for reference only |
125
+ | `mu`, `mu_sd` | posterior-mean effect location and its standard error |
126
+ | `sigma`, `sigma_sd` | posterior-mean effect scale and its standard error |
127
+ | `abundance` | fitted size factor `a_n` |
128
+ | `n_eff` | posterior grid support — large means the estimate is diffuse |
129
+ | `tot` | total observed reads |
130
+
131
+ All of it comes from the same posterior weights, so the columns are mutually
132
+ consistent: `activity` is `Σ_b b·bin_prob`. `mu` and `sigma` are in gauge units
133
+ (median cut 0, first cut −1), so they are comparable across sequences within a
134
+ cell line. A subset is selected with `--fields activity,activity_sd,tot` (or
135
+ `fields=[...]` in the API).
136
+
137
+ The `B−1` cut points are a property of the cell line, not of a sequence, so
138
+ they are not columns: `cuts_table(results)` returns them as one row per cell
139
+ line, and the CLI writes them next to the activity table as
140
+ `<out>_cuts.csv`. The gauge fixes the first two at −1 and 0, so what varies
141
+ between lines is where the upper cuts land (A549 0.990, MDA-MB-231 0.964).
142
+
143
+ Sequences with no reads at all in a cell line keep an activity (they are fitted
144
+ as structural zeros and land near the neutral prior mean, ~2.5 for `B = 4`);
145
+ sequences with no observed cell at all are `NaN`.
146
+
147
+ Useful CLI options:
148
+
149
+ ```
150
+ --groups A549,HepG2 cell lines to run, in output order
151
+ --abundance gamma integrate a_n out instead of fitting it
152
+ --zero-truncation drop all-zero rows instead of fitting them
153
+ --grid 61x25 readout grid (n_mu x n_log_sigma)
154
+ --save-fits fits.pkl keep the fitted parameters
155
+ --warm-from fits.pkl start from an earlier fit of the same data
156
+ --netcdf activity.nc also write the full posterior (see below)
157
+ --plots DIR also write the diagnostic plots
158
+ ```
159
+
160
+ ### Per-bin distribution
161
+
162
+ The one field too wide for a flat table is `bin_prob`, the posterior-mean
163
+ probability of each bin — an `(N, B)` array per cell line. It is returned in
164
+ `results`, and `--netcdf` writes it alongside every scalar field:
165
+
166
+ ```python
167
+ from ebin import activity_table, write_netcdf
168
+
169
+ table, results = activity_table("counts.csv")
170
+ results["A549"]["bin_prob"] # (N, B), rows sum to 1
171
+ write_netcdf("activity.nc", results, table.index)
172
+ ```
173
+
174
+ Readouts can be redone from saved fits without refitting, which is the cheap
175
+ way to try a different grid or prior:
176
+
177
+ ```python
178
+ from ebin import readout_table
179
+ table, results = readout_table("counts.csv", "fits.pkl")
180
+ ```
181
+
182
+ ## Diagnostics
183
+
184
+ Three plots, one panel per cell line, drawn from the table alone (`--plots DIR`
185
+ on the CLI writes all three):
186
+
187
+ ```python
188
+ from ebin import (plot_marginal_distribution, plot_activity_vs_raw,
189
+ plot_gc_vs_abundance)
190
+
191
+ plot_marginal_distribution(table, out="marginal.png")
192
+ plot_activity_vs_raw(table, "counts.csv", out="vs_raw.png")
193
+ plot_gc_vs_abundance(table, out="gc.png")
194
+ ```
195
+
196
+ **`plot_marginal_distribution`** — the marginal effect law: the `N`-component
197
+ mixture `G(x) = Σ_n w_n Phi((x − mu_n)/sigma_n)`, one normal per sequence,
198
+ drawn as the density it defines and sliced into the sorting bins, each in its
199
+ own colour. The x ticks are the cut points with their values. Weights are
200
+ uniform by default, as in the fit; `weights=` takes a per-sequence weight (the
201
+ fitted abundances, say) to see the marginal over cells rather than over
202
+ sequences. Every slice holds exactly `1/B` of the mass by construction, so the
203
+ gauge (cuts at −1 and 0) and any unusual tightness or skew in a cell line's
204
+ effect law are visible here.
205
+
206
+ **`plot_activity_vs_raw`** — fitted activity against the depth-normalized raw
207
+ mass centre (each replicate×bin column divided by its own library size, then
208
+ `Σ_b b·p_b`), coloured by fitted abundance. Well-measured sequences sit on the
209
+ diagonal; the horizontal band at the centre is the low-abundance tail, where the
210
+ raw estimate is noise and the model shrinks toward neutral. A cell line whose
211
+ *high*-abundance sequences leave the diagonal is a real warning sign.
212
+
213
+ **`plot_gc_vs_abundance`** — GC content against the fitted size factor, with the
214
+ binned median trend. A strong trend means `a_n` is absorbing a
215
+ cloning/sequencing bias rather than biological abundance alone. GC is taken from
216
+ the table index when the index is the sequence; otherwise it is supplied through
217
+ `sequences=`.
218
+
219
+ `raw_mass_center(counts)` and `gc_content(seqs)` are exported separately for
220
+ cases where the raw numbers are more appropriate than a picture.
221
+
222
+ ## Configuration
223
+
224
+ Defaults are the shipped configuration; they are not arbitrary and are worth
225
+ understanding before they are changed.
226
+
227
+ | option | default | why |
228
+ | --- | --- | --- |
229
+ | `conditional` | `False` | Zero **inflation**: all-zero rows are fitted with a structural-zero probability `phi`, so they enter the mixture that sets the cuts. Zero **truncation** (`True`) drops them, which sets the cuts on a zero-excluded distribution — measurably worse, both in-library and on transfer to an independent library. |
230
+ | `abundance` | `True` | A free size factor `a_n` per sequence. Without one, every sequence has the same expected latent total, so real depth variation has nowhere to go but `Pi` — which tilts toward the bins with the largest channel scale, and `Pi` stops being a profile. |
231
+ | `abundance_prior` | `None` | `'gamma'` integrates `a_n` out under `Gamma(kappa, mean=1)` instead: 2 parameters per sequence instead of 3, low-count sequences regularized, and the abundance uncertainty propagated into the effect. The activity profile is essentially unchanged (ρ ≈ 0.9996 against free `a_n`), so this is a parameter-economy. Costs ~2× runtime. |
232
+ | `mu_prior` | `1.3` | SD of the prior on the effect location. Bounding the effect *spread* alone still lets a single-bin low-count sequence run `mu_n` large and walk `Pi` to a vertex. The gauge pins Q50 = 0 and Q25 = −1, so the population SD is ≈ 1.5 and the between-sequence SD ≈ 1.1 — the gauge-consistent `tau` is ~1.3. A larger value (2–3) is inconsistent with the gauge and under-regularizes. |
233
+ | `sigma_prior` | `(0.0, 0.5)` | Prior on `log sigma_n`. The per-sequence MLE is unbounded: a sequence whose reads land only in the outer bins wants a two-point mass, reachable only as `sigma → ∞`. Without this, `sigma` hits its bound in several cell lines; those are bad optima, so the prior often *improves* the data likelihood. `(0, 1)` fits marginally better on well-behaved lines but leaves stuck ones stuck. |
234
+ | `lambda_fix` | `50.0` | The latent Poisson level is not identified upward — it rides the `R·lambda` ridge, and only products like `R(1−P)/P · Pi · lambda` are identified. It is held fixed and `R` absorbs the scale. |
235
+ | `a_max` | `15.0` | Bound on `a_n`; also sizes the truncated latent-count grid, so raising it costs runtime and memory. |
236
+ | readout grid | `121 × 33` | `(mu, log sigma)` grid for the posterior mean. Converged in the bulk: doubling to `181 × 49` moves the median activity by 2e-6 (a handful of extreme low-count sequences move by up to 0.04), while halving to `61 × 25` moves it by 5e-3. |
237
+
238
+ The readout re-uses the fit's own priors by default, so the posterior mean is
239
+ coherent with the fitted model. A flat effect location is obtained with
240
+ `readout=dict(tau_within=None)`, and `mu_center=<array>` shrinks toward a
241
+ per-sequence target (for instance the same sequence's consensus across cell
242
+ lines).
243
+
244
+ ## Runtime
245
+
246
+ One cell line of 30k sequences × 4 bins takes ~2–4 min on a GPU (fit + readout)
247
+ and roughly 20× longer on CPU; the Gamma-abundance variant costs ~2× the
248
+ free-`a_n` fit. Memory is dominated by the latent-count grid
249
+ (`a_max · lambda_fix` wide); the likelihood scans over abundance/rate components
250
+ so only one is live at a time. `XLA_PYTHON_CLIENT_PREALLOCATE=false` is set on
251
+ import so JAX does not claim 75% of VRAM.
252
+
253
+
254
+ ## Parameters
255
+
256
+
257
+ | symbol | shape | role | what it is | example (A549) |
258
+ | --- | --- | --- | --- | --- |
259
+ | `X[n,s,b]` | N×S×B | observed | reads counted for sequence n in channel (s,b) | 1686 median total |
260
+ | `T[n,s,b]` | N×S×B | latent | cells of n that landed in bin b — never observed, summed out | ~63 cells |
261
+ | `mu_n`, `sigma_n` | N each | per sequence | the sequence's expression law over cells, in gauge units | σ median 1.46 |
262
+ | `a_n` | N | per sequence | size factor: how many cells n contributes at all. Geometric mean pinned to 1, capped at `a_max` | 1.42 median |
263
+ | `Pi[n,b]` | N×B | derived | bin profile, rows sum to 1. Not free — read off `(mu_n, sigma_n)` and the cuts | — |
264
+ | `q_j` | B−1 | shared | cut points = quantiles of the mixture `G` at `j/B`. Gauge pins `q_1 = −1`, `q_2 = 0` | −1, 0, 0.99 |
265
+ | `lambda_s` | S | fixed | cell level of replicate s. Not identified — rides the `R·lambda` ridge, so held fixed while `R` absorbs the scale | 50 |
266
+ | `R[s,b]` | S×B | per channel | NB size per latent cell: `R·T` is the shape of the read distribution | 12.7 11.4 11.6 20.1 |
267
+ | `P[s,b]` | S×B | per channel | NB probability. Small `P` = a noisier channel at the same depth | .33 .32 .31 .52 |
268
+ | `phi` | 1 | shared | probability a sequence is a structural zero (dropout, never a cell) | 8e−7 |
269
+ | `kappa` | 1 | optional | Gamma shape when `a_n` is integrated out instead of fitted; CV = 1/√κ | 0.9 (variant) |
270
+
271
+ so `X, T, R, P` are 3D arrays:
272
+ <center>
273
+ <img src="http://data.georgy.top/media/ebin_index_cube.png" alt="Index cube: n sequences, s replicates, b bins" width="196">
274
+ </center>
275
+
@@ -4,8 +4,9 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ebin"
7
- version = "1.0"
7
+ dynamic = ["version"]
8
8
  description = "Posterior bin-expectation normalization for sorting-based MPRA"
9
+ readme = "README.md"
9
10
  requires-python = ">=3.9"
10
11
  dependencies = ["jax>=0.4", "numpy", "scipy", "pandas"]
11
12
 
@@ -17,3 +18,6 @@ ebin = "ebin.__main__:main"
17
18
 
18
19
  [tool.setuptools]
19
20
  packages = ["ebin"]
21
+
22
+ [tool.setuptools.dynamic]
23
+ version = {attr = "ebin.__version__"}
ebin-1.0/PKG-INFO DELETED
@@ -1,12 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: ebin
3
- Version: 1.0
4
- Summary: Posterior bin-expectation normalization for sorting-based MPRA
5
- Requires-Python: >=3.9
6
- Requires-Dist: jax>=0.4
7
- Requires-Dist: numpy
8
- Requires-Dist: scipy
9
- Requires-Dist: pandas
10
- Provides-Extra: netcdf
11
- Requires-Dist: xarray; extra == "netcdf"
12
- Requires-Dist: h5netcdf; extra == "netcdf"
@@ -1,12 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: ebin
3
- Version: 1.0
4
- Summary: Posterior bin-expectation normalization for sorting-based MPRA
5
- Requires-Python: >=3.9
6
- Requires-Dist: jax>=0.4
7
- Requires-Dist: numpy
8
- Requires-Dist: scipy
9
- Requires-Dist: pandas
10
- Provides-Extra: netcdf
11
- Requires-Dist: xarray; extra == "netcdf"
12
- Requires-Dist: h5netcdf; extra == "netcdf"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes