Rimjhim Mittal commited on
Commit
d40dc23
·
1 Parent(s): 73d192f

added check for what to show on plot

Browse files
Files changed (1) hide show
  1. app.py +127 -96
app.py CHANGED
@@ -50,59 +50,68 @@ def run_simulation(param_inputs, mdf_model):
50
  chart_data = pd.DataFrame(output_values)
51
  chart_data['Time'] = times
52
  chart_data.set_index('Time', inplace=True)
53
- print(chart_data)
54
- show_simulation_results(chart_data)
55
- return None
56
- # def run_simulation(param_inputs, mdf_model):
57
- # mod_graph = mdf_model.graphs[0]
58
- # nodes = mod_graph.nodes
59
- # for node in nodes:
60
- # parameters = node.parameters
61
- # outputs = node.output_ports
62
- # eg = EvaluableGraph(mod_graph, verbose=False)
63
- # duration = param_inputs["Simulation Duration (s)"]
64
- # dt = param_inputs["Time Step (s)"]
65
- # t = 0
66
- # times = []
67
- # output_values = {op.value: [] for op in outputs}
68
- # while t <= duration:
69
- # times.append(t)
70
- # if t == 0:
71
- # eg.evaluate()
72
- # else:
73
- # eg.evaluate(time_increment=dt)
74
-
75
- # for param in output_values:
76
- # if any(operator in param for operator in "+-/*"):
77
- # eval_param = eg.enodes[node.id].evaluable_outputs[param]
78
- # else:
79
- # eval_param = eg.enodes[node.id].evaluable_parameters[param]
80
- # output_value = eval_param.curr_value
81
- # if isinstance(output_value, (list, np.ndarray)):
82
- # # Extract the scalar value from the list or array
83
- # output_values[param].append(output_value[0] if len(output_value) > 0 else np.nan)
84
- # else:
85
- # output_values[param].append(output_value)
86
- # t += dt
87
-
88
- # chart_data = pd.DataFrame(output_values)
89
- # chart_data['Time'] = times
90
- # chart_data.set_index('Time', inplace=True)
91
- # print(chart_data)
92
- # show_simulation_results(chart_data)
93
- # return None
94
 
95
  def show_simulation_results(chart_data):
96
- try:
97
- st.line_chart(chart_data, use_container_width=True, height=400)
98
- except Exception as e:
99
- st.error(f"Error plotting chart: {e}")
100
- st.write("Chart data types:")
101
- st.write(chart_data.dtypes)
102
- st.write("Chart data head:")
103
- st.write(chart_data.head())
104
- st.write("Chart data description:")
105
- st.write(chart_data.describe())
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  def show_mdf_graph(mdf_model):
108
  st.subheader("MDF Graph")
@@ -114,10 +123,17 @@ def show_json_output(mdf_model):
114
  st.subheader("JSON Output")
115
  st.json(mdf_model.to_json())
116
 
 
117
  def view_tabs(mdf_model, param_inputs): # view
118
  tab1, tab2, tab3 = st.tabs(["Simulation Results", "MDF Graph", "Json Output"])
119
  with tab1:
120
- run_simulation(param_inputs, mdf_model) # model
 
 
 
 
 
 
121
  with tab2:
122
  show_mdf_graph(mdf_model) # view
123
  with tab3:
@@ -146,35 +162,43 @@ def display_and_edit_array(array, key):
146
  def parameter_form_to_update_model_and_view(mdf_model, parameters, param_inputs, mod_graph, nodes):
147
  with st.form(key="parameter_form"):
148
  valid_inputs = True
149
-
150
- # Create two columns outside the loop
151
- col1, col2 = st.columns(2)
152
-
153
- for node_wise_parameter_key, node_wise_parameter in enumerate(parameters):
154
- for i, param in enumerate(node_wise_parameter):
155
- if isinstance(param.value, str) or param.value is None:
156
- continue
157
- key = f"{param.id}_{i}"
158
-
159
- # Alternate between columns
160
- current_col = col1 if i % 2 == 0 else col2
161
-
162
- with current_col:
163
- if isinstance(param.value, (list, np.ndarray)):
164
- st.write(f"{param.id}:")
165
- value = display_and_edit_array(param.value, key)
 
166
  else:
167
- if param.metadata:
168
- value = st.text_input(f"{param.metadata.get('description', param.id)} ({param.id})", value=str(param.value), key=key)
 
 
 
 
169
  else:
170
- value = st.text_input(f"{param.id}", value=str(param.value), key=key)
171
- try:
172
- param_inputs[param.id] = float(value)
173
- except ValueError:
174
- st.error(f"Invalid input for {param.id}. Please enter a valid number.")
175
- valid_inputs = False
176
-
177
- param_inputs[param.id] = value
 
 
 
178
  st.write("Simulation Parameters:")
179
  with st.container(border=True):
180
  # Add Simulation Duration and Time Step inputs
