ebin 1.0__tar.gz → 1.0.3__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.3
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 —
@@ -61,15 +75,6 @@ Bins are ordered by the number in their name. Cell lines are fitted
61
75
  independently. **Empty fields are read as zero counts, not as missing data** —
62
76
  some exports write every zero as a blank, and treating those as missin
63
77
 
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
78
 
74
79
  ## Input
75
80
 
@@ -227,61 +232,6 @@ coherent with the fitted model. A flat effect location is obtained with
227
232
  per-sequence target (for instance the same sequence's consensus across cell
228
233
  lines).
229
234
 
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
235
  ## Runtime
286
236
 
287
237
  One cell line of 30k sequences × 4 bins takes ~2–4 min on a GPU (fit + readout)
ebin-1.0.3/README.md ADDED
@@ -0,0 +1,252 @@
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
+
65
+ ## Input
66
+
67
+ One row per sequence, a 3-level column header `(cell line, replicate, bin)`:
68
+
69
+ ```
70
+ seq, A549,A549,A549,A549,A549,...
71
+ rep1,rep1,rep1,rep1,rep2,...
72
+ bin1,bin2,bin3,bin4,bin1,...
73
+ ACGT..., 112, 340, 88, 15, 97, ...
74
+ ```
75
+
76
+ Bins are ordered by the number in their name. Cell lines are fitted
77
+ independently. **Empty fields are read as zero counts, not as missing data** —
78
+ some exports write every zero as a blank, and treating those as missing deletes
79
+ the informative zeros of the low-abundance sequences.
80
+
81
+ ## Use
82
+
83
+ ```bash
84
+ python -m ebin counts.csv -o activity.csv
85
+ ```
86
+
87
+ ```python
88
+ from ebin import activity_table
89
+
90
+ table, results = activity_table("counts.csv", out="activity.csv")
91
+ table[("A549", "activity")] # posterior-mean E[bin] per sequence
92
+ ```
93
+
94
+ The CSV has two header rows, `(cell line, field)`, one row per sequence, and
95
+ carries everything the model estimates per sequence:
96
+
97
+ | field | meaning |
98
+ | --- | --- |
99
+ | `activity` | posterior-mean `E[bin]` — the normalized value intended for downstream use |
100
+ | `activity_sd` | its posterior SD — per-sequence confidence |
101
+ | `activity_map` | plug-in mode, kept for reference only |
102
+ | `mu`, `mu_sd` | posterior-mean effect location and its standard error |
103
+ | `sigma`, `sigma_sd` | posterior-mean effect scale and its standard error |
104
+ | `abundance` | fitted size factor `a_n` |
105
+ | `n_eff` | posterior grid support — large means the estimate is diffuse |
106
+ | `tot` | total observed reads |
107
+
108
+ All of it comes from the same posterior weights, so the columns are mutually
109
+ consistent: `activity` is `Σ_b b·bin_prob`. `mu` and `sigma` are in gauge units
110
+ (median cut 0, first cut −1), so they are comparable across sequences within a
111
+ cell line. A subset is selected with `--fields activity,activity_sd,tot` (or
112
+ `fields=[...]` in the API).
113
+
114
+ The `B−1` cut points are a property of the cell line, not of a sequence, so
115
+ they are not columns: `cuts_table(results)` returns them as one row per cell
116
+ line, and the CLI writes them next to the activity table as
117
+ `<out>_cuts.csv`. The gauge fixes the first two at −1 and 0, so what varies
118
+ between lines is where the upper cuts land (A549 0.990, MDA-MB-231 0.964).
119
+
120
+ Sequences with no reads at all in a cell line keep an activity (they are fitted
121
+ as structural zeros and land near the neutral prior mean, ~2.5 for `B = 4`);
122
+ sequences with no observed cell at all are `NaN`.
123
+
124
+ Useful CLI options:
125
+
126
+ ```
127
+ --groups A549,HepG2 cell lines to run, in output order
128
+ --abundance gamma integrate a_n out instead of fitting it
129
+ --zero-truncation drop all-zero rows instead of fitting them
130
+ --grid 61x25 readout grid (n_mu x n_log_sigma)
131
+ --save-fits fits.pkl keep the fitted parameters
132
+ --warm-from fits.pkl start from an earlier fit of the same data
133
+ --netcdf activity.nc also write the full posterior (see below)
134
+ --plots DIR also write the diagnostic plots
135
+ ```
136
+
137
+ ### Per-bin distribution
138
+
139
+ The one field too wide for a flat table is `bin_prob`, the posterior-mean
140
+ probability of each bin — an `(N, B)` array per cell line. It is returned in
141
+ `results`, and `--netcdf` writes it alongside every scalar field:
142
+
143
+ ```python
144
+ from ebin import activity_table, write_netcdf
145
+
146
+ table, results = activity_table("counts.csv")
147
+ results["A549"]["bin_prob"] # (N, B), rows sum to 1
148
+ write_netcdf("activity.nc", results, table.index)
149
+ ```
150
+
151
+ Readouts can be redone from saved fits without refitting, which is the cheap
152
+ way to try a different grid or prior:
153
+
154
+ ```python
155
+ from ebin import readout_table
156
+ table, results = readout_table("counts.csv", "fits.pkl")
157
+ ```
158
+
159
+ ## Diagnostics
160
+
161
+ Three plots, one panel per cell line, drawn from the table alone (`--plots DIR`
162
+ on the CLI writes all three):
163
+
164
+ ```python
165
+ from ebin import (plot_marginal_distribution, plot_activity_vs_raw,
166
+ plot_gc_vs_abundance)
167
+
168
+ plot_marginal_distribution(table, out="marginal.png")
169
+ plot_activity_vs_raw(table, "counts.csv", out="vs_raw.png")
170
+ plot_gc_vs_abundance(table, out="gc.png")
171
+ ```
172
+
173
+ **`plot_marginal_distribution`** — the marginal effect law: the `N`-component
174
+ mixture `G(x) = Σ_n w_n Phi((x − mu_n)/sigma_n)`, one normal per sequence,
175
+ drawn as the density it defines and sliced into the sorting bins, each in its
176
+ own colour. The x ticks are the cut points with their values. Weights are
177
+ uniform by default, as in the fit; `weights=` takes a per-sequence weight (the
178
+ fitted abundances, say) to see the marginal over cells rather than over
179
+ sequences. Every slice holds exactly `1/B` of the mass by construction, so the
180
+ gauge (cuts at −1 and 0) and any unusual tightness or skew in a cell line's
181
+ effect law are visible here.
182
+
183
+ **`plot_activity_vs_raw`** — fitted activity against the depth-normalized raw
184
+ mass centre (each replicate×bin column divided by its own library size, then
185
+ `Σ_b b·p_b`), coloured by fitted abundance. Well-measured sequences sit on the
186
+ diagonal; the horizontal band at the centre is the low-abundance tail, where the
187
+ raw estimate is noise and the model shrinks toward neutral. A cell line whose
188
+ *high*-abundance sequences leave the diagonal is a real warning sign.
189
+
190
+ **`plot_gc_vs_abundance`** — GC content against the fitted size factor, with the
191
+ binned median trend. A strong trend means `a_n` is absorbing a
192
+ cloning/sequencing bias rather than biological abundance alone. GC is taken from
193
+ the table index when the index is the sequence; otherwise it is supplied through
194
+ `sequences=`.
195
+
196
+ `raw_mass_center(counts)` and `gc_content(seqs)` are exported separately for
197
+ cases where the raw numbers are more appropriate than a picture.
198
+
199
+ ## Configuration
200
+
201
+ Defaults are the shipped configuration; they are not arbitrary and are worth
202
+ understanding before they are changed.
203
+
204
+ | option | default | why |
205
+ | --- | --- | --- |
206
+ | `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. |
207
+ | `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. |
208
+ | `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. |
209
+ | `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. |
210
+ | `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. |
211
+ | `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. |
212
+ | `a_max` | `15.0` | Bound on `a_n`; also sizes the truncated latent-count grid, so raising it costs runtime and memory. |
213
+ | 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. |
214
+
215
+ The readout re-uses the fit's own priors by default, so the posterior mean is
216
+ coherent with the fitted model. A flat effect location is obtained with
217
+ `readout=dict(tau_within=None)`, and `mu_center=<array>` shrinks toward a
218
+ per-sequence target (for instance the same sequence's consensus across cell
219
+ lines).
220
+
221
+ ## Runtime
222
+
223
+ One cell line of 30k sequences × 4 bins takes ~2–4 min on a GPU (fit + readout)
224
+ and roughly 20× longer on CPU; the Gamma-abundance variant costs ~2× the
225
+ free-`a_n` fit. Memory is dominated by the latent-count grid
226
+ (`a_max · lambda_fix` wide); the likelihood scans over abundance/rate components
227
+ so only one is live at a time. `XLA_PYTHON_CLIENT_PREALLOCATE=false` is set on
228
+ import so JAX does not claim 75% of VRAM.
229
+
230
+
231
+ ## Parameters
232
+
233
+
234
+ | symbol | shape | role | what it is | example (A549) |
235
+ | --- | --- | --- | --- | --- |
236
+ | `X[n,s,b]` | N×S×B | observed | reads counted for sequence n in channel (s,b) | 1686 median total |
237
+ | `T[n,s,b]` | N×S×B | latent | cells of n that landed in bin b — never observed, summed out | ~63 cells |
238
+ | `mu_n`, `sigma_n` | N each | per sequence | the sequence's expression law over cells, in gauge units | σ median 1.46 |
239
+ | `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 |
240
+ | `Pi[n,b]` | N×B | derived | bin profile, rows sum to 1. Not free — read off `(mu_n, sigma_n)` and the cuts | — |
241
+ | `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 |
242
+ | `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 |
243
+ | `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 |
244
+ | `P[s,b]` | S×B | per channel | NB probability. Small `P` = a noisier channel at the same depth | .33 .32 .31 .52 |
245
+ | `phi` | 1 | shared | probability a sequence is a structural zero (dropout, never a cell) | 8e−7 |
246
+ | `kappa` | 1 | optional | Gamma shape when `a_n` is integrated out instead of fitted; CV = 1/√κ | 0.9 (variant) |
247
+
248
+ so `X, T, R, P` are 3D arrays:
249
+ <center>
250
+ <img src="http://data.georgy.top/media/ebin_index_cube.png" alt="Index cube: n sequences, s replicates, b bins" width="196">
251
+ </center>
252
+
@@ -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.3"
@@ -0,0 +1,266 @@
1
+ Metadata-Version: 2.4
2
+ Name: ebin
3
+ Version: 1.0.3
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
+
79
+ ## Input
80
+
81
+ One row per sequence, a 3-level column header `(cell line, replicate, bin)`:
82
+
83
+ ```
84
+ seq, A549,A549,A549,A549,A549,...
85
+ rep1,rep1,rep1,rep1,rep2,...
86
+ bin1,bin2,bin3,bin4,bin1,...
87
+ ACGT..., 112, 340, 88, 15, 97, ...
88
+ ```
89
+
90
+ Bins are ordered by the number in their name. Cell lines are fitted
91
+ independently. **Empty fields are read as zero counts, not as missing data** —
92
+ some exports write every zero as a blank, and treating those as missing deletes
93
+ the informative zeros of the low-abundance sequences.
94
+
95
+ ## Use
96
+
97
+ ```bash
98
+ python -m ebin counts.csv -o activity.csv
99
+ ```
100
+
101
+ ```python
102
+ from ebin import activity_table
103
+
104
+ table, results = activity_table("counts.csv", out="activity.csv")
105
+ table[("A549", "activity")] # posterior-mean E[bin] per sequence
106
+ ```
107
+
108
+ The CSV has two header rows, `(cell line, field)`, one row per sequence, and
109
+ carries everything the model estimates per sequence:
110
+
111
+ | field | meaning |
112
+ | --- | --- |
113
+ | `activity` | posterior-mean `E[bin]` — the normalized value intended for downstream use |
114
+ | `activity_sd` | its posterior SD — per-sequence confidence |
115
+ | `activity_map` | plug-in mode, kept for reference only |
116
+ | `mu`, `mu_sd` | posterior-mean effect location and its standard error |
117
+ | `sigma`, `sigma_sd` | posterior-mean effect scale and its standard error |
118
+ | `abundance` | fitted size factor `a_n` |
119
+ | `n_eff` | posterior grid support — large means the estimate is diffuse |
120
+ | `tot` | total observed reads |
121
+
122
+ All of it comes from the same posterior weights, so the columns are mutually
123
+ consistent: `activity` is `Σ_b b·bin_prob`. `mu` and `sigma` are in gauge units
124
+ (median cut 0, first cut −1), so they are comparable across sequences within a
125
+ cell line. A subset is selected with `--fields activity,activity_sd,tot` (or
126
+ `fields=[...]` in the API).
127
+
128
+ The `B−1` cut points are a property of the cell line, not of a sequence, so
129
+ they are not columns: `cuts_table(results)` returns them as one row per cell
130
+ line, and the CLI writes them next to the activity table as
131
+ `<out>_cuts.csv`. The gauge fixes the first two at −1 and 0, so what varies
132
+ between lines is where the upper cuts land (A549 0.990, MDA-MB-231 0.964).
133
+
134
+ Sequences with no reads at all in a cell line keep an activity (they are fitted
135
+ as structural zeros and land near the neutral prior mean, ~2.5 for `B = 4`);
136
+ sequences with no observed cell at all are `NaN`.
137
+
138
+ Useful CLI options:
139
+
140
+ ```
141
+ --groups A549,HepG2 cell lines to run, in output order
142
+ --abundance gamma integrate a_n out instead of fitting it
143
+ --zero-truncation drop all-zero rows instead of fitting them
144
+ --grid 61x25 readout grid (n_mu x n_log_sigma)
145
+ --save-fits fits.pkl keep the fitted parameters
146
+ --warm-from fits.pkl start from an earlier fit of the same data
147
+ --netcdf activity.nc also write the full posterior (see below)
148
+ --plots DIR also write the diagnostic plots
149
+ ```
150
+
151
+ ### Per-bin distribution
152
+
153
+ The one field too wide for a flat table is `bin_prob`, the posterior-mean
154
+ probability of each bin — an `(N, B)` array per cell line. It is returned in
155
+ `results`, and `--netcdf` writes it alongside every scalar field:
156
+
157
+ ```python
158
+ from ebin import activity_table, write_netcdf
159
+
160
+ table, results = activity_table("counts.csv")
161
+ results["A549"]["bin_prob"] # (N, B), rows sum to 1
162
+ write_netcdf("activity.nc", results, table.index)
163
+ ```
164
+
165
+ Readouts can be redone from saved fits without refitting, which is the cheap
166
+ way to try a different grid or prior:
167
+
168
+ ```python
169
+ from ebin import readout_table
170
+ table, results = readout_table("counts.csv", "fits.pkl")
171
+ ```
172
+
173
+ ## Diagnostics
174
+
175
+ Three plots, one panel per cell line, drawn from the table alone (`--plots DIR`
176
+ on the CLI writes all three):
177
+
178
+ ```python
179
+ from ebin import (plot_marginal_distribution, plot_activity_vs_raw,
180
+ plot_gc_vs_abundance)
181
+
182
+ plot_marginal_distribution(table, out="marginal.png")
183
+ plot_activity_vs_raw(table, "counts.csv", out="vs_raw.png")
184
+ plot_gc_vs_abundance(table, out="gc.png")
185
+ ```
186
+
187
+ **`plot_marginal_distribution`** — the marginal effect law: the `N`-component
188
+ mixture `G(x) = Σ_n w_n Phi((x − mu_n)/sigma_n)`, one normal per sequence,
189
+ drawn as the density it defines and sliced into the sorting bins, each in its
190
+ own colour. The x ticks are the cut points with their values. Weights are
191
+ uniform by default, as in the fit; `weights=` takes a per-sequence weight (the
192
+ fitted abundances, say) to see the marginal over cells rather than over
193
+ sequences. Every slice holds exactly `1/B` of the mass by construction, so the
194
+ gauge (cuts at −1 and 0) and any unusual tightness or skew in a cell line's
195
+ effect law are visible here.
196
+
197
+ **`plot_activity_vs_raw`** — fitted activity against the depth-normalized raw
198
+ mass centre (each replicate×bin column divided by its own library size, then
199
+ `Σ_b b·p_b`), coloured by fitted abundance. Well-measured sequences sit on the
200
+ diagonal; the horizontal band at the centre is the low-abundance tail, where the
201
+ raw estimate is noise and the model shrinks toward neutral. A cell line whose
202
+ *high*-abundance sequences leave the diagonal is a real warning sign.
203
+
204
+ **`plot_gc_vs_abundance`** — GC content against the fitted size factor, with the
205
+ binned median trend. A strong trend means `a_n` is absorbing a
206
+ cloning/sequencing bias rather than biological abundance alone. GC is taken from
207
+ the table index when the index is the sequence; otherwise it is supplied through
208
+ `sequences=`.
209
+
210
+ `raw_mass_center(counts)` and `gc_content(seqs)` are exported separately for
211
+ cases where the raw numbers are more appropriate than a picture.
212
+
213
+ ## Configuration
214
+
215
+ Defaults are the shipped configuration; they are not arbitrary and are worth
216
+ understanding before they are changed.
217
+
218
+ | option | default | why |
219
+ | --- | --- | --- |
220
+ | `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. |
221
+ | `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. |
222
+ | `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. |
223
+ | `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. |
224
+ | `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. |
225
+ | `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. |
226
+ | `a_max` | `15.0` | Bound on `a_n`; also sizes the truncated latent-count grid, so raising it costs runtime and memory. |
227
+ | 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. |
228
+
229
+ The readout re-uses the fit's own priors by default, so the posterior mean is
230
+ coherent with the fitted model. A flat effect location is obtained with
231
+ `readout=dict(tau_within=None)`, and `mu_center=<array>` shrinks toward a
232
+ per-sequence target (for instance the same sequence's consensus across cell
233
+ lines).
234
+
235
+ ## Runtime
236
+
237
+ One cell line of 30k sequences × 4 bins takes ~2–4 min on a GPU (fit + readout)
238
+ and roughly 20× longer on CPU; the Gamma-abundance variant costs ~2× the
239
+ free-`a_n` fit. Memory is dominated by the latent-count grid
240
+ (`a_max · lambda_fix` wide); the likelihood scans over abundance/rate components
241
+ so only one is live at a time. `XLA_PYTHON_CLIENT_PREALLOCATE=false` is set on
242
+ import so JAX does not claim 75% of VRAM.
243
+
244
+
245
+ ## Parameters
246
+
247
+
248
+ | symbol | shape | role | what it is | example (A549) |
249
+ | --- | --- | --- | --- | --- |
250
+ | `X[n,s,b]` | N×S×B | observed | reads counted for sequence n in channel (s,b) | 1686 median total |
251
+ | `T[n,s,b]` | N×S×B | latent | cells of n that landed in bin b — never observed, summed out | ~63 cells |
252
+ | `mu_n`, `sigma_n` | N each | per sequence | the sequence's expression law over cells, in gauge units | σ median 1.46 |
253
+ | `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 |
254
+ | `Pi[n,b]` | N×B | derived | bin profile, rows sum to 1. Not free — read off `(mu_n, sigma_n)` and the cuts | — |
255
+ | `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 |
256
+ | `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 |
257
+ | `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 |
258
+ | `P[s,b]` | S×B | per channel | NB probability. Small `P` = a noisier channel at the same depth | .33 .32 .31 .52 |
259
+ | `phi` | 1 | shared | probability a sequence is a structural zero (dropout, never a cell) | 8e−7 |
260
+ | `kappa` | 1 | optional | Gamma shape when `a_n` is integrated out instead of fitted; CV = 1/√κ | 0.9 (variant) |
261
+
262
+ so `X, T, R, P` are 3D arrays:
263
+ <center>
264
+ <img src="http://data.georgy.top/media/ebin_index_cube.png" alt="Index cube: n sequences, s replicates, b bins" width="196">
265
+ </center>
266
+
@@ -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