File size: 7,965 Bytes
d72ec4c
7166938
 
 
0266ad5
7166938
a8123aa
d72ec4c
7166938
d72ec4c
7166938
 
 
 
 
 
b4e28c5
7166938
c224b96
7166938
b4e28c5
 
 
 
 
 
 
 
 
7166938
 
 
 
 
 
 
b32a5a4
 
 
 
7166938
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb2d184
7166938
 
 
 
754f25b
7166938
 
b4e28c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7166938
 
 
 
 
fe0da66
95f9e48
 
 
 
 
3f4efec
7166938
 
 
b4e28c5
9c31df1
b4e28c5
 
 
7166938
 
b4e28c5
d5a2d2d
 
 
7166938
 
 
 
 
 
11a7804
f2018a5
7166938
 
 
 
 
 
 
 
 
 
 
11a7804
7166938
8c5d673
7166938
 
 
 
f0da168
7166938
11a7804
 
00b0789
eddfa89
11a7804
 
 
00b0789
 
eddfa89
11a7804
a8123aa
 
 
 
 
 
75500d1
 
b32a5a4
a8123aa
08e0af6
 
1dc19e6
08e0af6
 
 
a8123aa
 
 
6685cda
 
9610dbd
 
 
 
a8123aa
965ee30
6685cda
1b2d6d6
 
6685cda
80eaa84
6685cda
 
 
08d5702
b092f6a
6685cda
 
 
965ee30
7166938
1b2d6d6
9610dbd
 
7166938
6685cda
 
1b2d6d6
11a7804
4845564
965ee30
7166938
 
 
1ac5d48
 
 
 
 
 
7166938
 
 
 
 
 
 
 
 
 
0266ad5
 
b32a5a4
fc1a145
 
b32a5a4
6ac4757
b32a5a4
9610dbd
1079e63
 
b32a5a4
1079e63
fc1a145
1079e63
0266ad5
 
7166938
965ee30
 
 
3067716
 
 
965ee30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253

import numpy as np
import pandas as pd
import datasets
import streamlit as st
from streamlit_cytoscapejs import st_cytoscapejs
import networkx as nx

st.set_page_config(layout='wide')

# parse out gene_ids from URL query args to it's possible to link to this page
query_params = st.query_params
if "gene_ids" in query_params.keys():
    input_gene_ids = query_params["gene_ids"]
else:
    input_gene_ids = "TGME49_231630,TGME49_230210"
    
# use "\n" as the separator so it shows correctly in the text area
input_gene_ids = input_gene_ids.replace(",", "\n")

if "coexp_score_threshold" in query_params.keys():
    coexp_score_threshold = query_params["coexp_score_threshold"]        
else:
    coexp_score_threshold = "0.85"

if "max_per_gene" in query_params.keys():
    max_per_gene = query_params["max_per_gene"]        
else:
    max_per_gene = "25"

st.markdown("""
# ToxoCEN Network
**ToxoCEN** is a co-expression network for *Toxoplasma gondii* built on 719 RNA-seq runs across 39 studies.
A pair of genes are said to be co-expressed when their expression is correlated across different conditions and
is often a marker for genes to be involved in similar processes. 
To Cite:

    CS Arnold, Y Wang, VB Carruthers, MJ O'Meara
    ToxoCEN: A Co-Expression Network for Toxoplasma gondii

* Code available at https://github.com/maomlab/CalCEN/tree/master/vignettes/ToxoCEN
* Full network and dataset: https://huggingface.co/datasets/maomlab/ToxoCEN
## Plot a network for a set of genes
Put a ``TGME49_######`` gene_id, one each row to seed the network
""")

TGME49_transcript_annotations = datasets.load_dataset(
    path = "maomlab/ToxoCEN",
    data_files = {"TGME49_transcript_annotations": "TGME49_transcript_annotations.tsv"})
TGME49_transcript_annotations = TGME49_transcript_annotations["TGME49_transcript_annotations"].to_pandas()

top_coexp_hits = datasets.load_dataset(
    path = "maomlab/ToxoCEN",
    data_files = {"top_coexp_hits": "top_coexp_hits.tsv"})
top_coexp_hits = top_coexp_hits["top_coexp_hits"].to_pandas()


col1, col2, col3, padding = st.columns(spec = [0.2, 0.2, 0.2, 0.4])
with col1:
    input_gene_ids = st.text_area(
        label = "Gene IDs",
        value = f"{input_gene_ids}",
        height = 130,
        help = "TGME49 Gene IDs e.g. TGME49_231630")


with col2:
    coexp_score_threshold = st.text_input(
        label = "Co-expression threshold [0-1]",
        value = f"{coexp_score_threshold}",
        help = "Default: 0.85")

    try:
        coexp_score_threshold = float(coexp_score_threshold)
    except:
        st.error(f"Co-expression threshold should be a number between 0 and 1, instead it is '{coexp_score_threshold}'")
    if coexp_score_threshold < 0 or 1 < coexp_score_threshold:
        st.error(f"Co-expression threshold should be a number between 0 and 1, instead it is '{coexp_score_threshold}'")

    max_per_gene = st.text_input(
        label = "Max per gene",
        value = f"{max_per_gene}",
        help = "Default: 25")

    try:
        max_per_gene = int(max_per_gene)
    except:
        st.error(f"Max per gene should be a number greater than 0, instead it is '{max_per_gene}'")
    if max_per_gene <= 0:
        st.error(f"Max per gene should be a number greater than 0, instead it is '{max_per_gene}'")
    
    
