-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashboard.py
194 lines (168 loc) · 5.66 KB
/
dashboard.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
import os
import re
import dash
from dash import html, dcc, Input, Output
import plotly.express as px
import pandas as pd
import numpy as np
from time import time, sleep
import requests
import argparse
DASHBOARD_BASE_URL = os.getenv('DASHBOARD_BASE_URL', 'http://localhost:8000')
# Environment Variables
FILE_PATH = os.getenv('FILE_PATH', 'scores.csv')
MONTH = os.getenv('MONTH', None)
DECIMATE = int(os.getenv('DECIMATE', 10))
def dashboard_link(pid):
return f'{DASHBOARD_BASE_URL}/bin?bin={pid}'
def load_point_cloud(pid):
"""Load point cloud data for a given PID."""
URL=f'{DASHBOARD_BASE_URL}/api/plot/{pid}'
response = requests.get(URL)
if response.status_code != 200:
return np.random.rand(1,2)
else:
j = response.json()
return np.dstack((j['roi_x'], j['roi_y']))[0]
def plot_2d_point_cloud(points):
"""Create a scatter plot of a 2D point cloud."""
fig = px.scatter(
x=points[:, 0],
y=points[:, 1],
title="2D Point Cloud",
labels={'x': 'X (width)', 'y': 'Y (height)'}
)
fig.update_layout(
showlegend=False,
margin=dict(l=20, r=20, t=40, b=20),
yaxis=dict(
scaleanchor="x",
scaleratio=1,
)
)
return fig
def pid_to_datetime(pid):
if pid.startswith('D'):
return pd.to_datetime(pid[1:16], format='%Y%m%dT%H%M%S')
elif pid.startswith('I'):
ts = re.sub(r'^IFCB\d_', '', pid)
return pd.to_datetime(ts[0:15], format='%Y_%j_%H%M%S')
def load_data(file_path, month=None):
print(f'loading data from {file_path}')
data = pd.read_csv(file_path)
dates = [pid_to_datetime(pid) for pid in data['pid']]
df = pd.DataFrame({
'timestamp': dates,
'anomaly_score': data['anomaly_score'],
'pid': data['pid']
})
if month:
year = int(month[:4])
month_num = int(month[4:])
df = df[
(df['timestamp'].dt.year == year) &
(df['timestamp'].dt.month == month_num)
]
print(f'loaded {len(df)} records')
return df
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1('Interactive Point Cloud Anomaly Explorer'),
html.Hr(),
html.Div([
html.H3('Anomaly Score Timeline'),
dcc.Graph(
id='anomaly-time-series',
config={'scrollZoom': True}
),
html.Hr(),
html.H3('Selected Point Cloud'),
html.Div(id='point-cloud-details'),
html.Div([
html.Label('PID: ', style={'fontWeight': 'bold'}),
html.Span(id='selected-pid')
]),
dcc.Graph(id='2d-point-cloud'),
dcc.Store(id='last-hover-time', data=time())
], style={'padding': '20px'})
])
@app.callback(
Output('anomaly-time-series', 'figure'),
Input('anomaly-time-series', 'id')
)
def update_timeline(_):
fig = px.scatter(
df,
x='timestamp',
y='anomaly_score',
title='Anomaly Scores Over Time'
)
fig.update_layout(
hovermode='x',
hoverlabel=dict(bgcolor="white"),
margin=dict(l=20, r=20, t=40, b=20),
yaxis=dict(fixedrange=True),
)
return fig
@app.callback(
[Output('last-hover-time', 'data'),
Output('selected-pid', 'children'),
Output('2d-point-cloud', 'figure'),
Output('point-cloud-details', 'children')],
[Input('anomaly-time-series', 'clickData'),
Input('last-hover-time', 'data')],
)
def update_on_hover(hover_data, last_hover):
if hover_data is None:
return time(), '', {}, None
current_time = time()
# if current_time - last_hover < 0.5:
# raise dash.exceptions.PreventUpdate
try:
timestamp = pd.Timestamp(hover_data['points'][0]['x'])
selected_point = df.iloc[(df['timestamp'] - timestamp).abs().argsort()[:1]]
if not selected_point.empty:
pid = selected_point['pid'].iloc[0]
score = selected_point['anomaly_score'].iloc[0]
points = load_point_cloud(pid)
figure = plot_2d_point_cloud(points)
details = html.P([
html.Strong("PID: "),
html.A(pid, href=dashboard_link(pid), target="_blank"),
html.Br(),
html.Strong("Anomaly Score: "), f"{score:.4f}"
])
return current_time, pid, figure, details
except Exception as e:
print(f"Error updating visualization: {e}")
return current_time, '', {}, None
# Load data outside main block so Gunicorn can access it
df = None
try:
df = load_data(FILE_PATH, MONTH)
if len(df) == 0:
print("No data found")
exit(1)
if DECIMATE > 1:
df = df.iloc[::DECIMATE, :]
print(f'Decimated data to {len(df)} records')
except Exception as e:
print(f"Error loading data: {e}")
# Gunicorn entry point
server = app.server
# CLI mode
if __name__ == '__main__':
# parser = argparse.ArgumentParser(description='Interactive Point Cloud Anomaly Explorer')
# parser.add_argument('--file', default='scores.csv',
# help='Path to the CSV file containing anomaly scores')
# parser.add_argument('--month', help='Month to display in YYYYMM format (e.g., 202401)')
# parser.add_argument('--decimate', type=int, default=10, help='Decimation factor for time series plot')
# args = parser.parse_args()
# df = load_data(args.file, args.month)
# if len(df) == 0:
# print(f"No data found for month {args.month}")
# exit(1)
# if args.decimate > 1:
# df = df.iloc[::args.decimate, :]
# print(f'Decimated data to {len(df)} records')
app.run_server(debug=True)