@@ -203,7 +227,9 @@ def parameter_form_to_update_model_and_view(mdf_model, parameters, param_inputs,
203
  for param in b:
204
  if param.id in param_inputs:
205
  param.value = param_inputs[param.id]
206
- view_tabs(mdf_model, param_inputs)
 
 
207
 
208
  # def upload_file_and_load_to_model():
209
  # st.write("Choose how to load the model:")
@@ -256,24 +282,26 @@ def parameter_form_to_update_model_and_view(mdf_model, parameters, param_inputs,
256
  # return None
257
 
258
  def upload_file_and_load_to_model():
259
- # col1, col2 = st.columns(2)
260
- # with col1:
261
  uploaded_file = st.file_uploader("Choose a JSON/YAML/BSON file", type=["json", "yaml", "bson"])
262
  if uploaded_file is not None:
263
  file_content = uploaded_file.getvalue()
264
  file_extension = uploaded_file.name.split('.')[-1].lower()
265
  return load_model_from_content(file_content, file_extension)
266
- github_url = st.text_input("Enter GitHub raw file URL:", placeholder="Enter GitHub raw file URL")
267
- if github_url:
268
- try:
269
- response = requests.get(github_url)
270
- response.raise_for_status()
271
- file_content = response.content
272
- file_extension = github_url.split('.')[-1].lower()
273
- return load_model_from_content(file_content, file_extension)
274
- except requests.RequestException as e:
275
- st.error(f"Error loading file from GitHub: {e}")
276
- return None
 
 
277
  # with col2:
278
  # example_models = {
279
  # "Newton Cooling Model": "https://raw.githubusercontent.com/ModECI/MDF/development/examples/MDF/NewtonCoolingModel.json",
@@ -306,9 +334,10 @@ def upload_file_and_load_to_model():
306
  # "RNN":"./examples/RNNs.json",
307
  # "IAF":"./examples/IAFs.json"
308
  }
309
- selected_model = st.selectbox("Choose an example model", list(example_models.keys()), index=None)
310
- if selected_model:
311
- return load_mdf_json(example_models[selected_model])
 
312
 
313
 
314
 
@@ -332,6 +361,8 @@ def load_model_from_content(file_content, file_extension):
332
 
333
 
334
  def main():
 
 
335
  header1, header2 = st.columns([1,12], vertical_alignment="top")
336
  with header1:
337
  st.image("logo.png", width=100)
 
50
  chart_data = pd.DataFrame(output_values)
51
  chart_data['Time'] = times
52
  chart_data.set_index('Time', inplace=True)
53
+ return chart_data
54
+ # print(chart_data)
55
+ # show_simulation_results(chart_data)
56
+ # return None
57
+
58
+ # def show_simulation_results(chart_data):
59
+ # try:
60
+ # if 'selected_columns' not in st.session_state:
61
+ # st.session_state.selected_columns = {col: True for col in chart_data.columns}
62
+
63
+ # def handle_checkbox_change():
64
+ # st.session_state.selected_columns[column] = st.session_state[f"checkbox_{column}"]
65
+
66
+ # columns = chart_data.columns
67
+ # for column in columns:
68
+ # if f"checkbox_{column}" not in st.session_state:
69
+ # st.session_state[f"checkbox_{column}"] = st.session_state.selected_columns[column]
70
+ # st.checkbox(
71
+ # f"Show {column}",
72
+ # value=st.session_state.selected_columns[column],
73
+ # key=f"checkbox_{column}",
74
+ # on_change=handle_checkbox_change
75
+ # )
76
+
77
+ # # Filter the data based on selected checkboxes
78
+ # filtered_data = chart_data[[col for col, selected in st.session_state.selected_columns.items() if selected]]
79
+
80
+ # # Display the line chart with filtered data
81
+ # st.line_chart(filtered_data, use_container_width=True, height=400)
82
+ # except Exception as e:
83
+ # st.error(f"Error plotting chart: {e}")
84
+ # st.write("Chart data types:")
85
+ # st.write(chart_data.dtypes)
86
+ # st.write("Chart data head:")
87
+ # st.write(chart_data.head())
88
+ # st.write("Chart data description:")
89
+ # st.write(chart_data.describe())
 
 
 
 
90
 
91
  def show_simulation_results(chart_data):
92
+ if chart_data is not None:
93
+ if 'selected_columns' not in st.session_state:
94
+ st.session_state.selected_columns = {col: True for col in chart_data.columns}
95
+
96
+ columns = chart_data.columns
97
+ for column in columns:
98
+ st.checkbox(
99
+ f"{column}",
100
+ value=st.session_state.selected_columns[column],
101
+ key=f"checkbox_{column}",
102
+ on_change=update_selected_columns,
103
+ args=(column,)
104
+ )
105
+
106
+ # Filter the data based on selected checkboxes
107
+ filtered_data = chart_data[[col for col, selected in st.session_state.selected_columns.items() if selected]]
108
+
109
+ # Display the line chart with filtered data
110
+ st.line_chart(filtered_data, use_container_width=True, height=400)
111
+
112
+ def update_selected_columns(column):
113
+ st.session_state.selected_columns[column] = st.session_state[f"checkbox_{column}"]
114
+
115
 
116
  def show_mdf_graph(mdf_model):
117
  st.subheader("MDF Graph")
 
123
  st.subheader("JSON Output")
124
  st.json(mdf_model.to_json())
125
 
126
+ # st.cache_data()
127
  def view_tabs(mdf_model, param_inputs): # view
128
  tab1, tab2, tab3 = st.tabs(["Simulation Results", "MDF Graph", "Json Output"])
129
  with tab1:
130
+ if 'simulation_results' not in st.session_state:
131
+ st.session_state.simulation_results = None
132
+
133
+ if st.session_state.simulation_results is not None:
134
+ show_simulation_results(st.session_state.simulation_results)
135
+ else:
136
+ st.write("Run the simulation to see results.") # model
137
  with tab2:
138
  show_mdf_graph(mdf_model) # view
139
  with tab3:
 
162
  def parameter_form_to_update_model_and_view(mdf_model, parameters, param_inputs, mod_graph, nodes):
163
  with st.form(key="parameter_form"):
164
  valid_inputs = True
165
+ st.write("Model Parameters:")
166
+ with st.container(border=True):
167
+ # Create two columns outside the loop
168
+ col1, col2, col3, col4 = st.columns(4)
169
+
170
+ for node_wise_parameter_key, node_wise_parameter in enumerate(parameters):
171
+ for i, param in enumerate(node_wise_parameter):
172
+ if isinstance(param.value, str) or param.value is None:
173
+ continue
174
+ key = f"{param.id}_{i}"
175
+
176
+ # Alternate between columns
177
+ if i % 4 == 0:
178
+ current_col = col1
179
+ elif i%4 == 1:
180
+ current_col = col2
181
+ elif i%4 == 2:
182
+ current_col = col3
183
  else:
184
+ current_col = col4
185
+
186
+ with current_col:
187
+ if isinstance(param.value, (list, np.ndarray)):
188
+ st.write(f"{param.id}:")
189
+ value = display_and_edit_array(param.value, key)
190
  else:
191
+ if param.metadata:
192
+ value = st.text_input(f"{param.metadata.get('description', param.id)} ({param.id})", value=str(param.value), key=key)
193
+ else:
194
+ value = st.text_input(f"{param.id}", value=str(param.value), key=key)
195
+ try:
196
+ param_inputs[param.id] = float(value)
197
+ except ValueError:
198
+ st.error(f"Invalid input for {param.id}. Please enter a valid number.")
199
+ valid_inputs = False
200
+
201
+ param_inputs[param.id] = value
202
  st.write("Simulation Parameters:")
203
  with st.container(border=True):
204
  # Add Simulation Duration and Time Step inputs
 
227
  for param in b:
228
  if param.id in param_inputs:
229
  param.value = param_inputs[param.id]
230
+ st.session_state.simulation_results = run_simulation(param_inputs, mdf_model)
231
+
232
+ view_tabs(mdf_model, param_inputs)
233
 
234
  # def upload_file_and_load_to_model():
235
  # st.write("Choose how to load the model:")
 
282
  # return None
283
 
284
  def upload_file_and_load_to_model():
285
+
286
+
287
  uploaded_file = st.file_uploader("Choose a JSON/YAML/BSON file", type=["json", "yaml", "bson"])
288
  if uploaded_file is not None:
289
  file_content = uploaded_file.getvalue()
290
  file_extension = uploaded_file.name.split('.')[-1].lower()
291
  return load_model_from_content(file_content, file_extension)
292
+ col2, col3 = st.columns(2)
293
+ with col2:
294
+ github_url = st.text_input("Enter GitHub raw file URL:", placeholder="Enter GitHub raw file URL")
295
+ if github_url:
296
+ try:
297
+ response = requests.get(github_url)
298
+ response.raise_for_status()
299
+ file_content = response.content
300
+ file_extension = github_url.split('.')[-1].lower()
301
+ return load_model_from_content(file_content, file_extension)
302
+ except requests.RequestException as e:
303
+ st.error(f"Error loading file from GitHub: {e}")
304
+ return None
305
  # with col2:
306
  # example_models = {
307
  # "Newton Cooling Model": "https://raw.githubusercontent.com/ModECI/MDF/development/examples/MDF/NewtonCoolingModel.json",
 
334
  # "RNN":"./examples/RNNs.json",
335
  # "IAF":"./examples/IAFs.json"
336
  }
337
+ with col3:
338
+ selected_model = st.selectbox("Choose an example model", list(example_models.keys()), index=None, placeholder="Dont have an MDF Model? Try some sample examples here!")
339
+ if selected_model:
340
+ return load_mdf_json(example_models[selected_model])
341
 
342
 
343
 
 
361
 
362
 
363
  def main():
364
+ if "checkbox" not in st.session_state:
365
+ st.session_state.checkbox = False
366
  header1, header2 = st.columns([1,12], vertical_alignment="top")
367
  with header1:
368
  st.image("logo.png", width=100)