-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathutil.py
More file actions
235 lines (188 loc) · 7.29 KB
/
util.py
File metadata and controls
235 lines (188 loc) · 7.29 KB
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
import colorsys
import json
import os
import random
import shutil
from collections import OrderedDict
import flask
import matplotlib.cm as cm
import networkx as nx
import pandas as pd
import GlobalData as GD
import uploader
def delete_project(request: flask.request):
"""
Delete a project folder and all its contents.
"""
project_name = request.args.get("project")
projects = uploader.listProjects()
if project_name is None:
return f"Error: No project name provided. Example:\n<a href='{flask.request.base_url}?project={projects[0]}'>{flask.request.base_url}?project={projects[0]}</a>"
project_path = os.path.join("static", "projects", project_name)
if not os.path.exists(project_path):
return f"<h4>Project {project_name} does not exist!</h4>"
shutil.rmtree(project_path)
return f"<h4>Project {project_name} deleted!</h4>"
def generate_username():
"""
If no username is provided, generate a random one and return it
"""
username = flask.request.args.get("usr")
if username is None:
username = str(random.randint(1001, 9998))
else:
username = username + str(random.randint(1001, 9998))
return username
def has_no_empty_params(rule):
"""
Filters the route to ignore route with empty params.
"""
defaults = rule.defaults if rule.defaults is not None else ()
arguments = rule.arguments if rule.arguments is not None else ()
return len(defaults) >= len(arguments)
from typing import List, Tuple
def get_all_links(app) -> List[Tuple[str, str]]: #list[list[str, str]]:
"""Extracts all routes from flask app and return a list of tuples of which the first value is the route and the seconds is the name of the corresponding python function."""
links = []
for rule in app.url_map.iter_rules():
# Filter out rules we can't navigate to in a browser
# and rules that require parameters
if "GET" in rule.methods and has_no_empty_params(rule):
url = flask.url_for(rule.endpoint, **(rule.defaults or {}))
links.append((url, rule.endpoint))
return links
def create_dynamic_links(app: flask.app.Flask):
# Get all links from flask
links = get_all_links(app)
# links = [link for link in links if len(link[0].split("/"))>2]
GD.data["url_map"] = links
def prepare_protein_structures(nodes):
PREFIX = "AF-"
SUFFIX = "-F1-model_"
ALPHAFOLD_VER = "v2"
nodes_data = nodes["nodes"]
nodes_data = pd.DataFrame(nodes_data)
if not "uniprot" in nodes_data.columns:
return nodes
csv_file = os.path.join(
"static", "examplefiles", "protein_structure_info", "overview.csv"
)
protein_structure_infos = pd.read_csv(csv_file, index_col=0, header=0)
protein_structure_infos = protein_structure_infos.dropna(how="all", axis=0)
scale_columns = [
c
for c in protein_structure_infos.columns
if c not in ["pdb_file", "multi_structure", "parts"]
]
# Normalize scales to [0,1]
protein_structure_infos[scale_columns] = protein_structure_infos[
scale_columns
].apply(lambda c: c / c.max(), axis=0)
def extract_node_info(
uniprot_ids,
protein_structure_infos=protein_structure_infos,
scale_columns=scale_columns,
):
info = []
ids = [ident for ident in uniprot_ids if ident in protein_structure_infos.index]
for ident in ids:
structure_info = {}
structure_info["file"] = PREFIX + ident + SUFFIX + ALPHAFOLD_VER
for c in scale_columns:
scale = protein_structure_infos.loc[ident, c]
if pd.isna(scale):
continue
structure_info[c] = scale
info.append(structure_info)
return info
nodes_data["protein_info"] = None
has_uniprot = nodes_data[nodes_data["uniprot"].notnull()].copy()
has_uniprot["protein_info"] = has_uniprot["uniprot"].apply(extract_node_info)
nodes_data.update(has_uniprot)
nodes_data = [
{k: v for k, v in m.items() if isinstance(v, list) or pd.notna(v)}
for m in nodes_data.to_dict(orient="records")
]
nodes = {"nodes": nodes_data}
return nodes
def get_identifier_collection():
tsv_file = os.path.join(
"static", "examplefiles", "protein_structure_info", "uniprot_identifiers.tsv"
)
identifier_collection = pd.read_csv(tsv_file, sep="\t")
class OrderedGraph(nx.Graph):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.node_order = [] # List to store the order of node addition
def add_node(self, node_for_adding, **attr):
super().add_node(node_for_adding, **attr)
self.node_order.append(node_for_adding)
def add_nodes_from(self, nodes_for_adding, **attr):
super().add_nodes_from(nodes_for_adding, **attr)
self.node_order.extend(nodes_for_adding)
def project_to_graph(project,bool_links=False):
# --------------------------------------------------
# get checkbox value here
#bool_links =
# --------------------------------------------------
#print("C_DEBUG: in project to graph: ", bool_links)
if bool_links == False:
with open(f"./static/projects/{project}/links.json") as links_json:
links = json.load(links_json)
elif bool_links == True:
with open(f"./static/projects/{project}/linkslayouts.json") as links_json:
links = json.load(links_json)
try:
with open(f"./static/projects/{project}/nodes.json") as nodes_json:
nodes = json.load(nodes_json)
except FileNotFoundError:
# here maybe names.json parsing (even if its deprecated)
raise FileNotFoundError(
"The selected Project does not support nodes.json file for storing nodes."
)
graph_dict = OrderedDict()
for node in nodes["nodes"]:
graph_dict[str(node["id"])] = []
for link in links["links"]:
graph_dict[str(link["s"])].append(str(link["e"]))
graph = nx.from_dict_of_lists(graph_dict, create_using=OrderedGraph)
return graph
def rgb_to_hex(color):
if len(color) == 3:
r, g, b = color
if len(color) == 4:
r, g, b, a = color
return f"#{r:02x}{g:02x}{b:02x}"
def sample_color_gradient(plt_color_map, values):
"""
colors has to be lists as color = [r, g, b]
returns list of tuples according to the color
"""
colors = []
colormap = cm.get_cmap(plt_color_map)
for value in values:
# Interpolate between colors
interpolated_color = colormap(value)
rgb_color = tuple(int(x * 255) for x in interpolated_color[:3])
colors.append(rgb_color)
return colors
def generate_colors(n, s=None, v=None, alpha=None):
# n: int, number of colors to generate
# s: float [0.0, 1.0] Saturation
# v: float [0.0, 1.0] Light value
if s is None:
s = random.uniform(0.7, 1.0)
if v is None:
v = random.uniform(0.7, 1.0)
if alpha is None:
alpha = 100
if n <= 0:
return []
colors = []
hue_increment = 1.0 / n
for i in range(n):
hue = i * hue_increment
rgb = colorsys.hsv_to_rgb(hue, s, v)
rgba_tuple = (int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255), alpha)
colors.append(rgba_tuple)
return colors