-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeo_network.py
More file actions
176 lines (149 loc) · 4.36 KB
/
geo_network.py
File metadata and controls
176 lines (149 loc) · 4.36 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
# =========================
# PMC–Country–Continent Network (Dynamic, Colab-ready)
# =========================
import pandas as pd
import re, json
import networkx as nx
from collections import defaultdict
import pycountry
import pycountry_convert as pc
import argparse
# -------- Command-line arguments for input/output --------
parser = argparse.ArgumentParser(description="PMC–Country–Continent Network")
parser.add_argument("--input", type=str, required=True, help="Path to input CSV file")
parser.add_argument("--graphml", type=str, required=True, help="Path to save GraphML file")
parser.add_argument("--html", type=str, required=True, help="Path to save HTML file")
args = parser.parse_args()
csv_file = args.input
graphml_path = args.graphml
html_path = args.html
# -------- Load CSV --------
df = pd.read_csv(csv_file)
# -------- Dynamic Country → Continent function --------
def country_to_continent(country_name):
try:
country = pycountry.countries.lookup(country_name)
country_alpha2 = country.alpha_2
continent_code = pc.country_alpha2_to_continent_code(country_alpha2)
return pc.convert_continent_code_to_continent_name(continent_code)
except Exception:
return "Unknown"
# -------- Wikipedia helpers --------
def wikipedia_url(title):
title = title.replace(" ", "_")
return f"https://en.wikipedia.org/wiki/{title}"
# -------- Colors --------
color_map = {
"PMC": "#3b71cd",
"COUNTRY": "#e377c2",
"CONTINENT": "#5A4E11"
}
# -------- Build graph --------
G = nx.Graph()
edge_weights = defaultdict(int)
for _, row in df.iterrows():
file_path = str(row["file_path"])
match = re.search(r"(PMC\d+)", file_path)
if not match:
continue
pmc = match.group(1)
countries = {
c.strip() for c in str(row["0"]).split(",") if c.strip()
}
# PMC node
G.add_node(
pmc,
type="PMC",
url=f"https://www.ncbi.nlm.nih.gov/pmc/articles/{pmc}/"
)
for country in countries:
continent = country_to_continent(country)
G.add_node(
country,
type="COUNTRY",
url=wikipedia_url(country)
)
G.add_node(
continent,
type="CONTINENT",
url=wikipedia_url(continent)
)
edge_weights[(pmc, country)] += 1
G.add_edge(pmc, country)
G.add_edge(country, continent)
# -------- Assign edge weights --------
for (s, t), w in edge_weights.items():
if G.has_edge(s, t):
G[s][t]["weight"] = w
# -------- Export GraphML --------
nx.write_graphml(G, graphml_path)
print(f"✔ GraphML exported for Cytoscape Desktop: {graphml_path}")
# -------- Convert to Cytoscape elements --------
elements = []
for n, d in G.nodes(data=True):
elements.append({
"data": {
"id": n,
"label": n,
"type": d["type"],
"color": color_map.get(d["type"], "#cccccc"),
"url": d.get("url")
}
})
for s, t, d in G.edges(data=True):
elements.append({
"data": {
"source": s,
"target": t,
"weight": d.get("weight", 1)
}
})
# -------- Save HTML for Colab --------
with open(html_path, "w") as f:
f.write(f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PMC–Country–Continent Network</title>
<script src="https://unpkg.com/cytoscape@3.21.2/dist/cytoscape.min.js"></script>
</head>
<body>
<div id="cy" style="width:100%; height:750px; border:1px solid #ccc;"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {{
var cy = cytoscape({{
container: document.getElementById('cy'),
elements: {json.dumps(elements)},
style: [
{{
selector: 'node',
style: {{
'label': 'data(label)',
'background-color': 'data(color)',
'font-size': '10px',
'text-valign': 'center',
'text-halign': 'center'
}}
}},
{{
selector: 'edge',
style: {{
'width': 'mapData(weight, 1, 10, 1, 6)',
'line-color': '#999'
}}
}}
],
layout: {{ name: 'cose' }}
}});
cy.on('tap', 'node', function(evt) {{
const url = evt.target.data('url');
if (url) {{
window.open(url, '_blank');
}}
}});
}});
</script>
</body>
</html>
""")
print(f"✔ Interactive HTML saved: {html_path}")