pathview-plus 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pathview/examples.py ADDED
@@ -0,0 +1,342 @@
1
+ """
2
+ examples.py
3
+ Comprehensive examples demonstrating pathview.py features including the new
4
+ SBGNview-inspired additions: SVG rendering, highlighting, and spline curves.
5
+
6
+ Run these examples to explore all capabilities.
7
+ """
8
+
9
+ import polars as pl
10
+ from pathview import (
11
+ pathview,
12
+ highlight_nodes,
13
+ highlight_edges,
14
+ highlight_path,
15
+ cubic_bezier,
16
+ kegg_legend,
17
+ sim_mol_data,
18
+ )
19
+
20
+
21
+ # ===========================================================================
22
+ # Example 1: Basic pathway visualization (PNG output)
23
+ # ===========================================================================
24
+
25
+ def example_basic_png():
26
+ """Most common use case: overlay expression data on KEGG pathway (PNG)."""
27
+ print("\n" + "="*70)
28
+ print("Example 1: Basic pathway visualization (PNG)")
29
+ print("="*70)
30
+
31
+ # Simulated data
32
+ gene_df = sim_mol_data(mol_type="gene", species="hsa", n_mol=100, n_exp=1)
33
+
34
+ result = pathview(
35
+ pathway_id="04110", # Cell cycle
36
+ gene_data=gene_df,
37
+ species="hsa",
38
+ output_format="png", # Default
39
+ out_suffix="example1_basic",
40
+ )
41
+ print("✓ Generated: hsa04110.example1_basic.png")
42
+
43
+
44
+ # ===========================================================================
45
+ # Example 2: SVG output (vector graphics)
46
+ # ===========================================================================
47
+
48
+ def example_svg_output():
49
+ """NEW: Generate scalable SVG instead of pixel-based PNG."""
50
+ print("\n" + "="*70)
51
+ print("Example 2: SVG vector output")
52
+ print("="*70)
53
+
54
+ gene_df = sim_mol_data(mol_type="gene", species="hsa", n_mol=100, n_exp=1)
55
+
56
+ result = pathview(
57
+ pathway_id="04110",
58
+ gene_data=gene_df,
59
+ species="hsa",
60
+ output_format="svg", # NEW: SVG mode
61
+ out_suffix="example2_svg",
62
+ )
63
+ print("✓ Generated: hsa04110.example2_svg.svg")
64
+ print(" → Open in browser or vector graphics editor")
65
+ print(" → Scalable, smaller file size, web-native")
66
+
67
+
68
+ # ===========================================================================
69
+ # Example 3: Multi-condition comparison
70
+ # ===========================================================================
71
+
72
+ def example_multi_condition():
73
+ """Visualize multiple experimental conditions side-by-side."""
74
+ print("\n" + "="*70)
75
+ print("Example 3: Multi-condition comparison")
76
+ print("="*70)
77
+
78
+ # Three experimental conditions
79
+ gene_df = sim_mol_data(mol_type="gene", species="hsa", n_mol=150, n_exp=3)
80
+ gene_df = gene_df.rename({
81
+ "exp1": "Control",
82
+ "exp2": "Treatment_A",
83
+ "exp3": "Treatment_B",
84
+ })
85
+
86
+ result = pathview(
87
+ pathway_id="04010", # MAPK signaling
88
+ gene_data=gene_df,
89
+ species="hsa",
90
+ out_suffix="example3_multistate",
91
+ limit={"gene": 2.0, "cpd": 1.0},
92
+ )
93
+ print("✓ Each node is sliced into 3 color bands (one per condition)")
94
+
95
+
96
+ # ===========================================================================
97
+ # Example 4: Custom color scales
98
+ # ===========================================================================
99
+
100
+ def example_custom_colors():
101
+ """Use custom color schemes (e.g., ColorBrewer palettes)."""
102
+ print("\n" + "="*70)
103
+ print("Example 4: Custom color scales")
104
+ print("="*70)
105
+
106
+ gene_df = sim_mol_data(mol_type="gene", species="hsa", n_mol=100, n_exp=1)
107
+
108
+ result = pathview(
109
+ pathway_id="04151", # PI3K-Akt signaling
110
+ gene_data=gene_df,
111
+ species="hsa",
112
+ out_suffix="example4_custom_colors",
113
+ low={"gene": "#2166AC", "cpd": "#4575B4"}, # Blue scale
114
+ mid={"gene": "#F7F7F7", "cpd": "#F7F7F7"}, # White
115
+ high={"gene": "#D6604D", "cpd": "#B2182B"}, # Red scale
116
+ limit={"gene": 2.5, "cpd": 1.5},
117
+ )
118
+ print("✓ ColorBrewer RdBu diverging palette applied")
119
+
120
+
121
+ # ===========================================================================
122
+ # Example 5: Highlighting (NEW feature)
123
+ # ===========================================================================
124
+
125
+ def example_highlighting():
126
+ """
127
+ NEW: Layer-by-layer modifications after rendering.
128
+ Highlight specific genes, edges, or paths without re-rendering.
129
+ """
130
+ print("\n" + "="*70)
131
+ print("Example 5: Highlighting with composable layers")
132
+ print("="*70)
133
+
134
+ gene_df = pl.DataFrame({
135
+ "entrez": ["1956", "2099", "5594", "207", "4609"],
136
+ "lfc": [ 2.3, -1.1, 1.8, -0.5, 3.1],
137
+ })
138
+
139
+ # Base visualization
140
+ result = pathview(
141
+ pathway_id="04010",
142
+ gene_data=gene_df,
143
+ species="hsa",
144
+ out_suffix="example5_base",
145
+ )
146
+
147
+ # Apply highlighting layers (ggplot2-style)
148
+ print("\nApplying highlighting layers...")
149
+ print(" 1. Highlight EGFR and ESR1 in red")
150
+ print(" 2. Highlight edge between them in blue")
151
+ print(" 3. Highlight entire MAPK cascade path in orange")
152
+
153
+ # Note: Highlighting requires PathwayResult object which we'll implement fully
154
+ # This is a preview of the API design
155
+ # highlighted = (
156
+ # result
157
+ # + highlight_nodes(["1956", "2099"], color="red", width=4)
158
+ # + highlight_edges([("1956", "2099")], color="blue", width=3)
159
+ # + highlight_path(["1956", "2099", "5594"], color="orange")
160
+ # )
161
+ # highlighted.save("hsa04010.example5_highlighted.png")
162
+
163
+ print("✓ Highlighting API demonstrated (full implementation pending)")
164
+
165
+
166
+ # ===========================================================================
167
+ # Example 6: Gene symbol IDs
168
+ # ===========================================================================
169
+
170
+ def example_gene_symbols():
171
+ """Use gene symbols instead of Entrez IDs."""
172
+ print("\n" + "="*70)
173
+ print("Example 6: Gene symbol IDs")
174
+ print("="*70)
175
+
176
+ gene_df = pl.DataFrame({
177
+ "symbol": ["TP53", "EGFR", "KRAS", "PIK3CA", "AKT1"],
178
+ "lfc": [ -1.8, 2.4, 1.1, 1.5, 0.9],
179
+ })
180
+
181
+ result = pathview(
182
+ pathway_id="04151",
183
+ gene_data=gene_df,
184
+ species="hsa",
185
+ gene_idtype="SYMBOL", # Automatic conversion to Entrez
186
+ out_suffix="example6_symbols",
187
+ )
188
+ print("✓ Symbols automatically converted via MyGene.info")
189
+
190
+
191
+ # ===========================================================================
192
+ # Example 7: Combined gene + metabolite data
193
+ # ===========================================================================
194
+
195
+ def example_gene_plus_compound():
196
+ """Overlay both gene expression and metabolite abundance."""
197
+ print("\n" + "="*70)
198
+ print("Example 7: Combined gene + metabolite data")
199
+ print("="*70)
200
+
201
+ gene_df = sim_mol_data(mol_type="gene", species="hsa", n_mol=80, n_exp=1)
202
+ cpd_df = sim_mol_data(mol_type="cpd", n_mol=30, n_exp=1)
203
+
204
+ result = pathview(
205
+ pathway_id="00010", # Glycolysis / Gluconeogenesis
206
+ gene_data=gene_df,
207
+ cpd_data=cpd_df,
208
+ species="hsa",
209
+ out_suffix="example7_gene_cpd",
210
+ limit={"gene": 2.0, "cpd": 1.5},
211
+ low={"gene": "green", "cpd": "blue"},
212
+ high={"gene": "red", "cpd": "yellow"},
213
+ )
214
+ print("✓ Gene (rectangles) and compound (ellipses) overlays combined")
215
+
216
+
217
+ # ===========================================================================
218
+ # Example 8: Graph layout mode (no PNG background)
219
+ # ===========================================================================
220
+
221
+ def example_graph_layout():
222
+ """Use NetworkX graph layout instead of KEGG PNG background."""
223
+ print("\n" + "="*70)
224
+ print("Example 8: Graph layout mode (PDF output)")
225
+ print("="*70)
226
+
227
+ gene_df = sim_mol_data(mol_type="gene", species="hsa", n_mol=100, n_exp=1)
228
+
229
+ result = pathview(
230
+ pathway_id="04010",
231
+ gene_data=gene_df,
232
+ species="hsa",
233
+ kegg_native=False, # Switch to graph mode
234
+ output_format="pdf",
235
+ out_suffix="example8_graph",
236
+ )
237
+ print("✓ Generated: hsa04010.example8_graph.pdf")
238
+ print(" → NetworkX layout with Seaborn styling")
239
+
240
+
241
+ # ===========================================================================
242
+ # Example 9: Spline curves (NEW)
243
+ # ===========================================================================
244
+
245
+ def example_spline_curves():
246
+ """
247
+ NEW: Demonstrate Bezier curve generation.
248
+ (Future: integrate into pathway edge rendering)
249
+ """
250
+ print("\n" + "="*70)
251
+ print("Example 9: Spline curves (Bezier paths)")
252
+ print("="*70)
253
+
254
+ import matplotlib.pyplot as plt
255
+
256
+ # Generate cubic Bezier curve
257
+ curve = cubic_bezier(
258
+ p0=(0, 0), # Start
259
+ p1=(1, 2), # Control point 1
260
+ p2=(3, 2), # Control point 2
261
+ p3=(4, 0), # End
262
+ n_points=100
263
+ )
264
+
265
+ plt.figure(figsize=(8, 4))
266
+ plt.plot(curve[:, 0], curve[:, 1], 'b-', linewidth=2, label='Cubic Bezier')
267
+ plt.plot([0, 1, 3, 4], [0, 2, 2, 0], 'ro--', alpha=0.5, label='Control points')
268
+ plt.title("Bezier Curve Example")
269
+ plt.legend()
270
+ plt.grid(True, alpha=0.3)
271
+ plt.axis('equal')
272
+ plt.tight_layout()
273
+ plt.savefig("example9_bezier_curve.png", dpi=150)
274
+ plt.close()
275
+
276
+ print("✓ Generated: example9_bezier_curve.png")
277
+ print(" → Smooth curves for aesthetic edge routing")
278
+ print(" → Future: automatic edge routing with obstacle avoidance")
279
+
280
+
281
+ # ===========================================================================
282
+ # Example 10: Display KEGG legend
283
+ # ===========================================================================
284
+
285
+ def example_legend():
286
+ """Show the KEGG pathway element legend."""
287
+ print("\n" + "="*70)
288
+ print("Example 10: KEGG pathway legend")
289
+ print("="*70)
290
+
291
+ # This displays an interactive legend
292
+ # kegg_legend(legend_type="both") # Uncomment to show interactive plot
293
+
294
+ print("✓ Run kegg_legend() to see node/edge reference diagram")
295
+
296
+
297
+ # ===========================================================================
298
+ # Run all examples
299
+ # ===========================================================================
300
+
301
+ if __name__ == "__main__":
302
+ print("\n" + "="*70)
303
+ print("PATHVIEW.PY COMPREHENSIVE EXAMPLES")
304
+ print("="*70)
305
+ print("\nThis script demonstrates all features including new SBGNview additions:")
306
+ print(" • SVG vector output")
307
+ print(" • Highlighting layers")
308
+ print(" • Spline curves")
309
+ print(" • Multi-condition visualization")
310
+ print(" • Custom color schemes")
311
+ print(" • Gene + metabolite overlays")
312
+
313
+ try:
314
+ example_basic_png()
315
+ example_svg_output()
316
+ example_multi_condition()
317
+ example_custom_colors()
318
+ example_highlighting()
319
+ example_gene_symbols()
320
+ example_gene_plus_compound()
321
+ example_graph_layout()
322
+ example_spline_curves()
323
+ example_legend()
324
+
325
+ print("\n" + "="*70)
326
+ print("✓ All examples completed successfully!")
327
+ print("="*70)
328
+ print("\nCheck the current directory for output files:")
329
+ print(" • hsa04110.example1_basic.png")
330
+ print(" • hsa04110.example2_svg.svg")
331
+ print(" • hsa04010.example3_multistate.png")
332
+ print(" • hsa04151.example4_custom_colors.png")
333
+ print(" • hsa04010.example5_base.png")
334
+ print(" • hsa04151.example6_symbols.png")
335
+ print(" • hsa00010.example7_gene_cpd.png")
336
+ print(" • hsa04010.example8_graph.pdf")
337
+ print(" • example9_bezier_curve.png")
338
+
339
+ except Exception as e:
340
+ print(f"\n❌ Error: {e}")
341
+ import traceback
342
+ traceback.print_exc()