255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451 | def plot_subgraph(
self,
seed: str,
gene_col: str = "symbol",
max_genes: int = 10,
only: float = 0.3,
palette: List[str] = base_color_palette,
interactive: bool = True,
do_enr: bool = False,
color_overlap: pd.DataFrame | None = None,
node_size: int = 3000,
font_size: int = 14,
**kwargs: dict,
):
"""
plot_subgraph plots a subgraph of the gene regulatory network (GRN) centered around a seed gene.
Args:
seed (str or list): The seed gene or list of genes around which the subgraph will be centered.
gene_col (str, optional): The column name in the .var DataFrame that contains gene identifiers. Defaults to "symbol".
max_genes (int, optional): The maximum number of genes to include in the subgraph. Defaults to 10.
only (float, optional): The threshold for filtering connections. If less than 1, it is used as a minimum weight threshold. If 1 or greater, it is used as the number of top connections to retain. Defaults to 0.3.
palette (list, optional): The color palette to use for plotting. Defaults to base_color_palette.
interactive (bool, optional): Whether to create an interactive plot. Defaults to True.
do_enr (bool, optional): Whether to perform enrichment analysis on the subgraph. Defaults to False.
color_overlap (pd.DataFrame | None, optional): A DataFrame with geneA, geneB, and value columns to color edges based on overlap. Defaults to None.
Returns:
d3graph or None: The d3graph object if interactive is True, otherwise None.
"""
rn = {k: v for k, v in self.var[gene_col].items()}
if type(seed) is str:
gene_id = self.var[self.var[gene_col] == seed].index[0]
elem = (
self.grn.loc[gene_id]
.sort_values(ascending=False)
.head(max_genes)
.index.tolist()
)
if gene_id not in elem:
elem += [gene_id]
else:
elem = seed
mat = self.grn.loc[elem, elem].rename(columns=rn).rename(index=rn)
if only < 1:
mat[mat < only] = 0
else:
top_connections = mat.stack().nlargest(only)
top_connections.index.names = ["Gene1", "Gene2"]
top_connections.name = "Weight"
top_connections = top_connections.reset_index()
mat.index.name += "_2"
# Set anything not in the top N connections to 0
mask = mat.stack().isin(
top_connections.set_index(["Gene1", "Gene2"])["Weight"]
)
mat[~mask.unstack()] = 0
mat = mat * 100
color = [palette[0]] * len(mat)
if type(seed) is str:
color[mat.columns.get_loc(seed)] = palette[1]
mat = mat.T
if color_overlap is not None:
import matplotlib.cm as cm
import matplotlib.colors as mcolors
# Create a mapping from (geneA, geneB) to value
edge_colors = {}
for _, row in color_overlap.iterrows():
edge_colors[(row["geneA"], row["geneB"])] = row["value"]
# Get min and max values for normalization
values = color_overlap["value"].values
vmin, vmax = values.min(), values.max()
# Create viridis colormap and normalizer
cmap = cm.get_cmap("viridis")
norm = mcolors.Normalize(vmin=vmin, vmax=vmax)
# print(mat)
# print(color)
if interactive:
d3 = d3graph()
d3.graph(mat, color=None)
d3.set_node_properties(color=color, fontcolor="#000000", **kwargs)
d3.set_edge_properties(directed=True)
for i, gene1 in enumerate(mat.index):
for j, gene2 in enumerate(mat.columns):
if mat.iloc[i, j] != 0 and gene1 != gene2:
if (gene1, gene2) in edge_colors:
rgba = cmap(norm(edge_colors[(gene1, gene2)]))
hex_color = mcolors.rgb2hex(rgba)
d3.edge_properties[(gene1, gene2)]["color"] = hex_color
else:
d3.edge_properties[(gene1, gene2)][
"color"
] = "#808080" # Default gray
d3.show(notebook=True)
return d3
else:
# Create a graph from the DataFrame
G = nx.from_pandas_adjacency(mat, create_using=nx.DiGraph())
# Draw the graph
plt.figure(figsize=(15, 15)) # Increase the size of the plot
# Use spring layout with adjusted parameters for better spacing
pos = nx.spring_layout(G, k=2.0, iterations=50, seed=42)
# Or try kamada_kawai layout for better node distribution
# pos = nx.kamada_kawai_layout(G)
# Draw nodes with larger size
nx.draw_networkx_nodes(
G, pos, node_size=node_size, node_color=color, alpha=0.6
)
if color_overlap is not None:
# For networkx plotting
edge_colors_nx = []
for edge in G.edges():
if edge in edge_colors:
edge_colors_nx.append(cmap(norm(edge_colors[edge])))
elif (edge[1], edge[0]) in edge_colors: # Check reverse direction
edge_colors_nx.append(
cmap(norm(edge_colors[(edge[1], edge[0])]))
)
else:
edge_colors_nx.append("#808080") # Default gray
# Draw edges with transparency
nx.draw_networkx_edges(
G,
pos,
alpha=0.7,
width=1.5,
edge_color=edge_colors_nx,
arrows=True,
edge_cmap=cmap,
node_size=node_size,
connectionstyle="arc3,rad=0.1",
min_source_margin=15,
min_target_margin=15,
)
# Add colorbar
sm = cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ax=plt.gca(), label="Overlap Value")
else:
nx.draw_networkx_edges(
G,
pos,
alpha=0.7,
width=1.5,
arrows=True,
node_size=node_size,
connectionstyle="arc3,rad=0.1",
min_source_margin=15,
min_target_margin=15,
)
# Draw labels with better formatting
nx.draw_networkx_labels(
G,
pos,
font_size=font_size,
font_weight="bold",
font_family="sans-serif",
bbox=dict(
boxstyle="round,pad=0.3",
facecolor="white",
edgecolor="none",
alpha=0.7,
),
)
plt.axis("off")
plt.tight_layout()
plt.show()
if do_enr:
enr = gp.enrichr(
gene_list=list(G.nodes),
gene_sets=[
"KEGG_2021_Human",
"MSigDB_Hallmark_2020",
"Reactome_2022",
"Tabula_Sapiens",
"WikiPathway_2023_Human",
"TF_Perturbations_Followed_by_Expression",
"Reactome",
"PPI_Hub_Proteins",
"OMIM_Disease",
"GO_Molecular_Function_2023",
],
organism="Human", # change accordingly
# description='pathway',
# cutoff=0.08, # test dataset, use lower value for real case
background=self.var.symbol.tolist(),
)
print(enr.res2d.head(20))
return G
|