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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import dash
|
| 3 |
+
from dash import dcc, html
|
| 4 |
+
import webbrowser
|
| 5 |
+
from src.viz import Visualizer as viz
|
| 6 |
+
import plotly.graph_objects as go
|
| 7 |
+
import os
|
| 8 |
+
import datetime
|
| 9 |
+
import plotly.express as px
|
| 10 |
+
import json
|
| 11 |
+
|
| 12 |
+
start_time = 0#240
|
| 13 |
+
end_time = 1600#600
|
| 14 |
+
|
| 15 |
+
start_date = datetime.datetime(2024, 6, 7, 12, 0, 0)
|
| 16 |
+
end_date = start_date + datetime.timedelta(seconds=end_time)
|
| 17 |
+
|
| 18 |
+
# Initialize the Dash app
|
| 19 |
+
app = dash.Dash(__name__, suppress_callback_exceptions=True)
|
| 20 |
+
|
| 21 |
+
# Global dictionary to store data
|
| 22 |
+
data_store = {}
|
| 23 |
+
|
| 24 |
+
def parse_action_trace(path, exclude = []):
|
| 25 |
+
"""
|
| 26 |
+
Parses action data from CSV files into a dictionary.
|
| 27 |
+
|
| 28 |
+
This function reads CSV files specified in a dictionary where each key-value pair
|
| 29 |
+
corresponds to an condition ID and its associated file. It extracts columns related to
|
| 30 |
+
time, action name, agent name, action end time, and attributes from each file and
|
| 31 |
+
stores them in a nested dictionary structure.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
files_dict (dict): A dictionary where keys are action IDs and values are file paths.
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
dict: A dictionary where each key is an condition ID and the value is another dictionary
|
| 38 |
+
containing parsed data from the corresponding CSV file.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
df = pd.read_csv(path, engine = "python")
|
| 42 |
+
|
| 43 |
+
# Convert to events list for timeline plotting
|
| 44 |
+
events = []
|
| 45 |
+
|
| 46 |
+
for i in range(len(df['time'])):
|
| 47 |
+
if not any(excl in df['actionName'][i] for excl in exclude):
|
| 48 |
+
event = {
|
| 49 |
+
'agent': df['agentName'][i],
|
| 50 |
+
'name': df['actionName'][i],
|
| 51 |
+
'start': start_date + datetime.timedelta(seconds=df['time'][i]),
|
| 52 |
+
'end': start_date + datetime.timedelta(seconds=df['time'][i] + max(df['actionEndTime'][i], 2)),
|
| 53 |
+
'duration': max(df['actionEndTime'][i], 2),
|
| 54 |
+
'attributes': df['attributes'][i]
|
| 55 |
+
}
|
| 56 |
+
events.append(event)
|
| 57 |
+
|
| 58 |
+
return events
|
| 59 |
+
|
| 60 |
+
def parse_all_data(path):
|
| 61 |
+
|
| 62 |
+
# Get the list of subfolders in the 'data' folder
|
| 63 |
+
subfolders = [f.name for f in os.scandir(path) if f.is_dir()]
|
| 64 |
+
|
| 65 |
+
# Load all data at the start of the program
|
| 66 |
+
# Load the CSV files into pandas DataFrames from the selected subfolder
|
| 67 |
+
data = {}
|
| 68 |
+
exclude = ['Detect_crash','Detect_conflict','Flight_Dynamics','Reroute_flight','Show_radar','Direct_to_waypoint','Change_heading','fly']
|
| 69 |
+
for subfolder in subfolders:
|
| 70 |
+
data[subfolder] = {
|
| 71 |
+
'wnd_action_trace': pd.read_csv(f'{path}/{subfolder}/actionTrace_Agent_PIC Blaze.csv'),
|
| 72 |
+
'all_action_trace': parse_action_trace(f'{path}/{subfolder}/actionTrace.csv', exclude),
|
| 73 |
+
}
|
| 74 |
+
data[subfolder]['aircraft_data'] = {}
|
| 75 |
+
for file in os.listdir(f'{path}/{subfolder}'):
|
| 76 |
+
if file.endswith('_acstate.csv'):
|
| 77 |
+
aircraft_id = file.split('_')[0]
|
| 78 |
+
data[subfolder]['aircraft_data'][aircraft_id] = pd.read_csv(f'{path}/{subfolder}/{file}')
|
| 79 |
+
|
| 80 |
+
subfolder_labels = [{'label': i, 'value': i} for i in subfolders]
|
| 81 |
+
|
| 82 |
+
return subfolder_labels, data
|
| 83 |
+
|
| 84 |
+
# Create the layout for the app
|
| 85 |
+
app.layout = html.Div([
|
| 86 |
+
html.Div([
|
| 87 |
+
html.Div("Input the relative path to your results folder, then click 'Submit':", id='text1'),
|
| 88 |
+
dcc.Input(
|
| 89 |
+
id='path-input',
|
| 90 |
+
# value='data',
|
| 91 |
+
type='text',
|
| 92 |
+
placeholder='Type your path... For example, ../wmc5.1/Scenario/AAMv2/Results',
|
| 93 |
+
style={'width': '90%'} # Make the input wider
|
| 94 |
+
),
|
| 95 |
+
html.Button('Submit', id='submit-button', n_clicks=0),
|
| 96 |
+
# Create a dropdown menu with the subfolders as options
|
| 97 |
+
html.Div("Once all subfolders are loaded (representing the different conditions you ran in WMC), you can select which one to plot:", id='text2'),
|
| 98 |
+
dcc.Dropdown(
|
| 99 |
+
id='subfolder-dropdown',
|
| 100 |
+
value=None #subfolders[0] # Default value
|
| 101 |
+
)
|
| 102 |
+
], style={'width': '50%', 'border': '1px solid gray'}),
|
| 103 |
+
|
| 104 |
+
html.Div([
|
| 105 |
+
html.Div([
|
| 106 |
+
dcc.Graph(id='map'), # Second graph
|
| 107 |
+
dcc.Dropdown(
|
| 108 |
+
id='variable-dropdown',
|
| 109 |
+
# options=[{'label': i, 'value': i} for i in subfolders],
|
| 110 |
+
value=None #subfolders[0] # Default value
|
| 111 |
+
),
|
| 112 |
+
dcc.Graph(id='altitude-series') # Third graph
|
| 113 |
+
], style={'width': '39%', 'display': 'inline-block', 'border': '1px solid gray'}),
|
| 114 |
+
html.Div([
|
| 115 |
+
dcc.Tabs(id='tabs-example-1', value='tab-1', children=[
|
| 116 |
+
dcc.Tab(label='Traditional Action Trace', value='tab-1'),
|
| 117 |
+
dcc.Tab(label='What`s Next Diagram', value='tab-2'),
|
| 118 |
+
]),
|
| 119 |
+
html.Div(id='tabs-example-content-1'),
|
| 120 |
+
html.Div([dcc.Graph(id='timeline')], id='tab-1-content', style={'display': 'none'}), # Fourth graph
|
| 121 |
+
html.Div([dcc.Graph(id='time-series')], id='tab-2-content', style={'display': 'none'}), # First graph
|
| 122 |
+
], style={'width': '59%', 'display': 'inline-block', 'border': '1px solid gray'})
|
| 123 |
+
], style={'display': 'flex'}),
|
| 124 |
+
|
| 125 |
+
html.Div(
|
| 126 |
+
dcc.Slider(
|
| 127 |
+
id='time-slider',
|
| 128 |
+
min=start_time,
|
| 129 |
+
max=end_time,
|
| 130 |
+
value=start_time+100,
|
| 131 |
+
marks={str(time): str(time) for time in range(start_time, end_time+1, 50)},
|
| 132 |
+
updatemode='drag'
|
| 133 |
+
),
|
| 134 |
+
style={'width': '100%'} # Set the width of the div containing the slider to 80% of the container
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
])
|
| 138 |
+
|
| 139 |
+
@app.callback(
|
| 140 |
+
dash.dependencies.Output('tab-1-content', 'style'),
|
| 141 |
+
dash.dependencies.Output('tab-2-content', 'style'),
|
| 142 |
+
dash.dependencies.Input('tabs-example-1', 'value')
|
| 143 |
+
)
|
| 144 |
+
def render_content(tab):
|
| 145 |
+
if tab == 'tab-1':
|
| 146 |
+
return {'display': 'block'}, {'display': 'none'}
|
| 147 |
+
elif tab == 'tab-2':
|
| 148 |
+
return {'display': 'none'}, {'display': 'block'}
|
| 149 |
+
|
| 150 |
+
# Load data when the app starts and store it in the hidden div
|
| 151 |
+
@app.callback(
|
| 152 |
+
dash.dependencies.Output('subfolder-dropdown', 'options'),
|
| 153 |
+
dash.dependencies.Output('variable-dropdown', 'options'),
|
| 154 |
+
[dash.dependencies.Input('submit-button', 'n_clicks')],
|
| 155 |
+
[dash.dependencies.Input('path-input', 'value')],
|
| 156 |
+
)
|
| 157 |
+
def load_data(n_clicks, selected_path):
|
| 158 |
+
print("selected path is",selected_path)
|
| 159 |
+
global data_store
|
| 160 |
+
if n_clicks > 0:
|
| 161 |
+
if selected_path is None or not os.path.isdir(selected_path):
|
| 162 |
+
return [], []
|
| 163 |
+
subfolder_labels, data = parse_all_data(selected_path)
|
| 164 |
+
print('subfolders',subfolder_labels)
|
| 165 |
+
if data is None:
|
| 166 |
+
data = {}
|
| 167 |
+
# Store data in the global dictionary
|
| 168 |
+
data_store = data
|
| 169 |
+
labels = list(data[list(data.keys())[0]]['aircraft_data'][list(data[list(data.keys())[0]]['aircraft_data'].keys())[0]].columns.tolist()) # Extracting column names for the first aircraft-specific dataframe
|
| 170 |
+
return subfolder_labels, labels
|
| 171 |
+
else:
|
| 172 |
+
return [], []
|
| 173 |
+
|
| 174 |
+
# Define the callback to update the graphs based on the slider value
|
| 175 |
+
@app.callback(
|
| 176 |
+
dash.dependencies.Output('time-series', 'figure'),
|
| 177 |
+
dash.dependencies.Output('map', 'figure'),
|
| 178 |
+
dash.dependencies.Output('altitude-series', 'figure'),
|
| 179 |
+
dash.dependencies.Output('timeline', 'figure'),
|
| 180 |
+
# dash.dependencies.Input('path-input', 'value'),
|
| 181 |
+
[dash.dependencies.Input('subfolder-dropdown', 'value'),
|
| 182 |
+
dash.dependencies.Input('time-slider', 'value'),
|
| 183 |
+
dash.dependencies.Input('variable-dropdown','value')]
|
| 184 |
+
)
|
| 185 |
+
# def update_graph(selected_subfolder, selected_time):
|
| 186 |
+
# # Load the CSV files into pandas DataFrames from the selected subfolder
|
| 187 |
+
# df1 = pd.read_csv(f'data/{selected_subfolder}/actionTrace_Agent_PIC Blaze.csv')
|
| 188 |
+
# df2 = pd.read_csv(f'data/{selected_subfolder}/SNLBlaze_acstate.csv')
|
| 189 |
+
# df3 = pd.read_csv(f'data/{selected_subfolder}/GCCRaven_acstate.csv')
|
| 190 |
+
|
| 191 |
+
# exclude = ['Detect_crash','Detect_conflict','Flight_Dynamics','Reroute_flight','Show_radar','Direct_to_waypoint','Change_heading']
|
| 192 |
+
# events = parse_action_trace(f'data/{selected_subfolder}/actionTrace.csv', exclude)
|
| 193 |
+
|
| 194 |
+
def update_graph(selected_subfolder, selected_time, selected_variable):
|
| 195 |
+
|
| 196 |
+
if selected_subfolder not in data_store:
|
| 197 |
+
return go.Figure(), go.Figure(), go.Figure(layout=dict(autosize=True, width=None, height=300)), go.Figure()
|
| 198 |
+
|
| 199 |
+
wnd_action_trace = data_store[selected_subfolder].get('wnd_action_trace', pd.DataFrame())
|
| 200 |
+
all_action_trace = data_store[selected_subfolder].get('all_action_trace', [])
|
| 201 |
+
aircraft_data = data_store[selected_subfolder].get('aircraft_data', {})
|
| 202 |
+
|
| 203 |
+
filtered_wnd_action_trace = wnd_action_trace[(wnd_action_trace['time'] >= start_time) & (wnd_action_trace['time'] <= selected_time)]
|
| 204 |
+
|
| 205 |
+
filtered_all_action_trace = []
|
| 206 |
+
for event in all_action_trace:
|
| 207 |
+
if (event['start'] - start_date).total_seconds() <= selected_time:
|
| 208 |
+
event_copy = event.copy() # Create a local copy of the event
|
| 209 |
+
if (event_copy['end'] - start_date).total_seconds() > selected_time:
|
| 210 |
+
event_copy['end'] = start_date + datetime.timedelta(seconds=selected_time)
|
| 211 |
+
filtered_all_action_trace.append(event_copy)
|
| 212 |
+
|
| 213 |
+
ac_data = {}
|
| 214 |
+
for aircraft_id, df in aircraft_data.items():
|
| 215 |
+
filtered_df = df[(df['time'] >= start_time) & (df['time'] <= selected_time)]
|
| 216 |
+
ac_data[aircraft_id] = filtered_df
|
| 217 |
+
|
| 218 |
+
fig1 = go.Figure(layout=dict(autosize=True, width=None, height=500))
|
| 219 |
+
fig1['layout']['uirevision'] = 'Hello world!'
|
| 220 |
+
fig1 = viz.plot_trajectory(fig1, ac_data)
|
| 221 |
+
|
| 222 |
+
fig2 = go.Figure(layout=dict(autosize=True, width=700, height=700))
|
| 223 |
+
fig2 = viz.wnd_visualization(fig2, filtered_wnd_action_trace, selected_time, start_time, end_time)
|
| 224 |
+
fig2['layout']['uirevision'] = 'Hello world!'
|
| 225 |
+
|
| 226 |
+
if selected_variable is not None:
|
| 227 |
+
fig3 = go.Figure(layout=dict(autosize=True, width=None, height=300))
|
| 228 |
+
for aircraft_id, df in ac_data.items():
|
| 229 |
+
fig3.add_trace(go.Scatter(x=df['time'], y=df[selected_variable], mode='lines', name=aircraft_id))
|
| 230 |
+
fig3.update_layout(xaxis_title='Real Time', yaxis_title=selected_variable, showlegend=True, xaxis=dict(range=[start_time, end_time]))#, yaxis=dict(range=[0, 1200])
|
| 231 |
+
fig3['layout']['uirevision'] = 'Hello world!'
|
| 232 |
+
|
| 233 |
+
else:
|
| 234 |
+
fig3 = go.Figure(layout=dict(autosize=True, width=None, height=300))
|
| 235 |
+
fig4 = go.Figure(layout=dict(autosize=True, width=None, height=700))
|
| 236 |
+
fig4 = viz.timeline(fig4, filtered_all_action_trace, selected_time, start_date, end_date)
|
| 237 |
+
fig4['layout']['uirevision'] = 'Hello world!'
|
| 238 |
+
|
| 239 |
+
return fig2, fig1, fig3, fig4
|
| 240 |
+
|
| 241 |
+
# Run the app
|
| 242 |
+
if __name__ == '__main__':
|
| 243 |
+
|
| 244 |
+
webbrowser.open_new("http://127.0.0.1:8050/")
|
| 245 |
+
app.run_server(debug=True)
|
src/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
''' This file makes the folder it is stored in into
|
| 2 |
+
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import webbrowser
|
| 2 |
+
import dash as dcc
|
| 3 |
+
import dash as html
|
| 4 |
+
import numpy as np
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
import plotly.express as px
|
| 7 |
+
import networkx as nx
|
| 8 |
+
import datetime
|
| 9 |
+
|
| 10 |
+
class Visualizer:
|
| 11 |
+
|
| 12 |
+
def wnd_visualization(figure_handle, dataframe, current_time, start_time = 0, end_time = 10^6):
|
| 13 |
+
# Diagonal line y=x
|
| 14 |
+
figure_handle.add_trace(go.Scatter(x=[start_time, end_time], y=[start_time, end_time], mode='lines', line=dict(color='black', dash='dash')))
|
| 15 |
+
|
| 16 |
+
# Dotted lines from the point to axes
|
| 17 |
+
figure_handle.add_trace(go.Scatter(x=[current_time, current_time, start_time], y=[start_time, current_time, current_time], mode='lines', line=dict(color='black', dash='dot')))
|
| 18 |
+
|
| 19 |
+
for time, name in dataframe[['time', 'actionName']].values:
|
| 20 |
+
figure_handle.add_trace(go.Scatter(x=[time], y=[time], mode='markers', marker=dict(color='black', size=10)))
|
| 21 |
+
|
| 22 |
+
timestamps_and_ids_dict = {}
|
| 23 |
+
|
| 24 |
+
for index, row in dataframe.iterrows():
|
| 25 |
+
array_data = row['attributes']
|
| 26 |
+
if isinstance(array_data, str):
|
| 27 |
+
timestamp_id_triples = []
|
| 28 |
+
for pair in array_data.split(';'):
|
| 29 |
+
triple = pair.split('|')
|
| 30 |
+
triple.append("")
|
| 31 |
+
timestamp_id_triples.append(triple)
|
| 32 |
+
for triple in timestamp_id_triples:
|
| 33 |
+
if '(' in triple[1]:
|
| 34 |
+
triple[1], triple[2] = triple[1].split('(')
|
| 35 |
+
else:
|
| 36 |
+
timestamp_id_triples = []
|
| 37 |
+
timestamp_id_triples.sort(key=lambda x: float(x[0][0]))
|
| 38 |
+
|
| 39 |
+
timestamp_id_dict = {float(triple[0]): str(triple[1]) for triple in timestamp_id_triples}
|
| 40 |
+
timestamps_and_ids_dict[row['time']] = timestamp_id_dict
|
| 41 |
+
|
| 42 |
+
timestamps_before_simulation_time = {timestamp: data for timestamp, data in timestamps_and_ids_dict.items() if timestamp <= current_time}
|
| 43 |
+
print(timestamps_before_simulation_time)
|
| 44 |
+
mental_model_over_time = {}
|
| 45 |
+
|
| 46 |
+
if timestamps_before_simulation_time:
|
| 47 |
+
for mm_time, array_timestamps_and_ids in timestamps_before_simulation_time.items():
|
| 48 |
+
for timestamp, value in array_timestamps_and_ids.items():
|
| 49 |
+
if value in mental_model_over_time:
|
| 50 |
+
# Value is already in the dictionary, append the timestamp to the existing list
|
| 51 |
+
mental_model_over_time[value].append((mm_time, timestamp))
|
| 52 |
+
else:
|
| 53 |
+
# Value is not in the dictionary, create a new list with the timestamp
|
| 54 |
+
mental_model_over_time[value] = [(mm_time, timestamp)]
|
| 55 |
+
|
| 56 |
+
# Get last update on mental model
|
| 57 |
+
previous_timestamp, array_timestamps_and_ids = max(timestamps_before_simulation_time.items(), key=lambda x: x[0])
|
| 58 |
+
|
| 59 |
+
# Assuming mental model does not change in between, load this as current mental model into dictionary
|
| 60 |
+
for timestamp, value in array_timestamps_and_ids.items():
|
| 61 |
+
if value in mental_model_over_time:
|
| 62 |
+
# Value is already in the dictionary, append the timestamp to the existing list
|
| 63 |
+
mental_model_over_time[value].append((current_time, timestamp))
|
| 64 |
+
else:
|
| 65 |
+
# Value is not in the dictionary, create a new list with the timestamp
|
| 66 |
+
mental_model_over_time[value] = [(current_time, timestamp)]
|
| 67 |
+
|
| 68 |
+
# Add text box with name of event
|
| 69 |
+
figure_handle.add_annotation(x=current_time, y=timestamp, text=value, showarrow=True, arrowhead=1, arrowcolor='black', arrowwidth=2)
|
| 70 |
+
|
| 71 |
+
for label, coordinates in mental_model_over_time.items():
|
| 72 |
+
for i in range(len(coordinates) - 1):
|
| 73 |
+
x = [coordinates[i][0], coordinates[i + 1][0], coordinates[i + 1][0]]
|
| 74 |
+
y = [coordinates[i][1], coordinates[i][1], coordinates[i + 1][1]]
|
| 75 |
+
|
| 76 |
+
if all(xi <= yi for xi, yi in zip(x, y)):
|
| 77 |
+
figure_handle.add_trace(go.Scatter(x=x, y=y, mode='lines', line=dict(color='blue'), marker_symbol='triangle-up'))
|
| 78 |
+
|
| 79 |
+
if all(xi >= yi for xi, yi in zip(x, y)):
|
| 80 |
+
figure_handle.add_trace(go.Scatter(x=x, y=y, mode='lines', line=dict(color='gray'), marker_symbol='circle'))
|
| 81 |
+
|
| 82 |
+
figure_handle.update_layout(
|
| 83 |
+
xaxis_title='Real Time',
|
| 84 |
+
yaxis_title='Comprehension of Timeline of Events',
|
| 85 |
+
showlegend=False,
|
| 86 |
+
xaxis=dict(
|
| 87 |
+
range=[start_time,end_time]
|
| 88 |
+
),
|
| 89 |
+
yaxis=dict(
|
| 90 |
+
range=[start_time,end_time],
|
| 91 |
+
scaleanchor="x",
|
| 92 |
+
scaleratio=1
|
| 93 |
+
)
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
return figure_handle
|
| 97 |
+
|
| 98 |
+
def plot_trajectory(figure_handle, parsed_data, uptime=float('inf'), background_image=None):
|
| 99 |
+
fig = figure_handle
|
| 100 |
+
|
| 101 |
+
if background_image:
|
| 102 |
+
fig.add_layout_image(
|
| 103 |
+
source=background_image,
|
| 104 |
+
xref="x",
|
| 105 |
+
yref="y",
|
| 106 |
+
x=-96.88,
|
| 107 |
+
y=33.16,
|
| 108 |
+
sizex=0.23,
|
| 109 |
+
sizey=0.44,
|
| 110 |
+
sizing="fill",
|
| 111 |
+
opacity=0.5,
|
| 112 |
+
layer="below"
|
| 113 |
+
)
|
| 114 |
+
else:
|
| 115 |
+
fig.update_layout(
|
| 116 |
+
mapbox_style="open-street-map",
|
| 117 |
+
mapbox_center_lon=-96.765,
|
| 118 |
+
mapbox_center_lat=32.95,
|
| 119 |
+
mapbox_zoom=10
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# Create a graph for the flight plans
|
| 123 |
+
G = nx.Graph()
|
| 124 |
+
|
| 125 |
+
# Define waypoints and their positions with new names from the embedded code
|
| 126 |
+
waypoints = {
|
| 127 |
+
"NTI": (-96.7535, 32.928), "NTHW": (-96.749, 32.8573), "RUBL": (-96.7588, 32.78),
|
| 128 |
+
"HW342": (-96.8003, 32.7508), "TLWY": (-96.807, 32.769), "4DT": (-96.8508, 32.846),
|
| 129 |
+
"T57": (-96.686, 32.888), "FSC": (-96.8213, 33.1413), "PLN": (-96.7275, 33.0297)
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
# Add edges between waypoints to the graph with updated names
|
| 133 |
+
edges = [("NTI", "NTHW"), ("NTHW", "RUBL"), ("RUBL", "HW342"), ("HW342", "TLWY"),
|
| 134 |
+
("TLWY", "4DT"), ("T57", "NTI"), ("FSC", "PLN"),("PLN","NTI")]
|
| 135 |
+
G.add_edges_from(edges)
|
| 136 |
+
|
| 137 |
+
# Draw the graph with smaller waypoint symbols in gray and keep the node labels
|
| 138 |
+
for edge in G.edges():
|
| 139 |
+
x_values = [waypoints[edge[0]][0], waypoints[edge[1]][0]]
|
| 140 |
+
y_values = [waypoints[edge[0]][1], waypoints[edge[1]][1]]
|
| 141 |
+
fig.add_trace(go.Scattermapbox(lon=x_values, lat=y_values, mode='lines', line=dict(color='gray'), showlegend=False))#, dash='dash'
|
| 142 |
+
|
| 143 |
+
for node in G.nodes():
|
| 144 |
+
x_value = waypoints[node][0]
|
| 145 |
+
y_value = waypoints[node][1]
|
| 146 |
+
fig.add_trace(go.Scattermapbox(lon=[x_value], lat=[y_value], mode='markers', marker=dict(size=5, color='gray'), showlegend=False))#, symbol='pentagon'
|
| 147 |
+
# for node, (x_value, y_value) in waypoints.items():
|
| 148 |
+
# fig.add_annotation(lon=x_value, lat=y_value, text=node, showarrow=False, font=dict(size=6, color='gray'), xanchor='left', yanchor='bottom')
|
| 149 |
+
|
| 150 |
+
# Add legend label for waypoints and corridors
|
| 151 |
+
legend_labels = []
|
| 152 |
+
legend_labels.append("Corridors")
|
| 153 |
+
legend_labels.append("Waypoints")
|
| 154 |
+
|
| 155 |
+
colors = ['blue', 'red', 'green', 'purple', 'orange', 'yellow', 'pink', 'cyan', 'magenta', 'brown']
|
| 156 |
+
color_index = 0
|
| 157 |
+
|
| 158 |
+
for ac_name, data in parsed_data.items():
|
| 159 |
+
mask = (data['time'] >= 0) & (data['time'] <= uptime)
|
| 160 |
+
filtered_xdata = data['longitude_deg'][mask]
|
| 161 |
+
filtered_ydata = data['latitude_deg'][mask]
|
| 162 |
+
filtered_heading = data['heading_deg'][mask]
|
| 163 |
+
filtered_altitude = data['altitude_ft'][mask] # In case we ever want to do 3D visualizations
|
| 164 |
+
|
| 165 |
+
fig.add_trace(go.Scattermapbox(#Scatter3d possibly for 3D but issue with Scattermapbox not being compatible
|
| 166 |
+
mode="lines",
|
| 167 |
+
lon=filtered_xdata,
|
| 168 |
+
lat=filtered_ydata,
|
| 169 |
+
line=dict(width=2, color=colors[color_index]),
|
| 170 |
+
name=ac_name
|
| 171 |
+
))
|
| 172 |
+
|
| 173 |
+
if len(filtered_xdata) > 0 and len(filtered_ydata) > 0:
|
| 174 |
+
current_heading = filtered_heading.iloc[-1]
|
| 175 |
+
fig.add_trace(go.Scattermapbox(
|
| 176 |
+
mode="markers",
|
| 177 |
+
lon=[filtered_xdata.iloc[-1]],
|
| 178 |
+
lat=[filtered_ydata.iloc[-1]],
|
| 179 |
+
marker=dict(size=10, color=colors[color_index]),#, symbol=['cross']), #To make custom markers, you need MapBox access token (to use any of Mapbox's tools, APIs, or SDK)
|
| 180 |
+
name=ac_name + " Current Location"
|
| 181 |
+
))
|
| 182 |
+
|
| 183 |
+
color_index = (color_index + 1) % len(colors)
|
| 184 |
+
|
| 185 |
+
fig.update_layout(
|
| 186 |
+
mapbox=dict(
|
| 187 |
+
center=dict(lon=-96.765, lat=32.95),
|
| 188 |
+
zoom=9
|
| 189 |
+
),
|
| 190 |
+
margin=dict(l=20, r=20, t=20, b=20)
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
return fig
|
| 194 |
+
|
| 195 |
+
def timeline(figure_handle, events, current_time = 0, start_date = 0, end_date = 0):
|
| 196 |
+
|
| 197 |
+
category_order = sorted(list(set([e['agent'] for e in events])))
|
| 198 |
+
|
| 199 |
+
figure_handle = px.timeline(
|
| 200 |
+
events, x_start="start", x_end="end", y="agent",
|
| 201 |
+
hover_data=['attributes', 'duration'],
|
| 202 |
+
color='name',# height=400, width=1600,
|
| 203 |
+
category_orders={'agent': category_order}
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# Add a vertical dashed line at x = current_time
|
| 207 |
+
current_datetime = start_date + datetime.timedelta(seconds=current_time)
|
| 208 |
+
figure_handle.add_shape(
|
| 209 |
+
type="line",
|
| 210 |
+
x0=current_datetime, y0=0,
|
| 211 |
+
x1=current_datetime, y1=1,
|
| 212 |
+
yref="paper",
|
| 213 |
+
line=dict(
|
| 214 |
+
color="Black",
|
| 215 |
+
width=2,
|
| 216 |
+
dash="dash",
|
| 217 |
+
)
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
figure_handle.update_layout(
|
| 221 |
+
xaxis_range=[start_date, end_date]#,
|
| 222 |
+
# width=600,
|
| 223 |
+
# height=500
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
return figure_handle
|