-
Notifications
You must be signed in to change notification settings - Fork 74
/
app.py
303 lines (268 loc) · 13.4 KB
/
app.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import networkx as nx
import plotly.graph_objs as go
import pandas as pd
from colour import Color
from datetime import datetime
from textwrap import dedent as d
import json
# import the css template, and pass the css template into dash
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = "Transaction Network"
YEAR=[2010, 2019]
ACCOUNT="A0001"
##############################################################################################################################################################
def network_graph(yearRange, AccountToSearch):
edge1 = pd.read_csv('edge1.csv')
node1 = pd.read_csv('node1.csv')
# filter the record by datetime, to enable interactive control through the input box
edge1['Datetime'] = "" # add empty Datetime column to edge1 dataframe
accountSet=set() # contain unique account
for index in range(0,len(edge1)):
edge1['Datetime'][index] = datetime.strptime(edge1['Date'][index], '%d/%m/%Y')
if edge1['Datetime'][index].year<yearRange[0] or edge1['Datetime'][index].year>yearRange[1]:
edge1.drop(axis=0, index=index, inplace=True)
continue
accountSet.add(edge1['Source'][index])
accountSet.add(edge1['Target'][index])
# to define the centric point of the networkx layout
shells=[]
shell1=[]
shell1.append(AccountToSearch)
shells.append(shell1)
shell2=[]
for ele in accountSet:
if ele!=AccountToSearch:
shell2.append(ele)
shells.append(shell2)
G = nx.from_pandas_edgelist(edge1, 'Source', 'Target', ['Source', 'Target', 'TransactionAmt', 'Date'], create_using=nx.MultiDiGraph())
nx.set_node_attributes(G, node1.set_index('Account')['CustomerName'].to_dict(), 'CustomerName')
nx.set_node_attributes(G, node1.set_index('Account')['Type'].to_dict(), 'Type')
# pos = nx.layout.spring_layout(G)
# pos = nx.layout.circular_layout(G)
# nx.layout.shell_layout only works for more than 3 nodes
if len(shell2)>1:
pos = nx.drawing.layout.shell_layout(G, shells)
else:
pos = nx.drawing.layout.spring_layout(G)
for node in G.nodes:
G.nodes[node]['pos'] = list(pos[node])
if len(shell2)==0:
traceRecode = [] # contains edge_trace, node_trace, middle_node_trace
node_trace = go.Scatter(x=tuple([1]), y=tuple([1]), text=tuple([str(AccountToSearch)]), textposition="bottom center",
mode='markers+text',
marker={'size': 50, 'color': 'LightSkyBlue'})
traceRecode.append(node_trace)
node_trace1 = go.Scatter(x=tuple([1]), y=tuple([1]),
mode='markers',
marker={'size': 50, 'color': 'LightSkyBlue'},
opacity=0)
traceRecode.append(node_trace1)
figure = {
"data": traceRecode,
"layout": go.Layout(title='Interactive Transaction Visualization', showlegend=False,
margin={'b': 40, 'l': 40, 'r': 40, 't': 40},
xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
height=600
)}
return figure
traceRecode = [] # contains edge_trace, node_trace, middle_node_trace
############################################################################################################################################################
colors = list(Color('lightcoral').range_to(Color('darkred'), len(G.edges())))
colors = ['rgb' + str(x.rgb) for x in colors]
index = 0
for edge in G.edges:
x0, y0 = G.nodes[edge[0]]['pos']
x1, y1 = G.nodes[edge[1]]['pos']
weight = float(G.edges[edge]['TransactionAmt']) / max(edge1['TransactionAmt']) * 10
trace = go.Scatter(x=tuple([x0, x1, None]), y=tuple([y0, y1, None]),
mode='lines',
line={'width': weight},
marker=dict(color=colors[index]),
line_shape='spline',
opacity=1)
traceRecode.append(trace)
index = index + 1
###############################################################################################################################################################
node_trace = go.Scatter(x=[], y=[], hovertext=[], text=[], mode='markers+text', textposition="bottom center",
hoverinfo="text", marker={'size': 50, 'color': 'LightSkyBlue'})
index = 0
for node in G.nodes():
x, y = G.nodes[node]['pos']
hovertext = "CustomerName: " + str(G.nodes[node]['CustomerName']) + "<br>" + "AccountType: " + str(
G.nodes[node]['Type'])
text = node1['Account'][index]
node_trace['x'] += tuple([x])
node_trace['y'] += tuple([y])
node_trace['hovertext'] += tuple([hovertext])
node_trace['text'] += tuple([text])
index = index + 1
traceRecode.append(node_trace)
################################################################################################################################################################
middle_hover_trace = go.Scatter(x=[], y=[], hovertext=[], mode='markers', hoverinfo="text",
marker={'size': 20, 'color': 'LightSkyBlue'},
opacity=0)
index = 0
for edge in G.edges:
x0, y0 = G.nodes[edge[0]]['pos']
x1, y1 = G.nodes[edge[1]]['pos']
hovertext = "From: " + str(G.edges[edge]['Source']) + "<br>" + "To: " + str(
G.edges[edge]['Target']) + "<br>" + "TransactionAmt: " + str(
G.edges[edge]['TransactionAmt']) + "<br>" + "TransactionDate: " + str(G.edges[edge]['Date'])
middle_hover_trace['x'] += tuple([(x0 + x1) / 2])
middle_hover_trace['y'] += tuple([(y0 + y1) / 2])
middle_hover_trace['hovertext'] += tuple([hovertext])
index = index + 1
traceRecode.append(middle_hover_trace)
#################################################################################################################################################################
figure = {
"data": traceRecode,
"layout": go.Layout(title='Interactive Transaction Visualization', showlegend=False, hovermode='closest',
margin={'b': 40, 'l': 40, 'r': 40, 't': 40},
xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
height=600,
clickmode='event+select',
annotations=[
dict(
ax=(G.nodes[edge[0]]['pos'][0] + G.nodes[edge[1]]['pos'][0]) / 2,
ay=(G.nodes[edge[0]]['pos'][1] + G.nodes[edge[1]]['pos'][1]) / 2, axref='x', ayref='y',
x=(G.nodes[edge[1]]['pos'][0] * 3 + G.nodes[edge[0]]['pos'][0]) / 4,
y=(G.nodes[edge[1]]['pos'][1] * 3 + G.nodes[edge[0]]['pos'][1]) / 4, xref='x', yref='y',
showarrow=True,
arrowhead=3,
arrowsize=4,
arrowwidth=1,
opacity=1
) for edge in G.edges]
)}
return figure
######################################################################################################################################################################
# styles: for right side hover/click component
styles = {
'pre': {
'border': 'thin lightgrey solid',
'overflowX': 'scroll'
}
}
app.layout = html.Div([
#########################Title
html.Div([html.H1("Transaction Network Graph")],
className="row",
style={'textAlign': "center"}),
#############################################################################################define the row
html.Div(
className="row",
children=[
##############################################left side two input components
html.Div(
className="two columns",
children=[
dcc.Markdown(d("""
**Time Range To Visualize**
Slide the bar to define year range.
""")),
html.Div(
className="twelve columns",
children=[
dcc.RangeSlider(
id='my-range-slider',
min=2010,
max=2019,
step=1,
value=[2010, 2019],
marks={
2010: {'label': '2010'},
2011: {'label': '2011'},
2012: {'label': '2012'},
2013: {'label': '2013'},
2014: {'label': '2014'},
2015: {'label': '2015'},
2016: {'label': '2016'},
2017: {'label': '2017'},
2018: {'label': '2018'},
2019: {'label': '2019'}
}
),
html.Br(),
html.Div(id='output-container-range-slider')
],
style={'height': '300px'}
),
html.Div(
className="twelve columns",
children=[
dcc.Markdown(d("""
**Account To Search**
Input the account to visualize.
""")),
dcc.Input(id="input1", type="text", placeholder="Account"),
html.Div(id="output")
],
style={'height': '300px'}
)
]
),
############################################middle graph component
html.Div(
className="eight columns",
children=[dcc.Graph(id="my-graph",
figure=network_graph(YEAR, ACCOUNT))],
),
#########################################right side two output component
html.Div(
className="two columns",
children=[
html.Div(
className='twelve columns',
children=[
dcc.Markdown(d("""
**Hover Data**
Mouse over values in the graph.
""")),
html.Pre(id='hover-data', style=styles['pre'])
],
style={'height': '400px'}),
html.Div(
className='twelve columns',
children=[
dcc.Markdown(d("""
**Click Data**
Click on points in the graph.
""")),
html.Pre(id='click-data', style=styles['pre'])
],
style={'height': '400px'})
]
)
]
)
])
###################################callback for left side components
@app.callback(
dash.dependencies.Output('my-graph', 'figure'),
[dash.dependencies.Input('my-range-slider', 'value'), dash.dependencies.Input('input1', 'value')])
def update_output(value,input1):
YEAR = value
ACCOUNT = input1
return network_graph(value, input1)
# to update the global variable of YEAR and ACCOUNT
################################callback for right side components
@app.callback(
dash.dependencies.Output('hover-data', 'children'),
[dash.dependencies.Input('my-graph', 'hoverData')])
def display_hover_data(hoverData):
return json.dumps(hoverData, indent=2)
@app.callback(
dash.dependencies.Output('click-data', 'children'),
[dash.dependencies.Input('my-graph', 'clickData')])
def display_click_data(clickData):
return json.dumps(clickData, indent=2)
if __name__ == '__main__':
app.run_server(debug=True)