DynaVista 0.5.0rc1__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.
@@ -0,0 +1,994 @@
1
+ Metadata-Version: 2.4
2
+ Name: DynaVista
3
+ Version: 0.5.0rc1
4
+ Summary: Stochastic discrete dynamical systems simulator for Boolean and multi-state biological networks
5
+ Author: Daniel Plaugher
6
+ License: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: numpy>=1.24
11
+ Requires-Dist: scipy>=1.10
12
+ Requires-Dist: sympy>=1.12
13
+ Requires-Dist: matplotlib>=3.7
14
+ Requires-Dist: pandas>=2.0
15
+ Requires-Dist: joblib>=1.3
16
+ Requires-Dist: openpyxl>=3.1
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=7.0; extra == "dev"
19
+ Requires-Dist: jupyter>=1.0; extra == "dev"
20
+ Requires-Dist: ipykernel; extra == "dev"
21
+ Provides-Extra: docs
22
+ Requires-Dist: mkdocs>=1.5; extra == "docs"
23
+ Requires-Dist: mkdocs-material>=9.5; extra == "docs"
24
+ Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
25
+ Requires-Dist: black>=24.0; extra == "docs"
26
+ Dynamic: license-file
27
+
28
+ # DynaVista
29
+
30
+ **Stochastic Discrete Dynamical Systems (SDDS) Simulator for Biological Networks**
31
+
32
+ A Python framework for Boolean and multi-state network simulation, mutation/control
33
+ analysis, attractor identification, and Markov chain analysis.
34
+
35
+ **Authors:** Daniel Plaugher
36
+ **Based on:** SMATA pipeline (Plaugher 2022) and BNPBN toolbox (Shmulevich, Aguilar, Murrugarra)
37
+ **Version:** 0.5.0
38
+
39
+ [![PyPI](https://img.shields.io/pypi/v/DynaVista?label=PyPI)](https://pypi.org/project/DynaVista/)
40
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
41
+ [![Docs](https://img.shields.io/badge/docs-mkdocs-green)](https://drplaugher.github.io/DynaVista)
42
+
43
+ ---
44
+
45
+ ## Table of Contents
46
+
47
+ 1. [Installation](#1-installation)
48
+ 2. [Quick Start](#2-quick-start)
49
+ 3. [Project Structure](#3-project-structure)
50
+ 4. [Core Concepts](#4-core-concepts)
51
+ 5. [Module Reference](#5-module-reference)
52
+ 6. [Config File Guide](#6-config-file-guide)
53
+ 7. [Network Format Guide](#7-network-format-guide)
54
+ 8. [Mutation and Control Guide](#8-mutation-and-control-guide)
55
+ 9. [Mutation Sweep Guide](#9-mutation-sweep-guide)
56
+ 10. [Markov Chain Guide](#10-markov-chain-guide)
57
+ 11. [Scalability Guide](#11-scalability-guide)
58
+ 12. [MATLAB Equivalence Table](#12-matlab-equivalence-table)
59
+ 13. [Citation](#13-citation)
60
+
61
+ ---
62
+
63
+ ## 1. Installation
64
+
65
+ ### Requirements
66
+
67
+ - Python 3.10 or higher
68
+ - pip (included with Python)
69
+
70
+ ### Step-by-step install
71
+
72
+ **Step 1.** Download the `dynavista` folder (from GitHub or as a zip).
73
+
74
+ **Step 2.** Open a terminal and navigate to the folder containing `dynavista/` and `pyproject.toml`.
75
+
76
+ **Step 3.** Install:
77
+
78
+ ```bash
79
+ pip install -e .
80
+ ```
81
+
82
+ The `-e` flag installs in *editable* mode — changes to source files take effect immediately without reinstalling.
83
+
84
+ All required packages are installed automatically:
85
+
86
+ | Package | Purpose |
87
+ |---------|---------|
88
+ | `numpy` | Array math, state vectors |
89
+ | `scipy` | Sparse matrices (Markov chain) |
90
+ | `sympy` | Symbolic polynomial evaluation in sdds_build |
91
+ | `matplotlib` | All plotting |
92
+ | `pandas` | Sweep results, attractor tables |
93
+ | `joblib` | Parallel simulation runs |
94
+ | `openpyxl` | Excel workbook export (config pipeline) |
95
+
96
+ ### Verify
97
+
98
+ ```python
99
+ import dynavista
100
+ print(dynavista.__version__) # should print 0.5.0
101
+ ```
102
+
103
+ ### Documentation
104
+
105
+ Full documentation — including the auto-generated API reference — can be read
106
+ two ways:
107
+
108
+ **Option A — Read it online (no setup).**
109
+ The published documentation is hosted at
110
+ **[https://drplaugher.github.io/DynaVista](https://drplaugher.github.io/DynaVista)**.
111
+ This is the easiest option: just open the link in a browser. (If the link does
112
+ not load yet, the online docs have not been published for this release — use
113
+ Option B in the meantime.)
114
+
115
+ **Option B — Build and read it locally.**
116
+ The documentation is built with [MkDocs](https://www.mkdocs.org/) from the
117
+ `docs/` folder and the source docstrings. To read it on your own machine:
118
+
119
+ ```bash
120
+ pip install -e ".[docs]" # installs mkdocs + the docs toolchain
121
+ mkdocs serve # serves the docs locally
122
+ ```
123
+
124
+ Then open **http://127.0.0.1:8000** in your browser. Press `Ctrl+C` in the
125
+ terminal to stop the server. To produce a static copy instead of serving it,
126
+ run `mkdocs build` — the finished site is written to a `site/` folder you can
127
+ open directly (`site/index.html`).
128
+
129
+ The API reference is generated automatically from the docstrings in the source
130
+ code, so it always matches the installed version.
131
+
132
+ ### IDE setup
133
+
134
+ DynaVista works in any Python environment with no special configuration:
135
+ - **Jupyter Notebook / JupyterLab** — recommended for interactive analysis
136
+ - **VS Code** — install the Python extension, select your Python interpreter
137
+ - **PyCharm** — open the project folder, mark `dynavista/` as a source root
138
+ - **Spyder** — install via Anaconda, then `pip install -e .` in the Spyder terminal
139
+ - **Plain Python scripts** — `python my_analysis.py`
140
+
141
+ ---
142
+
143
+ ## 2. Quick Start
144
+
145
+ ### Minimal example
146
+
147
+ ```python
148
+ import numpy as np
149
+ from dynavista import sdds_build, simulate, plot_simulation
150
+
151
+ # Define network
152
+ node_names = ["A", "B", "C"]
153
+ rules = ["C", "A", "A OR B"] # Boolean or polynomial form
154
+
155
+ # Build SDDS structures
156
+ varF, nv, F = sdds_build(rules, node_names, p=2)
157
+
158
+ # Propensity matrix (probability of state change per step)
159
+ n = len(node_names)
160
+ c = 0.9 * np.ones((2, n))
161
+
162
+ # Simulate — noise=0.0 selects the clean path automatically
163
+ Y, My = simulate(F, varF, nv, p=2, c=c, nsteps=20, nins=1000, noise=0.0)
164
+
165
+ # Plot
166
+ plot_simulation(Y, node_names)
167
+ ```
168
+
169
+ ### One-file pipeline
170
+
171
+ ```python
172
+ from dynavista.config import run_from_config
173
+
174
+ run_from_config("dynavista_config.py")
175
+ ```
176
+
177
+ ---
178
+
179
+ ## Customising figures
180
+
181
+ `PlotConfig` controls palette, font size, DPI, and save format for every plot
182
+ function in dynavista:
183
+
184
+ ```python
185
+ from dynavista import PlotConfig, plot_simulation
186
+
187
+ cfg = PlotConfig(
188
+ palette="coolwarm", # matplotlib colormap or list of hex colours
189
+ fontsize=14,
190
+ dpi=300,
191
+ save_path="trajectory.pdf",
192
+ save_format="pdf",
193
+ )
194
+
195
+ plot_simulation(Y, node_names, plot_cfg=cfg)
196
+ ```
197
+
198
+ ---
199
+
200
+ ## 3. Project Structure
201
+
202
+ ```
203
+ dynavista/
204
+ ├── __init__.py Clean public API — import everything from here
205
+ ├── sdds_build.py Build truth tables from network rules
206
+ ├── sdds_next_state.py Single SDDS update step (stochastic + deterministic)
207
+ ├── sdds_run.py Single trajectory runner (with/without noise)
208
+ ├── sdds_sim.py Ensemble simulation over many initializations
209
+ ├── truth_table_mutations.py Node and edge perturbations (mutations, controls)
210
+ ├── attr_search.py Attractor identification from simulation endpoints
211
+ ├── markov.py Markov chain analysis (transition matrix, basins)
212
+ ├── sweep.py Automated single-node and combinatorial sweeps
213
+ ├── parsers.py Multi-format network file parsers
214
+ ├── plotting.py Publication-ready figures
215
+ ├── config.py Config-file pipeline runner (run_from_config)
216
+ └── utils.py Base conversion utilities (dec2multistate, etc.)
217
+
218
+ examples/
219
+ ├── TLGL6/ 6-node T-LGL leukemia model (config + notebooks)
220
+ ├── PCC_small/ 22-node network
221
+ ├── KLK/ 38-node lung-cancer signaling network
222
+ ├── TLGL_large/ 60-node T-LGL model
223
+ └── PCC_large/ 69-node network (cyclic attractors)
224
+ # each folder has dynavista_config_<NAME>.py, attractors_<NAME>.csv,
225
+ # (TLGL6 and KLK also ship a worked-example notebook)
226
+ ```
227
+
228
+ ---
229
+
230
+ ## 4. Core Concepts
231
+
232
+ ### Network rules
233
+
234
+ Each node's next state is defined by an update rule. The two most common input formats are shown below; see §5 for the full set (polynomial, Boolean word, symbol, and mixed):
235
+
236
+ **Polynomial form** (GF(p) arithmetic, matches MATLAB):
237
+ ```python
238
+ "x1*x2 + x1 + x2" # x1 OR x2
239
+ "x1 + 1" # NOT x1
240
+ "x1*x2" # x1 AND x2
241
+ "1" # always ON
242
+ "0" # always OFF
243
+ ```
244
+
245
+ **Boolean form** (human-readable, auto-converted):
246
+ ```python
247
+ "x1 OR x2"
248
+ "NOT x1"
249
+ "x1 AND x2"
250
+ "True"
251
+ "False"
252
+ ```
253
+
254
+ You can mix both formats in the same rule list. `sdds_build` auto-detects per rule.
255
+
256
+ ### SDDS structures
257
+
258
+ `sdds_build()` produces three arrays used by all downstream functions:
259
+
260
+ | Array | Shape | Content |
261
+ |-------|-------|---------|
262
+ | `varF` | `(MAXnv, n)` | Input variable indices per node (1-indexed, -1 = unused) |
263
+ | `nv` | `(n,)` | Number of inputs per node |
264
+ | `F` | `(p^MAXnv, n)` | Truth table values |
265
+
266
+ ### Stochastic update (SDDS)
267
+
268
+ At each step, each node computes its deterministic target `z[i]`, then:
269
+ - **Activation** (`x[i] < z[i]`): node updates with probability `c[0, i]`
270
+ - **Degradation** (`x[i] > z[i]`): node updates with probability `c[1, i]`
271
+ - **No change** (`x[i] == z[i]`): stays as-is
272
+
273
+ `c = 0.9 * ones(2, n)` means nodes update 90% of the time when a change is warranted.
274
+ `c = 1.0` gives deterministic (synchronous) updates.
275
+
276
+ ### Global noise
277
+
278
+ `noise > 0` replaces the entire state randomly with probability `noise` per step.
279
+ This models stochastic perturbations and prevents convergence to attractors.
280
+ **Do not run attractor search on noisy simulations.**
281
+
282
+ ### Simulation output
283
+
284
+ `Y` has shape `(n, nsteps+1)`. `Y[i, t]` is the fraction of simulation runs in
285
+ which node `i` was ON at time step `t`. `Y[:, -1]` gives endpoint expression frequencies.
286
+
287
+ ---
288
+
289
+ ## 5. Module Reference
290
+
291
+ ### `sdds_build.py`
292
+
293
+ ```python
294
+ varF, nv, F = sdds_build(rules, node_names, p=2)
295
+ ```
296
+
297
+ Converts network rules to SDDS truth table structures. This is the entry
298
+ point for every analysis — all other functions consume its output. The rule
299
+ format (polynomial, Boolean word, symbol, or mixed) is detected automatically,
300
+ so you never need to declare it.
301
+
302
+ | Parameter | Type | Description |
303
+ |-----------|------|-------------|
304
+ | `rules` | `list[str]` | One rule per node, polynomial or Boolean (auto-detected) |
305
+ | `node_names` | `list[str]` | Ordered node names (index 0 = x1) |
306
+ | `p` | `int` | States per node (default 2) |
307
+
308
+ ---
309
+
310
+ ### `sdds_sim.py`
311
+
312
+ ```python
313
+ Y, My = simulate(F, varF, nv, p, c, nsteps=20, nins=1000,
314
+ noise=0.0, n_jobs=1, seed=None)
315
+ ```
316
+
317
+ Main simulation entry point. Automatically selects clean or noisy mode.
318
+
319
+ | Parameter | Description |
320
+ |-----------|-------------|
321
+ | `F, varF, nv, p` | SDDS structures from `sdds_build` |
322
+ | `c` | Propensity matrix, shape `(2, n)` |
323
+ | `nsteps` | Time steps per trajectory |
324
+ | `nins` | Number of random initializations |
325
+ | `noise` | Global noise per step (0 = clean) |
326
+ | `n_jobs` | Parallel workers (`-1` = all cores) |
327
+ | `seed` | Integer for reproducibility |
328
+
329
+ **Returns:**
330
+ - `Y`: `(n, nsteps+1)` — averaged expression frequencies
331
+ - `My`: `list` of per-run state matrices, each `(nsteps+1, n)`
332
+
333
+ Lower-level functions also available:
334
+ ```python
335
+ sdds_sim(F, varF, nv, p, c, n, nsteps, nins) # no noise
336
+ sdds_sim_noise(g, F, varF, nv, p, c, n, nsteps, nins) # with noise
337
+ sdds_run(x0, F, varF, nv, p, c, nsteps) # single trajectory
338
+ sdds_run_noise(g, x0, F, varF, nv, p, c, nsteps) # single noisy trajectory
339
+ sdds_next_state(x, F, varF, nv, p, c) # one step
340
+ ```
341
+
342
+ ---
343
+
344
+ ### `truth_table_mutations.py`
345
+
346
+ #### `fix_node` — recommended for node mutations and controls
347
+
348
+ ```python
349
+ FF = fix_node(F, nv, p, node, v)
350
+ ```
351
+
352
+ Locks node `node` (1-indexed) to constant value `v` by overwriting its
353
+ F column. Equivalent to `f(i) = v` before `SDDS_Build` in MATLAB.
354
+
355
+ ```python
356
+ FF = fix_node(F, nv, p=2, node=3, v=1) # KRAS = 1 (gain-of-function)
357
+ FF = fix_node(F, nv, p=2, node=9, v=0) # RAF inhibition
358
+ FF = fix_node(F, nv, p=2, node=2, v=0) # LKB1 loss of function
359
+ ```
360
+
361
+ #### `fix_nodes` — batch node mutation
362
+
363
+ ```python
364
+ FF = fix_nodes(F, nv, p, node_value_pairs=[
365
+ (3, 1), # KRAS = 1
366
+ (2, 0), # LKB1 = 0
367
+ (1, 0), # KEAP1 = 0
368
+ ])
369
+ ```
370
+
371
+ #### `delete_edge` — edge-level structural control
372
+
373
+ ```python
374
+ FF = delete_edge(F, nv, varF, p, tail=5, head=7, v=0)
375
+ ```
376
+
377
+ Removes the structural influence of node `tail` on `head` by fixing
378
+ the tail input to `v` in head's truth table. Use for edge-specific
379
+ perturbations where the node itself should remain functional.
380
+
381
+ #### `delete_node` — structural node removal
382
+
383
+ ```python
384
+ FF = delete_node(F, nv, varF, p, node=3, v=0)
385
+ ```
386
+
387
+ Removes all outgoing edges from `node` and locks its column to `v`.
388
+ More thorough than `fix_node`. Use when modeling complete gene deletion.
389
+
390
+ #### `apply_mutations` — mixed batch
391
+
392
+ ```python
393
+ FF = apply_mutations(F, nv, varF, p, mutations=[
394
+ {"type": "node", "node": 3, "value": 1},
395
+ {"type": "edge", "tail": 5, "head": 7, "value": 0},
396
+ ])
397
+ ```
398
+
399
+ ---
400
+
401
+ ### `attr_search.py`
402
+
403
+ ```python
404
+ FndAttr, AttrFreq = attr_search(nins, n, Natt, My, Attrs)
405
+ ```
406
+
407
+ Matches simulation endpoints to known attractors via Hamming distance on
408
+ non-oscillating nodes. Only valid for **noise-free** simulations.
409
+
410
+ | Parameter | Description |
411
+ |-----------|-------------|
412
+ | `My` | Output from `simulate()` (noise=0) |
413
+ | `Attrs` | `(n, Natt)` matrix. Column = attractor, value -1 = oscillating node |
414
+
415
+ ```python
416
+ # Load attractor CSV
417
+ Attrs = load_attractors_csv("attractors/WT_attractors.csv")
418
+ Natt = Attrs.shape[1]
419
+ FndAttr, AttrFreq = attr_search(nins, n, Natt, My, Attrs)
420
+
421
+ # Summarize
422
+ summary = summarize_attractors(AttrFreq, nins)
423
+ print(summary)
424
+ ```
425
+
426
+ **Attractor CSV format** — columns = attractors, rows = nodes in order:
427
+ ```
428
+ 0,1,0
429
+ 1,0,-1
430
+ 0,-1,1
431
+ ```
432
+ `-1` marks a node that oscillates in that attractor (excluded from Hamming distance).
433
+
434
+ > **Want to *compute* attractors rather than test against known ones?**
435
+ > `attr_search` checks whether simulation endpoints match a set of attractors
436
+ > *you already supply* — it does not discover them from the rules. To compute
437
+ > attractors/fixed points directly from a network's update rules, see
438
+ > [`pystablemotifs`](https://github.com/jcrozum/pystablemotifs) (Rozum, Deritei,
439
+ > Park, Gómez Tejeda Zañudo, Albert, *pystablemotifs*, *Bioinformatics*, 2021;
440
+ > algorithm: Rozum et al., *Sci. Adv.* 7, eabf8124, 2021), which uses trap-space
441
+ > percolation to compute exact attractors efficiently on real biological
442
+ > networks.
443
+
444
+ ---
445
+
446
+ ### `sweep.py`
447
+
448
+ #### Single-node sweep
449
+
450
+ ```python
451
+ df = sweep_single_nodes(
452
+ F, varF, nv, p, c,
453
+ node_names=NODE_NAMES,
454
+ phenotype_nodes=[33, 34, 35, 36],
455
+ phenotype_labels=["OxyStress", "PRC2", "CC_Survival", "Cell_Death"],
456
+ nsteps=20, nins=1000, noise=0.0,
457
+ values=[0, 1], # test knockout AND overexpression
458
+ nodes_to_sweep=None, # None = all nodes
459
+ n_jobs=-1, # parallel
460
+ seed=42,
461
+ )
462
+ ```
463
+
464
+ Returns a DataFrame with one row per condition (wildtype first), columns
465
+ for each phenotype endpoint.
466
+
467
+ #### Delta analysis
468
+
469
+ ```python
470
+ df_delta = compute_delta(df, phenotype_labels=["OxyStress","PRC2","CC_Survival"])
471
+ ```
472
+
473
+ Adds `delta_<phenotype>` columns showing change from wildtype.
474
+
475
+ #### Combinatorial sweep
476
+
477
+ ```python
478
+ df_combo = sweep_combinations(
479
+ F, varF, nv, p, c,
480
+ node_names=NODE_NAMES,
481
+ phenotype_nodes=[35, 36, 37, 38],
482
+ mutation_sets=[
483
+ [(3,1), (2,0)], # KRAS + LKB1 double
484
+ [(3,1), (1,0)], # KRAS + KEAP1 double
485
+ [(3,1), (2,0), (1,0)], # triple
486
+ ],
487
+ mutation_set_names=["KRAS+LKB1", "KRAS+KEAP1", "Triple"],
488
+ nsteps=20, nins=1000,
489
+ )
490
+ ```
491
+
492
+ #### Pairwise double-mutant screen
493
+
494
+ ```python
495
+ df_pairs = sweep_pairwise(
496
+ F, varF, nv, p, c,
497
+ node_names=NODE_NAMES,
498
+ phenotype_nodes=[35, 36],
499
+ value_a=0, value_b=0, # all double knockouts
500
+ nsteps=20, nins=300, # use lower nins for speed
501
+ )
502
+ ```
503
+
504
+ #### Sweep visualizations
505
+
506
+ ```python
507
+ # Heatmap of delta values
508
+ plot_sweep_heatmap(df_delta, phenotype_labels, delta=True,
509
+ save_path="sweep_heatmap.png")
510
+
511
+ # Ranked bar chart for one phenotype
512
+ plot_sweep_ranked(df, "CC_Survival", top_n=15,
513
+ save_path="ranked_CCsurvival.png")
514
+ ```
515
+
516
+ ---
517
+
518
+ ### `parsers.py`
519
+
520
+ Convert published network files into DynaVista format.
521
+
522
+ ```python
523
+ # BoolNet (.bnet) — most common published format
524
+ rules, names = parse_boolnet("network.bnet")
525
+
526
+ # BooleanNet / pystablemotifs text format
527
+ rules, names = parse_booleannet("network.txt")
528
+
529
+ # Plain text rules (name = rule, one per line)
530
+ rules, names = parse_rules_txt("rules.txt")
531
+
532
+ # Edge list CSV (source, target, sign columns)
533
+ rules, names = parse_adjacency_csv("edges.csv")
534
+
535
+ # Auto-detect format
536
+ rules, names = parse_network("my_file.bnet")
537
+
538
+ # All parsers feed directly into sdds_build
539
+ varF, nv, F = sdds_build(rules, names, p=2)
540
+ ```
541
+
542
+ **BoolNet format** (`network.bnet`):
543
+ ```
544
+ targets, factors
545
+ NodeA, NodeB & NodeC
546
+ NodeB, NodeA | !NodeC
547
+ NodeC, 1
548
+ ```
549
+
550
+ **BooleanNet format** (`network.txt`):
551
+ ```
552
+ NodeA* = NodeB AND NodeC
553
+ NodeB* = NodeA OR NOT NodeC
554
+ NodeC* = True
555
+ ```
556
+
557
+ **Plain text rules** (`rules.txt`):
558
+ ```
559
+ KEAP1 = 1
560
+ LKB1 = 1
561
+ KRAS = 0
562
+ Methionine = Lat1 OR Homocysteine
563
+ ```
564
+
565
+ **Edge list CSV** (`edges.csv`):
566
+ ```
567
+ source,target,sign
568
+ A,B,1
569
+ C,B,-1
570
+ A,C,1
571
+ ```
572
+ Sign values: `1, +1, +, activates` = activation; `-1, -1, -, inhibits` = inhibition.
573
+
574
+ ---
575
+
576
+ ### `markov.py`
577
+
578
+ #### Exact attractor analysis (networks with n ≤ 20)
579
+
580
+ ```python
581
+ A, Avec = bn_asparse(F, varF, nv, p) # sparse transition matrix
582
+ ab, d = bn_attractor(Avec) # attractor labels and distances
583
+ attrs = get_attractor_states(ab, Avec, n, p) # attractor states as binary vectors
584
+ bs = basin_sizes(ab) # basin size per attractor
585
+ ```
586
+
587
+ `ab` encodes: negative values = on attractor (−1 = attractor 1, −2 = attractor 2, ...),
588
+ positive values = in basin of that attractor. `d` = steps to attractor from each state.
589
+
590
+ #### Full stochastic transition matrix (n ≤ 16 recommended)
591
+
592
+ ```python
593
+ A = multistate_A(F, varF, nv, c, p) # p^n × p^n transition matrix
594
+ G = google_matrix(A, g=0.9) # add noise for ergodicity
595
+ pi = stationary_distribution(G) # stationary distribution
596
+ ```
597
+
598
+ #### Scalable stationary distribution (n > 20)
599
+
600
+ For networks too large to enumerate exactly, estimate the dominant attractors
601
+ by sampling. It runs random trajectories, builds a sparse transition matrix
602
+ over the visited states only, applies Google damping, and solves for the
603
+ stationary distribution of that reduced chain — ranking the dominant attractors
604
+ without enumerating 2ⁿ states.
605
+
606
+ > **Note:** this is an attractor-ranking heuristic, not the exact SDDS
607
+ > stationary distribution. It targets the deterministic-plus-damped chain over
608
+ > sampled states; its accuracy plateaus with more samples and the mid-rank
609
+ > probabilities are not expected to match exact values. Use the exact path
610
+ > (`multistate_A` → `stationary_distribution`) when the network is small enough.
611
+
612
+ ```python
613
+ result = stationary_distribution_sampled(
614
+ F, varF, nv, p,
615
+ node_names=node_names,
616
+ n_samples=10000,
617
+ nsteps=300,
618
+ g=0.85,
619
+ top_k=10,
620
+ )
621
+ # result["top_states"]: ranked states with probability and type
622
+ # (fixed point / cycle member); result["n_states_visited"]: distinct states seen
623
+ ```
624
+
625
+ > **Computing attractors from the rules.** dynavista's `attr_search` only tests
626
+ > whether trajectories end in attractors *you supply* — it does not discover
627
+ > them. To compute attractors/fixed points directly from a network's update
628
+ > rules, use [`pystablemotifs`](https://github.com/jcrozum/pystablemotifs)
629
+ > (Rozum et al., *Bioinformatics* 2021; algorithm: Rozum et al., *Sci. Adv.* 7,
630
+ > eabf8124, 2021), which uses trap-space percolation to compute exact
631
+ > attractors efficiently on real biological networks.
632
+
633
+ ---
634
+
635
+ ### `plotting.py`
636
+
637
+ Trajectory plots default to 14pt font and the other plot types to 13pt (all configurable), at 300 DPI with publication-clean axes.
638
+
639
+ ```python
640
+ # Apply publication style globally (do this once at the top of your notebook)
641
+ set_publication_style()
642
+
643
+ # Trajectory plot — shows average node expression over time
644
+ plot_simulation(Y, node_names,
645
+ nodes_to_plot=[33, 34, 35, 36, 37, 38],
646
+ title="KLK Network — Wildtype",
647
+ save_path="trajectory.png")
648
+
649
+ # Endpoint bar chart — shows final time-step frequencies
650
+ plot_endpoint_bar(Y[:, -1], node_names,
651
+ nodes_to_plot=[33, 34, 35, 36],
652
+ title="Phenotype Readouts")
653
+
654
+ # Attractor basin pie + bar
655
+ plot_attractor_basins(AttrFreq, nins,
656
+ attr_labels=["Attractor 1", "Attractor 2"])
657
+
658
+ # Stationary distribution top states
659
+ plot_stationary_distribution(pi, n, p, top_k=20)
660
+
661
+ # Sweep heatmap
662
+ plot_sweep_heatmap(df_delta, phenotype_labels, delta=True)
663
+
664
+ # Sweep ranked bar
665
+ plot_sweep_ranked(df, "CC_Survival", top_n=15)
666
+ ```
667
+
668
+ ---
669
+
670
+ ## 6. Config File Guide
671
+
672
+ A config file defines an entire analysis in one place. It is an ordinary
673
+ Python file (`dynavista_config_*.py`) whose module-level constants are read by
674
+ `run_from_config()`. Every validated network ships one — see
675
+ `examples/TLGL6/dynavista_config_TLGL6.py` for a fully annotated 6-node example,
676
+ or `examples/KLK/dynavista_config_KLK.py` for a 38-node one. Copy one, edit the
677
+ constants, and run it; the file is heavily commented and is the only thing you
678
+ need to edit.
679
+
680
+ ### Minimal config
681
+
682
+ ```python
683
+ # my_config.py
684
+ NETWORK_NAME = "My Network"
685
+ P = 2 # 2 = Boolean
686
+ OUTPUT_DIR = "output"
687
+
688
+ NODE_NAMES = ["A", "B", "C"]
689
+ RULES = ["C", "A", "A OR B"] # one rule per node, same order as NODE_NAMES
690
+
691
+ NINS = 1000 # random initial conditions
692
+ NSTEPS = 20 # SDDS time steps
693
+ NOISE = 0.0 # per-step noise probability
694
+ PROPENSITY = 0.9 # update probability (c value)
695
+ SEED = 42 # int for reproducibility, or None
696
+ ```
697
+
698
+ ### Full config with mutations and phenotypes
699
+
700
+ The example configs group settings into clearly commented blocks. The most
701
+ commonly edited ones:
702
+
703
+ ```python
704
+ NETWORK_NAME = "KLK Network"
705
+ P = 2
706
+ OUTPUT_DIR = "klk_output"
707
+
708
+ NODE_NAMES = ["KEAP1", "LKB1", "KRAS", ...] # 38 total
709
+ RULES = ["1", "1", "0", ...] # one per node
710
+
711
+ # Simulation
712
+ NINS = 3000
713
+ NSTEPS = 20
714
+ NOISE = 0.01
715
+ PROPENSITY = 0.9
716
+ N_JOBS = -1 # -1 = all CPU cores
717
+ SEED = None
718
+
719
+ # Mutations: 'exhaustive', 'manual', or 'off'
720
+ # In 'manual' mode, each entry is a {node_id: value} dict (node IDs are
721
+ # 1-indexed). An empty dict {} is the wildtype (no mutations).
722
+ MUTATION_MODE = 'manual'
723
+ MUTATION_MANUAL = [
724
+ {}, # wildtype (no mutations)
725
+ {3: 1}, # node 3 -> ON
726
+ {3: 1, 2: 0}, # node 3 ON, node 2 OFF
727
+ ]
728
+
729
+ # Phenotype reads: (1-indexed node, label)
730
+ PHENOTYPE_NODES = [
731
+ (33, "Oxidative Stress"),
732
+ (35, "Cell Survival"),
733
+ (36, "Cell Death"),
734
+ (37, "PDL1"),
735
+ ]
736
+ PLOT_NODES = [33, 34, 35, 36, 37, 38]
737
+
738
+ # Attractor search against a supplied CSV (None to skip)
739
+ ATTRACTOR_CSV = None
740
+ ```
741
+
742
+ ### Running
743
+
744
+ ```python
745
+ from dynavista import run_from_config
746
+
747
+ results = run_from_config("my_config.py", verbose=True,
748
+ save_figures=True, show_figures=False)
749
+
750
+ # Access results (keyed by condition name). The wildtype entry ({}) is keyed
751
+ # "wildtype"; other conditions use names generated from their mutations.
752
+ # Inspect the keys to see the exact names for your run:
753
+ print([k for k in results if not k.startswith("_")])
754
+
755
+ Y_wt = results["wildtype"]["Y"]
756
+ phenotype = results["wildtype"]["phenotype"] # dict of endpoint values
757
+ ```
758
+
759
+ `run_from_config()` reads every setting from the file, builds the SDDS
760
+ structures, simulates each mutation and control condition, optionally runs the
761
+ sampled stationary-distribution analysis and the perturbation sweep, saves
762
+ figures to `OUTPUT_DIR`, and returns a structured results dict.
763
+
764
+ ---
765
+
766
+ ## 7. Network Format Guide
767
+
768
+ | Format | Extension | Use case |
769
+ |--------|-----------|----------|
770
+ | BoolNet | `.bnet` | Published models (GINsim, BioModels, Cell Collective) |
771
+ | BooleanNet | `.txt` | pystablemotifs, BooleanNet, BoolSim |
772
+ | Plain rules | `.txt` | DynaVista-native, easiest for new networks |
773
+ | Adjacency list | `.csv` | STRING, SIGNOR, literature curation |
774
+ | Truth table | `.csv` | Precomputed F columns (auto-detected by `parse_network`) |
775
+ | Polynomial | inline `list[str]` | Direct from MATLAB SMATA pipeline |
776
+
777
+ ```python
778
+ # From any format → sdds_build → simulate
779
+ from dynavista import parse_network, sdds_build, simulate
780
+
781
+ rules, names = parse_network("my_model.bnet")
782
+ varF, nv, F = sdds_build(rules, names, p=2)
783
+ Y, My = simulate(F, varF, nv, p=2, c=0.9*np.ones((2,len(names))),
784
+ nsteps=20, nins=1000)
785
+ ```
786
+
787
+ ---
788
+
789
+ ## 8. Mutation and Control Guide
790
+
791
+ ### When to use each function
792
+
793
+ | Situation | Function |
794
+ |-----------|----------|
795
+ | Lock node to 0 or 1 (knock out / overexpress) | `fix_node` |
796
+ | Multiple node changes at once | `fix_nodes` |
797
+ | Remove one specific edge between two nodes | `delete_edge` |
798
+ | Complete structural removal of a node | `delete_node` |
799
+ | Mixed node + edge changes | `apply_mutations` |
800
+ | In a config file | `MUTATION_MANUAL` / `MUTATION_MODE` |
801
+
802
+ ### Method equivalence
803
+
804
+ All three methods produce **identical F**:
805
+
806
+ ```python
807
+ # Method A — fix_node (recommended, most concise)
808
+ FF = fix_node(F, nv, p=2, node=3, v=1)
809
+
810
+ # Method B — pre-build (most transparent, matches original MATLAB)
811
+ rules_mut = rules.copy()
812
+ rules_mut[2] = "1" # index 2 = x3 (0-based)
813
+ _, _, FF = sdds_build(rules_mut, names, p=2)
814
+
815
+ # Method C — in a dynavista_config_*.py file
816
+ # MUTATION_MODE = 'manual'
817
+ # MUTATION_MANUAL = [
818
+ # {3: 1}, # node 3 (1-indexed) -> ON
819
+ # ]
820
+ ```
821
+
822
+ ### Common mutation patterns
823
+
824
+ ```python
825
+ # NSCLC mutation panel
826
+ F_WT = F.copy()
827
+ F_KRAS_mut = fix_node(F, nv, p=2, node=3, v=1)
828
+ F_LKB1_ko = fix_node(F, nv, p=2, node=2, v=0)
829
+ F_KEAP1_ko = fix_node(F, nv, p=2, node=1, v=0)
830
+ F_double = fix_nodes(F, nv, p=2, node_value_pairs=[(3,1),(2,0)])
831
+ F_triple = fix_nodes(F, nv, p=2, node_value_pairs=[(3,1),(2,0),(1,0)])
832
+
833
+ # Therapeutic controls
834
+ F_RAFi = fix_node(F, nv, p=2, node=9, v=0)
835
+ F_MEKi = fix_node(F, nv, p=2, node=15, v=0)
836
+ F_combo = fix_nodes(F, nv, p=2, node_value_pairs=[(3,1),(9,0)]) # KRAS mut + RAFi
837
+ ```
838
+
839
+ ---
840
+
841
+ ## 9. Mutation Sweep Guide
842
+
843
+ ### Screen all single-node knockouts
844
+
845
+ ```python
846
+ from dynavista import sweep_single_nodes, compute_delta, plot_sweep_heatmap
847
+
848
+ df = sweep_single_nodes(
849
+ F, varF, nv, p=2, c=c,
850
+ node_names=NODE_NAMES,
851
+ phenotype_nodes=[35, 36, 37, 38],
852
+ phenotype_labels=["CC_Survival","Cell_Death","PDL1","IFNg"],
853
+ nsteps=20, nins=1000,
854
+ values=[0], # knockout only
855
+ n_jobs=-1, seed=42,
856
+ )
857
+
858
+ df_delta = compute_delta(df, ["CC_Survival","Cell_Death","PDL1","IFNg"])
859
+
860
+ # Heatmap of all knockouts vs phenotype
861
+ plot_sweep_heatmap(df_delta, ["CC_Survival","Cell_Death","PDL1","IFNg"],
862
+ title="Single-Node Knockout Screen",
863
+ save_path="knockout_screen.png")
864
+
865
+ # Which knockout most increases CC_Survival?
866
+ plot_sweep_ranked(df, "CC_Survival", target_value=0, top_n=15,
867
+ save_path="ranked_survival.png")
868
+ ```
869
+
870
+ ### Save sweep results
871
+
872
+ ```python
873
+ df.to_csv("sweep_results.csv", index=False)
874
+ df_delta.to_csv("sweep_delta.csv", index=False)
875
+ ```
876
+
877
+ ---
878
+
879
+ ## 10. Markov Chain Guide
880
+
881
+ ### Small networks (n ≤ 20) — exact analysis
882
+
883
+ ```python
884
+ from dynavista import bn_asparse, bn_attractor, get_attractor_states, basin_sizes
885
+
886
+ A, Avec = bn_asparse(F, varF, nv, p=2)
887
+ ab, d = bn_attractor(Avec)
888
+
889
+ attrs = get_attractor_states(ab, Avec, n, p=2)
890
+ for k, states in attrs.items():
891
+ print(f"Attractor {k}: {[list(s) for s in states]}")
892
+
893
+ bs = basin_sizes(ab)
894
+ for k, size in bs.items():
895
+ print(f"Attractor {k} basin: {size} states ({100*size/2**n:.1f}%)")
896
+ ```
897
+
898
+ ### Small networks — stationary distribution
899
+
900
+ ```python
901
+ from dynavista import multistate_A, google_matrix, stationary_distribution
902
+
903
+ A = multistate_A(F, varF, nv, c, p=2) # exact transition matrix
904
+ G = google_matrix(A, g=0.9) # regularize for Perron-Frobenius
905
+ pi = stationary_distribution(G) # stationary probabilities
906
+
907
+ # Top 10 states by stationary weight
908
+ top_idx = pi.argsort()[::-1][:10]
909
+ for i in top_idx:
910
+ state = dec2multistate(i, p=2, n=n)
911
+ print(f"State {i}: {list(state)} pi={pi[i]:.4f}")
912
+ ```
913
+
914
+ ### Large networks — sampling
915
+
916
+ ```python
917
+ from dynavista import stationary_distribution_sampled
918
+
919
+ result = stationary_distribution_sampled(
920
+ F, varF, nv, p=2, node_names=node_names,
921
+ n_samples=10000, nsteps=300, g=0.85, top_k=5,
922
+ )
923
+ for s in result["top_states"]:
924
+ on = [k for k, v in s["state_labels"].items() if v == 1]
925
+ print(f"rank {s['rank']}: p={s['probability']:.3f} ({s['type']}) ON: {on}")
926
+ ```
927
+
928
+ ---
929
+
930
+ ## 11. Scalability Guide
931
+
932
+ | Network size | Recommended approach | Notes |
933
+ |---|---|---|
934
+ | n ≤ 12 | Full Markov chain (`multistate_A`) | Dense p^n × p^n matrix; fits comfortably in memory |
935
+ | n ≤ 38 | Simulation (`simulate`) | e.g. KLK (n=38): ~5s for 3000 runs × 20 steps |
936
+ | n ≤ 69 | Simulation (`simulate`) | e.g. PCC_large (n=69): ~8s for 3000 runs × 20 steps; ~35s for 1000 runs × 300 steps |
937
+ | n > 69 | `simulate` with `n_jobs=-1` | Parallelize across all CPU cores |
938
+ | Large n, long-run behaviour | `stationary_distribution_sampled` | Sampling-based attractor ranking (see §10) |
939
+
940
+ ### Speeding up large simulations
941
+
942
+ ```python
943
+ # Use all available CPU cores
944
+ Y, My = simulate(F, varF, nv, p=2, c=c,
945
+ nsteps=20, nins=5000,
946
+ n_jobs=-1)
947
+
948
+ # Reduce nins for sweeps (500 is often sufficient for ranking)
949
+ df = sweep_single_nodes(..., nins=500, n_jobs=-1)
950
+ ```
951
+
952
+ ---
953
+
954
+ ## 12. MATLAB Equivalence Table
955
+
956
+ | MATLAB | Python (DynaVista) |
957
+ |--------|----------------|
958
+ | `SDDS_Build(syms, f, p)` | `sdds_build(rules, names, p)` |
959
+ | `SDDS_sim(F, varF, nv, p, c, n, nsteps, nins)` | `simulate(F, varF, nv, p, c, nsteps, nins)` |
960
+ | `SDDS_simNoise(g, F, varF, nv, p, c, n, nsteps, nins)` | `simulate(F, varF, nv, p, c, nsteps, nins, noise=g)` |
961
+ | `SDDSRun(x, F, varF, nv, p, c, nsteps)` | `sdds_run(x, F, varF, nv, p, c, nsteps)` |
962
+ | `SDDSRunNoise(g, x, F, ...)` | `sdds_run_noise(g, x, F, ...)` |
963
+ | `SDDSNextState(x, F, varF, nv, p, c)` | `sdds_next_state(x, F, varF, nv, p, c)` |
964
+ | `f(i) = v` before Build | `fix_node(F, nv, p, i, v)` |
965
+ | Multiple `f(i) = v` | `fix_nodes(F, nv, p, [(i,v), ...])` |
966
+ | `TruthTable_del_n_temp(...)` | `delete_node(F, nv, varF, p, node, v)` |
967
+ | `TruthTable_del_a_temp(...)` | `delete_edge(F, nv, varF, p, tail, head, v)` |
968
+ | `AttrSearch(nins, n, Natt, My, Attrs)` | `attr_search(nins, n, Natt, My, Attrs)` |
969
+ | `bnAsparse(F, varF, nv)` | `bn_asparse(F, varF, nv, p)` |
970
+ | `bnAttractor(Avec)` | `bn_attractor(Avec)` |
971
+ | `multistateA(F, varF, nv, c, p)` | `multistate_A(F, varF, nv, c, p)` |
972
+ | `dec2multistate(y, p, n)` | `dec2multistate(y, p, n)` |
973
+ | `multistate2dec(x, p, n)` | `multistate2dec(x, p, n)` |
974
+ | `dtmc(G); asymptotics(mc)` | `stationary_distribution(G)` |
975
+ | `figure; plot(X, Y(i,:), ...)` | `plot_simulation(Y, names, nodes_to_plot=[i])` |
976
+ | (no equivalent) | `run_from_config("dynavista_config.py")` |
977
+ | (no equivalent) | `sweep_single_nodes(...)` |
978
+ | (no equivalent) | `parse_boolnet(...)` |
979
+
980
+ ---
981
+
982
+ ## 13. Citation
983
+
984
+ If you use this software in your research, please cite the accompanying
985
+ publication. Citation details (BibTeX and full reference) will be added here
986
+ once the manuscript is published.
987
+
988
+ <!-- TODO: add published citation (BibTeX + reference) at publication time. -->
989
+
990
+ ---
991
+
992
+ ## License
993
+
994
+ MIT License. See LICENSE file.