##################################
# Parse and check the user input #
##################################

seed_gene_ids = []
for input_gene_id in input_gene_ids.split("\n"):
    gene_id = input_gene_id.strip()
    if gene_id == "":
        continue
    else:
        seed_gene_ids.append(gene_id)

neighbors = []
for seed_gene_id in seed_gene_ids:
    hits = top_coexp_hits[
            (top_coexp_hits.gene_id_1 == seed_gene_id) & (top_coexp_hits.coexp_score > coexp_score_threshold)]
    if len(hits.index) > max_per_gene:
        hits = hits[0:max_per_gene]
    neighbors.append(hits)

neighbors = pd.concat(neighbors)
    
neighbor_gene_ids = list(set(neighbors.gene_id_2))
gene_ids = seed_gene_ids + neighbor_gene_ids
gene_types = ['seed'] * len(seed_gene_ids) + ['neighbor'] * len(neighbor_gene_ids)

TGME49_ids = []
gene_names = []
descriptions = []
    
for gene_id in gene_ids:
    try:
        TGME49_id = TGME49_transcript_annotations.loc[TGME49_transcript_annotations["gene_id"] == gene_id]["TGME49_id"].values[0]
        gene_name = TGME49_transcript_annotations.loc[TGME49_transcript_annotations["gene_id"] == gene_id]["gene_name"].values[0]
        description = TGME49_transcript_annotations.loc[TGME49_transcript_annotations["gene_id"] == gene_id]["description"].values[0]
    except:
        st.error(f"Unable to locate TGME49_id for Gene ID: {gene_id}, it should be of the form 'TGME49_######'")
        TGME49_id = None
        gene_name = None
        description = None

    TGME49_ids.append(TGME49_id)
    gene_names.append(gene_name)
    descriptions.append(description)

node_info = pd.DataFrame({
    "gene_index": range(len(gene_ids)),
    "gene_id" : gene_ids,
    "gene_type" : gene_types,
    "TGME49_id": TGME49_ids,
    "gene_name": gene_names,
    "description": descriptions})

neighbors = neighbors.merge(
    right = node_info,
    left_on = "gene_id_1",
    right_on = "gene_id")

neighbors = neighbors.merge(
    right = node_info,
    left_on = "gene_id_2",
    right_on = "gene_id",
    suffixes = ("_a", "_b"))

################################
# Use NetworkX to layout graph #
################################
# note I think CytoscapeJS can layout graphs
# but I'm unsure how to do it through the streamlit-cytoscapejs interface :(

st.write(neighbors)


G = nx.Graph()
for i in range(len(neighbors.index)):
    edge = neighbors.iloc[i]
    G.add_edge(
        edge["gene_index_a"],
        edge["gene_index_b"],
        weight = edge["coexp_score"])
layout = nx.spring_layout(G)




node_color_lut = {
    "seed" : "#4866F0",    # blue
    "neighbor" : "#F0C547" # gold
}

elements = []
singleton_index = 0
for i in range(len(node_info.index)):
    node = node_info.iloc[i]

    if node["gene_index"] in layout.keys():
        layout_x = layout[node["gene_index"]][0] * 600 + 1500/2
        layout_y = layout[node["gene_index"]][1] * 600 + 1500/2
    else:
        layout_x = (singleton_index % 8) * 150 + 100
        layout_y = np.floor(singleton_index / 8) * 50 + 30
        singleton_index += 1

    
    elements.append({
        "data": {
            "id": node["gene_id"],
            "label": node["gene_name"] if node["gene_name"] is not None else node["gene_id"],
            "color": node_color_lut[node["gene_type"]]},
        "position": {
            "x" : layout_x,
            "y" : layout_y}})

for i in range(len(neighbors.index)):
    edge = neighbors.iloc[i]
    elements.append({
        "data" : {
            "source" : edge["gene_id_1"],
            "target" : edge["gene_id_2"],
            "width" :
                20 if edge["coexp_score"] > 0.98 else
                15 if edge["coexp_score"] > 0.93 else
                10 if edge["coexp_score"] > 0.90 else
                8  if edge["coexp_score"] > 0.88 else
                5}})

with col3:
    st.text('') # help alignment with input box
    st.download_button(
        label = "Download as as TSV",
        data = neighbors.to_csv(sep ='\t').encode('utf-8'),
        file_name = f"ToxoCEN_network.tsv",
        mime = "text/csv")

##########################################################

stylesheet = [
    {"selector": "node", "style": {
        "width": 140,
        "height": 30,
        "shape": "rectangle",
        "label" : "data(label)",
        "labelFontSize": 100,
        'background-color': 'data(color)',
        "text-halign": "center",
        "text-valign": "center",
    }},
    {"selector": "edge", "style": {
        "width": "data(width)"
    }}
]

st.title("ToxoCEN Network")
clicked_elements = st_cytoscapejs(
    elements = elements,
    stylesheet = stylesheet,
    width = 1000,
    height= 1000,
    key = "1")