-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmake_dist_and_network_data.py
279 lines (248 loc) · 7.31 KB
/
make_dist_and_network_data.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
import os
import json
import pandas as pd
import networkx as nx
from collections import Counter
from random import randint
from acdh_tei_pyutils.tei import TeiReader
from geopy import distance
from lxml import etree as ET
from config import MASTER_ENRICHED, NAME_SPACES
main_file = MASTER_ENRICHED
ns = NAME_SPACES
GEXF_OUT = "./html/data/network.xml"
print(f"running {os.path.basename(__file__)}")
def get_distance(row):
"""helper function to calculate distance from lat/lng columns in dataframe"""
if row["name"] == row["next_name"]:
dist = 0
else:
point_a = (row["lat"], row["lng"])
point_b = (row["next_lat"], row["next_lng"])
dist = distance.distance(point_a, point_b).km
return dist
print(f"converting {main_file} into a DataFrame")
doc = TeiReader(main_file)
places = doc.any_xpath(".//tei:place")
domains = [
"gnd",
"schnitzler_bahr",
"schnitzler_briefe",
"legalkraus",
"schnitzler_tagebuch",
"wikidata",
]
df_data = {
"name": [],
"lat": [],
"lng": [],
"day": [],
"pmb": [],
"akon": [],
"gnd": [],
"schnitzler_tagebuch": [],
"schnitzler_bahr": [],
"schnitzler_briefe": [],
"legalkraus": [],
"wikidata": [],
}
counter = 0
for x in places:
counter += 1
pl_name = " ".join(x.xpath(".//tei:placeName", namespaces=ns)[0].text.split())
try:
coords = x.xpath(".//tei:geo", namespaces=ns)[0].text
except IndexError:
print(f"looks like place {pl_name} has no coords")
continue
try:
lat, lng = coords.split()[0:2]
except AttributeError:
continue
try:
df_data["lat"].append(float(lat))
df_data["lng"].append(float(lng))
except ValueError:
continue
for domain in domains:
try:
uri = x.xpath(f'./tei:idno[@subtype="{domain}"]/text()', namespaces=ns)[0]
except IndexError:
uri = "no url"
df_data[domain].append(uri)
try:
akon = x.xpath("./tei:link/@target", namespaces=ns)[0]
except IndexError:
akon = "no url"
df_data["akon"].append(akon)
try:
pmb = x.xpath('./tei:idno[@type="pmb"]/text()', namespaces=ns)[0]
except IndexError:
pmb = "no url"
df_data["pmb"].append(pmb)
df_data["name"].append(pl_name)
try:
df_data["day"].append(x.getparent().getparent().getparent().attrib["when"])
except KeyError:
event = x.getparent().getparent().getparent().getparent()
# print(f"{counter} ###############")
# print(ET.tostring(event))
# print("#################\n\n\n")
df_data["day"].append(
x.getparent().getparent().getparent().getparent().attrib["when"]
)
df = pd.DataFrame(df_data)
# add values from next row to the current one
df = pd.concat(
[
df,
df.shift(-1).add_prefix("next_"),
],
axis=1,
).fillna(0.0)
# drop last row
df.drop(index=df.index[-1], axis=0, inplace=True)
# drop rows without movement
df.drop(df.loc[df["name"] == df["next_name"]].index, inplace=True)
# df.to_csv('hansi.csv', index=False)
print("create graphology.js network graph data")
domains = [
"gnd",
"schnitzler_bahr",
"schnitzler_briefe",
"legalkraus",
"schnitzler_tagebuch",
"wikidata",
"pmb",
"akon",
]
G = nx.MultiGraph()
for i, row in df.iterrows():
G.add_node(row["name"])
for domain in domains:
G.nodes[row["name"]][domain] = row[domain]
for i, row in df.iterrows():
G.add_edges_from(
[
(
row["name"],
row["next_name"],
{"day": row["day"], "edge_key": f"edge_{i}"},
),
]
)
# add network coords
print("calculating spring layout")
pos = nx.spring_layout(G, iterations=30, seed=1721)
for key, value in pos.items():
G.nodes[key]["x"] = float(value[0])
G.nodes[key]["y"] = float(value[1])
# add node size taken from centrality
degree_centrality = nx.centrality.degree_centrality(G)
for key, value in degree_centrality.items():
size = value * 100
if size < 2:
size = 2
elif size > 5:
size = 5 + value
G.nodes[key]["size"] = size
# add cluster and colors
for com in nx.community.label_propagation_communities(G):
color = "#%06X" % randint(0, 0xFFFFFF) # creates random RGB color
for node in list(
com
): # fill colors list with the particular color for the community nodes
G.nodes[node]["color"] = color
# add edge weight
c = Counter(G.edges())
for u, v, d in G.edges(data=True):
d["weight"] = c[u, v]
# print(f"dumping graph data as gexf into {GEXF_OUT}")
# nx.write_gexf(G, GEXF_OUT)
# serialize into graphology format
data = {
"attributes": {
"name": "Schnitzler Reisen als Netzwerk",
"description": "Der Graph zeigt Schnitzler Reisen von Ort A zu B. Je größer ein Knoten, desto mehr andere Orte verbindet er.",
},
"options": {"type": "undirected", "multi": True, "allowSelfLoops": True},
"nodes": [],
"edges": [],
}
for node in nx.nodes(G):
item = {"key": node, "attributes": dict(G.nodes[node])}
item["attributes"]["label"] = node
data["nodes"].append(item)
for u, v, d in G.edges(data=True):
weight = d["weight"]
if weight > 10:
weight = 10
color = "#ffe6ff"
elif weight <= 10 and weight > 5:
color = "#ffe6ff"
else:
color = "#ff99ff"
item = {
"key": d["edge_key"],
"source": u,
"target": v,
"attributes": {
"day": d["day"],
"size": weight,
"color": color,
},
}
data["edges"].append(item)
print("dumping graph data")
with open("./html/data/network.json", "w") as f:
json.dump(data, f, ensure_ascii=False)
# create arc-data
data = []
for i, row in df.iterrows():
item = {}
item["from"] = {
"name": row["name"],
"day": row["day"],
"year": row["day"][:4],
"coordinates": [row["lng"], row["lat"]],
}
item["to"] = {
"name": row["next_name"],
"coordinates": [row["next_lng"], row["next_lat"]],
}
data.append(item)
with open("./html/data/arc-data.json", "w") as f:
json.dump(data, f, ensure_ascii=False)
# create travel-net-map.json data
graph_data = []
for g, gdf in df.groupby("name"):
row = gdf.iloc[0]
item = {}
item["properties"] = {"id": g, "lat": row["lat"], "lon": row["lng"]}
item["connections"] = {}
for target, tdf in gdf.groupby("next_name"):
item["connections"][target] = len(tdf)
graph_data.append(item)
with open("./html/data/travel-net-map.json", "w") as f:
json.dump(graph_data, f, ensure_ascii=False)
# calculate distance
df["distance"] = df.apply(lambda row: get_distance(row), axis=1)
travels = []
for i, row in df.iterrows():
travels.append("___".join([row["name"], row["next_name"], str(row["distance"])]))
travels = dict(Counter(travels).most_common())
better_travels = []
for key, value in travels.items():
source, target, distance = key.split("___")
better_travels.append(
{
"travel_id": f"{source}___{target}",
"source": source,
"target": target,
"distance": float(distance),
"amount": value,
}
)
data = {"data": better_travels}
with open("./html/data/travels.json", "w") as f:
json.dump(data, f, ensure_ascii=False)