-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauxillary_methods.py
541 lines (465 loc) · 16.5 KB
/
auxillary_methods.py
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
254
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
import matplotlib
from typing import Any, Dict, List, Optional, Tuple, Type, Union, Text
import requests
from tqdm import tqdm
import streamlit as st
import pandas as pd
import networkx as networkx
nx = networkx
import pickle
import numpy as np
import plotly.graph_objects as go
import pandas as pd
#from datashader.bundling import hammer_bundle
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
def draw_wstate_tree(G):
#from networkx.drawing.nx_agraph import write_dot, graphviz_layout
pos = nx.spring_layout(G)
#pos = graphviz_layout(G, prog='dot')
edge_labels = nx.get_edge_attributes(G, 'label')
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8)
nx.draw_networkx_labels(G, pos, font_size=10)
matplotlib.use('Agg')
plt.savefig("whole_net.png")
st.write(plt.show())
# Custom function to create an edge between node x and node y, with a given text and width
def make_edge(x, y, text, width):
return go.Scatter(
x=x,
y=y,
line=dict(width=width, color="cornflowerblue"),
hoverinfo="text",
text=([text]),
mode="lines",
)
def plotly_sized(g):
"""
https://towardsdatascience.com/tutorial-network-visualization-basics-with-networkx-and-plotly-and-a-little-nlp-57c9bbb55bb9
"""
pos_ = nx.fruchterman_reingold_layout(g)
# x, y = pos_[node]
# pos_ = nx.spring_layout(g)
# For each edge, make an edge_trace, append to list
edge_trace = []
for edge in g.edges():
weight = 1 + g.edges()[edge]["weight"]
weight = 2.5 * np.log(weight)
# if weight => 5:
# print(weight)
if g.edges()[edge]["weight"] > 0:
char_1 = edge[0]
char_2 = edge[1]
x0, y0 = pos_[char_1]
x1, y1 = pos_[char_2]
text = char_1 + "--" + char_2 + ": " + str(g.edges()[edge]["weight"])
trace = make_edge(
[x0, x1, text],
[y0, y1, text],
text,
width=weight,
)
edge_trace.append(trace)
# Make a node trace
# for node in g.nodes():
# labels = [str(node) for node in g.nodes()]
node_trace = go.Scatter(
x=[],
y=[],
hoverinfo="none",
text=([text]),
mode="markers+text",
marker=dict(color=[], size=[], line=None),
)
# marker=dict(symbol='circle-dot',
# size=5,
# color='#6959CD',
# line=dict(color='rgb(50,50,50)', width=0.5))
# For each node in g, get the position and size and add to the node_trace
for node in g.nodes():
x, y = pos_[node]
# print(x,tuple(x),node_trace["x"])
node_trace["x"] += tuple([x])
node_trace["y"] += tuple([y])
# node_trace["marker"]["color"] += tuple(["cornflowerblue"])
# node_trace['marker']['size'] += tuple([5*g.nodes()[node]['size']])
node_trace["marker"]["size"] += tuple([0.45 * g.nodes()[node]["size"]])
node_trace["text"] += tuple(["<b>" + str(node) + "</b>"])
# Customize layout
layout = go.Layout(
paper_bgcolor="rgba(0,0,0,0)", # transparent background
plot_bgcolor="rgba(0,0,0,0)", # transparent 2nd background
xaxis={"showgrid": False, "zeroline": False}, # no gridlines
yaxis={"showgrid": False, "zeroline": False}, # no gridlines
) # Create figure
layout["width"] = 725
layout["height"] = 725
fig = go.Figure(layout=layout) # Add all edge traces
for trace in edge_trace:
fig.add_trace(trace) # Add node trace
fig.add_trace(node_trace) # Remove legend
fig.update_layout(showlegend=False) # Remove tick labels
fig.update_xaxes(showticklabels=False)
fig.update_yaxes(showticklabels=False) # Show figure
return fig
# fig.show()
'''
def try_again(g):
from holoviews.operation.datashader import datashade, bundle_graph
import holoviews as hv
#edges_df = g.edges#pd.read_csv('../assets/fb_edges.csv')
ds_edges_py = [
[n0, n1] for (n0, n1) in g.edges
]
#edges_df = pd.DataFrame(ds_edges_py, columns=["source", "target"])
fb_nodes = hv.Nodes(g.nodes)#.sort()
fb_graph = hv.Graph((g.edges, fb_nodes), label='Entire Sirg Network')
return fb_graph
#
def ego_graph(g):
# https://hvplot.holoviz.org/user_guide/NetworkX.html
#import holoviews.networkx as hvnx
from operator import itemgetter
import holoviews as hv
# Create a BA model graph
#n = 1000
#m = 2
#G = nx.generators.barabasi_albert_graph(n, m)
# find node with largest degree
node_and_degree = g.degree()
(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
# Create ego graph of main hub
hub_ego = nx.ego_graph(g, largest_hub)
# Draw graph
pos = nx.spring_layout(hub_ego)
g = nx.draw(hub_ego, pos, node_color='blue', node_size=50, with_labels=False)
# Draw ego as large and red
#gnodes = nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='red')
#result = g * gnodes
st.write(hv.render(result, backend="bokeh"))
return result
def data_shade(graph):
# from sklearn.decomposition import PCA
nodes = list(graph.nodes())
weights = (
np.asarray(list(map(lambda x: x[-1]["weight"], graph.edges(data=True)))) ** 2
)
pos_ = nx.fruchterman_reingold_layout(graph)
coords = []
for node in graph.nodes:
x, y = pos_[node]
coords.append((x, y))
nodes_py = [[name, pos[0], pos[1]] for name, pos in zip(nodes, coords)]
ds_nodes = pd.DataFrame(nodes_py, columns=["name", "x", "y"])
ds_edges_py = [
[n0, n1] for (n0, n1) in graph.edges
]
ds_edges = pd.DataFrame(ds_edges_py, columns=["source", "target"])
hb = hammer_bundle(ds_nodes, ds_edges)
fig = hb.plot(x="x", y="y", figsize=(9, 9))
return fig
'''
def university_data_frame():
world_universities = pd.read_csv("world-universities.csv")
world_universities.rename(
columns={
"AD": "country",
"University of Andorra": "university",
"http://www.uda.ad/": "wesbite",
},
inplace=True,
)
class tqdm:
def __init__(self, iterable, title=None):
if title:
st.write(title)
self.prog_bar = st.progress(0)
self.iterable = iterable
self.length = len(iterable)
self.i = 0
def __iter__(self):
for obj in self.iterable:
yield obj
self.i += 1
current_prog = self.i / self.length
self.prog_bar.progress(current_prog)
def network(coauthors, MAIN_AUTHOR):
node_strengths = {}
cnt = 0
titles = {}
for title, mini_net in coauthors:
for names in mini_net:
key = names["name"]["first"] + str(" ") + names["name"]["last"]
# titles[key] = title
if key not in node_strengths.keys():
node_strengths[key] = 1
else:
node_strengths[key] += 1
cnt += 1
g = networkx.DiGraph()
# for key,value in node_strengths.items():
#
for title, mini_net in coauthors:
for names in mini_net:
key = names["name"]["first"] + str(" ") + names["name"]["last"]
g.add_node(key, label=title, size=node_strengths[key])
if cnt > 100:
st.markdown(
""" Detected large degree of collaborators/interconnectdness {0} building network will take time ... """.format(
cnt
)
)
for title, mini_net in tqdm(
coauthors,
title="Queried authors, now building network structure and rendering plots",
):
# build small worlds
# from projection
for i, namesi in enumerate(mini_net):
keyi = namesi["name"]["first"] + str(" ") + namesi["name"]["last"]
# to projection
for j, namesj in enumerate(mini_net):
keyj = namesj["name"]["first"] + str(" ") + namesj["name"]["last"]
if i != j:
g.add_edge(keyi, keyj, weight=node_strengths[keyi])
return g
def make_clickable(link):
# target _blank to open new window
# extract clickable text to display for your link
text = link # .split('=')[1]
return f'<a target="_blank" href="{link}">{text}</a>'
def author_to_coauthor_network(name: str = "") -> networkx.DiGraph():
response = requests.get("https://dissem.in/api/search/?authors=" + str(name))
author_papers = response.json()
coauthors = []
titles = []
list_of_dicts = []
if len(author_papers["papers"]) == 0:
st.markdown(
"""## That query lead to zero papers. \n Retry either adding or ommitting middle initial."""
)
return None
for p in author_papers["papers"]:
coauthors_ = p["authors"]
title = p["title"]
titles.append(title)
coauthors.append((title, coauthors_))
if "pdf_url" in p.keys():
temp = {"title": p["title"], "Web_Link": p["pdf_url"]}
else:
temp = {"title": p["title"], "Web_Link": p["records"][0]["splash_url"]}
list_of_dicts.append(temp)
df = pd.DataFrame(list_of_dicts)
with open(str(name) + "_df.p", "wb") as f:
pickle.dump(df, f)
g = network(coauthors, name)
return g, df
def push_frame_to_screen(df_links):
df_links.drop_duplicates(subset="Web_Link", inplace=True)
df_links["Web_Link"] = df_links["Web_Link"].apply(make_clickable)
df_links = df_links.to_html(escape=False)
st.write(df_links, unsafe_allow_html=True)
def get_cluster_id(url):
"""
Google assign a cluster identifier to a group of web documents
that appear to be the same publication in different places on the web.
How they do this is a bit of a mystery, but this identifier is
important since it uniquely identifies the publication.
"""
vals = parse_qs(urlparse(url).query).get("cluster", [])
if len(vals) == 1:
return vals[0]
else:
vals = parse_qs(urlparse(url).query).get("cites", [])
print(vals)
if len(vals) == 1:
return vals[0]
return None
def author_to_urls(NAME):
response = requests.get("https://dissem.in/api/search/?authors=" + str(NAME))
author_papers = response.json()
visit_urls = []
coauthors = []
titles = []
for p in author_papers["papers"]:
coauthors_ = p["authors"]
title = p["title"]
titles.append(title)
coauthors.append(coauthors_)
if "pdf_url" in p.keys():
visit_urls.append(p["pdf_url"])
records = p["records"][0]
if "splash_url" in records.keys():
visit_urls.append(records["splash_url"])
if "doi" in records.keys():
visit_urls.append(records["doi"])
visit_urls = [i for i in visit_urls if "FIGSHARE" not in i]
visit_urls = [i for i in visit_urls if "figshare" not in i]
visit_urls = [i for i in visit_urls if "doi" in i]
dois = []
for link in visit_urls:
if "https://doi.org/" in link:
li = link.split("https://doi.org/")
dois.append(li[1])
if "http://dx.doi.org" in link:
li = link.split("http://dx.doi.org")
dois.append(li[1])
return dois, coauthors, titles
def response_paper_to_url(p: dict = {}) -> List:
if "pdf_url" in p.keys():
visit_urls.append(p["pdf_url"])
records = p["records"][0]
if "splash_url" in records.keys():
visit_urls.append(records["splash_url"])
if "doi" in records.keys():
visit_urls.append(records["doi"])
visit_urls = [i for i in visit_urls if "FIGSHARE" not in i]
visit_urls = [i for i in visit_urls if "figshare" not in i]
visit_urls = [i for i in visit_urls if "doi" in i]
dois = []
for link in visit_urls:
if "https://doi.org/" in link:
li = link.split("https://doi.org/")
dois.append(li[1])
if "http://dx.doi.org" in link:
li = link.split("http://dx.doi.org")
dois.append(li[1])
return dois
def get_id(e):
"""
Determining the publication id is tricky since it involves looking
in the element for the various places a cluster id can show up.
If it can't find one it will use the data-cid which should be
usable since it will be a dead end anyway: Scholar doesn't know of
anything that cites it.
"""
for a in e.find(".gs_fl a"):
if "Cited by" in a.text:
return get_cluster_id(a.attrs["href"])
elif "versions" in a.text:
return get_cluster_id(a.attrs["href"])
if "data-cid" in e.attrs.keys():
return e.attrs["data-cid"]
else:
print(e.attrs)
def get_citations(url, depth=1, pages=1):
"""
Given a page of citations it will return bibliographic information
for the source, target of a citation.
"""
if url in seen:
return
html = get_html(url)
seen.add(url)
# get the publication that these citations reference.
# Note: this can be None when starting with generic search results
a = html.find("#gs_res_ccl_top a", first=True)
if a:
to_pub = {
"id": get_cluster_id(url),
"title": a.text,
}
else:
to_pub = None
for e in html.find("#gs_res_ccl_mid .gs_r"):
try:
from_pub = get_metadata(e)
yield from_pub, to_pub
except:
pass
# depth first search if we need to go deeper
if depth > 0 and from_pub["cited_by_url"]:
yield from get_citations(
from_pub["cited_by_url"], depth=depth - 1, pages=pages
)
# get the next page if that's what they wanted
if pages > 1:
for link in html.find("#gs_n a"):
if link.text == "Next":
yield from get_citations(
"https://scholar.google.com" + link.attrs["href"],
depth=depth,
pages=pages - 1,
)
def get_metadata(e):
"""
Fetch the citation metadata from a citation element on the page.
"""
article_id = get_id(e)
a = e.find(".gs_rt a", first=True)
if a:
url = a.attrs["href"]
title = a.text
else:
url = None
title = e.find(".gs_rt .gs_ctu", first=True).text
authors = source = website = None
# try:
meta = e.find(".gs_a", first=True).text
# except:
# print(e)
meta_parts = [m.strip() for m in re.split(r"\W-\W", meta)]
if len(meta_parts) == 3:
authors, source, website = meta_parts
elif len(meta_parts) == 2:
authors, source = meta_parts
if source and "," in source:
year = source.split(",")[-1].strip()
else:
year = source
cited_by = cited_by_url = None
for a in e.find(".gs_fl a"):
if "Cited by" in a.text:
cited_by = a.search("Cited by {:d}")[0]
cited_by_url = "https://scholar.google.com" + a.attrs["href"]
return {
"id": article_id,
"url": url,
"title": title,
"authors": authors,
"year": year,
"cited_by": cited_by,
"cited_by_url": cited_by_url,
}
def get_html(url):
"""
get_html uses selenium to drive a browser to fetch a URL, and return a
requests_html.HTML object for it.
If there is a captcha challenge it will alert the user and wait until
it has been completed.
"""
global driver
time.sleep(random.randint(1, 5))
driver.get(url)
while True:
try:
recap = driver.find_element_by_css_selector("#gs_captcha_ccl,#recaptcha")
except NoSuchElementException:
try:
html = driver.find_element_by_css_selector("#gs_top").get_attribute(
"innerHTML"
)
return requests_html.HTML(html=html)
except NoSuchElementException:
print("google has blocked this browser, reopening")
driver.close()
driver = webdriver.Chrome()
return get_html(url)
print("... it's CAPTCHA time!\a ...")
time.sleep(5)
def remove_nones(d):
new_d = {}
for k, v in d.items():
if v is not None:
new_d[k] = v
return new_d
def to_json(g):
j = {"nodes": [], "links": []}
for node_id, node_attrs in g.nodes(True):
node_attrs["id"] = node_id
j["nodes"].append(node_attrs)
for source, target, attrs in g.edges(data=True):
j["links"].append({"source": source, "target": target})
return j