Rimjhim Mittal commited on
Commit
b218236
·
unverified ·
2 Parent(s): 3115cba7cc6f57

Merge pull request #13 from ModECI/development

Browse files
Files changed (3) hide show
  1. app.py +76 -64
  2. examples/keras_to_MDF.json +0 -0
  3. page_icon.png +0 -0
app.py CHANGED
@@ -2,11 +2,11 @@ import streamlit as st, pandas as pd, os, io
2
  from modeci_mdf.mdf import Model, Graph, Node, Parameter, OutputPort
3
  from modeci_mdf.utils import load_mdf_json, load_mdf, load_mdf_yaml
4
  from modeci_mdf.execution_engine import EvaluableGraph, EvaluableOutput
5
- import json
6
  import numpy as np
7
  import requests
8
- st.set_page_config(layout="wide", page_icon="logo.png", page_title="Model Description Format", menu_items={
9
- 'Report a bug': "https://github.com/ModECI/MDF/",
10
  'About': "ModECI (Model Exchange and Convergence Initiative) is a multi-investigator collaboration that aims to develop a standardized format for exchanging computational models across diverse software platforms and domains of scientific research and technology development, with a particular focus on neuroscience, Machine Learning and Artificial Intelligence. Refer to https://modeci.org/ for more."
11
  })
12
 
@@ -24,9 +24,6 @@ def run_simulation(param_inputs, mdf_model, stateful):
24
  if stateful:
25
  duration = param_inputs["Simulation Duration (s)"]
26
  dt = param_inputs["Time Step (s)"]
27
-
28
-
29
-
30
  for node in nodes:
31
  eg = EvaluableGraph(mod_graph, verbose=False)
32
  t = 0
@@ -59,7 +56,7 @@ def run_simulation(param_inputs, mdf_model, stateful):
59
  for node in nodes:
60
  eg = EvaluableGraph(mod_graph, verbose=False)
61
  eg.evaluate()
62
- all_node_results[node.id] = pd.DataFrame({op.value: [float(eg.enodes[node.id].evaluable_outputs[op.id].curr_value)] for op in node.output_ports})
63
 
64
  return all_node_results
65
  def show_simulation_results(all_node_results, stateful_nodes):
@@ -71,24 +68,26 @@ def show_simulation_results(all_node_results, stateful_nodes):
71
  st.session_state.selected_columns = {node_id: {col: True for col in chart_data.columns}}
72
  elif node_id not in st.session_state.selected_columns:
73
  st.session_state.selected_columns[node_id] = {col: True for col in chart_data.columns}
74
- columns = chart_data.columns
75
- for column in columns:
76
- st.checkbox(
77
- f"{column}",
78
- value=st.session_state.selected_columns[node_id][column],
79
- key=f"checkbox_{node_id}_{column}",
80
- on_change=update_selected_columns,
81
- args=(node_id, column,)
82
- )
83
-
84
  # Filter the data based on selected checkboxes
85
  filtered_data = chart_data[[col for col, selected in st.session_state.selected_columns[node_id].items() if selected]]
86
-
87
  # Display the line chart with filtered data
88
  st.line_chart(filtered_data, use_container_width=True, height=400)
 
 
 
 
 
 
 
 
 
 
 
 
89
  else:
90
- st.write(all_node_results[node_id])
91
-
92
 
93
  def update_selected_columns(node_id, column):
94
  st.session_state.selected_columns[node_id][column] = st.session_state[f"checkbox_{node_id}_{column}"]
@@ -99,55 +98,54 @@ def show_mdf_graph(mdf_model):
99
  image_path = mdf_model.id + ".png"
100
  st.image(image_path, caption="Model Graph Visualization")
101
 
102
- def show_json_output(mdf_model):
103
  st.subheader("JSON Model")
104
  st.json(mdf_model.to_json())
105
 
106
- # st.cache_data()
107
  def view_tabs(mdf_model, param_inputs, stateful): # view
108
  tab1, tab2, tab3 = st.tabs(["Simulation Results", "MDF Graph", "Json Model"])
109
  with tab1:
110
- if stateful:
111
- if 'simulation_results' not in st.session_state:
112
- st.session_state.simulation_results = None
113
-
114
- if st.session_state.simulation_results is not None:
115
- show_simulation_results(st.session_state.simulation_results, stateful)
116
- else:
117
- st.write("Run the simulation to see results.") # model
118
  else:
119
- if 'simulation_results' not in st.session_state:
120
- st.session_state.simulation_results = None
121
-
122
- if st.session_state.simulation_results is not None:
123
- show_simulation_results(st.session_state.simulation_results, stateful)
124
- else:
125
- st.write("Stateless.")
126
-
127
  with tab2:
128
  show_mdf_graph(mdf_model) # view
129
  with tab3:
130
- show_json_output(mdf_model) # view
131
 
132
  def display_and_edit_array(array, key):
133
  if isinstance(array, list):
134
  array = np.array(array)
135
-
136
  rows, cols = array.shape if array.ndim > 1 else (1, len(array))
137
-
138
- edited_array = []
139
- for i in range(rows):
140
- row = []
141
- for j in range(cols):
142
- value = array[i][j] if array.ndim > 1 else array[i]
143
- edited_value = st.text_input(f"[{i}][{j}]", value=str(value), key=f"{key}_{i}_{j}")
144
- try:
145
- row.append(float(edited_value))
146
- except ValueError:
147
- st.error(f"Invalid input for [{i}][{j}]. Please enter a valid number.")
148
- edited_array.append(row)
149
-
150
- return np.array(edited_array)
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  def parameter_form_to_update_model_and_view(mdf_model):
153
  mod_graph = mdf_model.graphs[0]
@@ -186,8 +184,13 @@ def parameter_form_to_update_model_and_view(mdf_model):
186
 
187
  # Create four columns for each node
188
  col1, col2, col3, col4 = st.columns(4)
189
-
190
  for i, param in enumerate(node.parameters):
 
 
 
 
 
191
  if isinstance(param.value, str) or param.value is None:
192
  continue
193
  key = f"{param.id}_{node_index}_{i}"
@@ -233,7 +236,7 @@ def parameter_form_to_update_model_and_view(mdf_model):
233
  valid_inputs = False
234
 
235
  run_button = st.form_submit_button("Run Simulation")
236
-
237
  if run_button:
238
  if valid_inputs:
239
  for node in nodes:
@@ -241,8 +244,11 @@ def parameter_form_to_update_model_and_view(mdf_model):
241
  if param.id in param_inputs:
242
  param.value = param_inputs[param.id]
243
  st.session_state.simulation_results = run_simulation(param_inputs, mdf_model, stateful)
244
-
245
- view_tabs(mdf_model, param_inputs, stateful_nodes)
 
 
 
246
 
247
  def upload_file_and_load_to_model():
248
 
@@ -250,15 +256,16 @@ def upload_file_and_load_to_model():
250
  github_url = st.sidebar.text_input("Enter GitHub raw file URL:", placeholder="Enter GitHub raw file URL")
251
  example_models = {
252
  "Newton Cooling Model": "./examples/NewtonCoolingModel.json",
253
- # "ABCD": "./examples/ABCD.json",
254
  "FN": "./examples/FN.mdf.json",
255
  "States": "./examples/States.json",
256
- "Swicthed RLC Circuit": "./examples/switched_rlc_circuit.json",
257
  "Simple":"./examples/Simple.json",
258
- # "Arrays":"./examples/Arrays.json",
259
- # "RNN":"./examples/RNNs.json",
260
  "IAF":"./examples/IAFs.json",
261
- "Izhikevich Test":"./examples/IzhikevichTest.mdf.json"
 
262
  }
263
  selected_model = st.sidebar.selectbox("Choose an example model", list(example_models.keys()), index=None, placeholder="Dont have an MDF Model? Try some sample examples here!")
264
 
@@ -290,7 +297,11 @@ def load_model_from_content(file_content, file_extension):
290
  json_data = json.loads(file_content)
291
  mdf_model = Model.from_dict(json_data)
292
  elif file_extension in ['yaml', 'yml']:
293
- mdf_model = load_mdf_yaml(io.BytesIO(file_content))
 
 
 
 
294
  else:
295
  st.error("Unsupported file format. Please use JSON or YAML files.")
296
  return None
@@ -311,6 +322,7 @@ def main():
311
  mdf_model = upload_file_and_load_to_model() # controller
312
 
313
  if mdf_model:
 
314
  header1, header2 = st.columns([1, 8], vertical_alignment="top")
315
  with header1:
316
  with st.container():
 
2
  from modeci_mdf.mdf import Model, Graph, Node, Parameter, OutputPort
3
  from modeci_mdf.utils import load_mdf_json, load_mdf, load_mdf_yaml
4
  from modeci_mdf.execution_engine import EvaluableGraph, EvaluableOutput
5
+ import json, yaml, bson
6
  import numpy as np
7
  import requests
8
+ st.set_page_config(layout="wide", page_icon="page_icon.png", page_title="Model Description Format", menu_items={
9
+ 'Report a bug': "https://github.com/ModECI/MDF-UI/",
10
  'About': "ModECI (Model Exchange and Convergence Initiative) is a multi-investigator collaboration that aims to develop a standardized format for exchanging computational models across diverse software platforms and domains of scientific research and technology development, with a particular focus on neuroscience, Machine Learning and Artificial Intelligence. Refer to https://modeci.org/ for more."
11
  })
12
 
 
24
  if stateful:
25
  duration = param_inputs["Simulation Duration (s)"]
26
  dt = param_inputs["Time Step (s)"]
 
 
 
27
  for node in nodes:
28
  eg = EvaluableGraph(mod_graph, verbose=False)
29
  t = 0
 
56
  for node in nodes:
57
  eg = EvaluableGraph(mod_graph, verbose=False)
58
  eg.evaluate()
59
+ all_node_results[node.id] = pd.DataFrame({op.value: [eg.enodes[node.id].evaluable_outputs[op.id].curr_value] for op in node.output_ports})
60
 
61
  return all_node_results
62
  def show_simulation_results(all_node_results, stateful_nodes):
 
68
  st.session_state.selected_columns = {node_id: {col: True for col in chart_data.columns}}
69
  elif node_id not in st.session_state.selected_columns:
70
  st.session_state.selected_columns[node_id] = {col: True for col in chart_data.columns}
71
+
 
 
 
 
 
 
 
 
 
72
  # Filter the data based on selected checkboxes
73
  filtered_data = chart_data[[col for col, selected in st.session_state.selected_columns[node_id].items() if selected]]
 
74
  # Display the line chart with filtered data
75
  st.line_chart(filtered_data, use_container_width=True, height=400)
76
+ columns = chart_data.columns
77
+ checks = st.columns(8)
78
+ if len(columns) > 0 and len(st.session_state.selected_columns[node_id])>1:
79
+ for l, column in enumerate(columns):
80
+ with checks[l]:
81
+ st.checkbox(
82
+ f"{column}",
83
+ value=st.session_state.selected_columns[node_id][column],
84
+ key=f"checkbox_{node_id}_{column}",
85
+ on_change=update_selected_columns,
86
+ args=(node_id, column,)
87
+ )
88
  else:
89
+ for col in chart_data.columns:
90
+ st.write(f"{col}: {chart_data[col][0]}")
91
 
92
  def update_selected_columns(node_id, column):
93
  st.session_state.selected_columns[node_id][column] = st.session_state[f"checkbox_{node_id}_{column}"]
 
98
  image_path = mdf_model.id + ".png"
99
  st.image(image_path, caption="Model Graph Visualization")
100
 
101
+ def show_json_model(mdf_model):
102
  st.subheader("JSON Model")
103
  st.json(mdf_model.to_json())
104
 
 
105
  def view_tabs(mdf_model, param_inputs, stateful): # view
106
  tab1, tab2, tab3 = st.tabs(["Simulation Results", "MDF Graph", "Json Model"])
107
  with tab1:
108
+ if 'simulation_run' not in st.session_state or not st.session_state.simulation_run:
109
+ st.write("Run the simulation to see results.")
110
+ elif st.session_state.simulation_results is not None:
111
+ show_simulation_results(st.session_state.simulation_results, stateful)
 
 
 
 
112
  else:
113
+ st.write("No simulation results available.")
 
 
 
 
 
 
 
114
  with tab2:
115
  show_mdf_graph(mdf_model) # view
116
  with tab3:
117
+ show_json_model(mdf_model) # view
118
 
119
  def display_and_edit_array(array, key):
120
  if isinstance(array, list):
121
  array = np.array(array)
 
122
  rows, cols = array.shape if array.ndim > 1 else (1, len(array))
123
+ if rows*cols > 10:
124
+ st.write(array)
125
+ st.write("Array Shape:", array.shape)
126
+ else:
127
+ edited_array = []
128
+ if rows == 1:
129
+ for j in range(cols):
130
+ value = array[j] if array.ndim > 1 else array[j]
131
+ edited_value = st.text_input(f"[{j}]", value=str(value), key=f"{key}_{j}")
132
+ try:
133
+ edited_array.append(float(edited_value))
134
+ except ValueError:
135
+ st.error(f"Invalid input for [{j}]. Please enter a valid number.")
136
+ else:
137
+ for i in range(rows):
138
+ row = []
139
+ for j in range(cols):
140
+ value = array[i][j] if array.ndim > 1 else array[i]
141
+ edited_value = st.text_input(f"[{i}][{j}]", value=str(value), key=f"{key}_{i}_{j}")
142
+ try:
143
+ row.append(float(edited_value))
144
+ except ValueError:
145
+ st.error(f"Invalid input for [{i}][{j}]. Please enter a valid number.")
146
+ edited_array.append(row)
147
+
148
+ return np.array(edited_array)
149
 
150
  def parameter_form_to_update_model_and_view(mdf_model):
151
  mod_graph = mdf_model.graphs[0]
 
184
 
185
  # Create four columns for each node
186
  col1, col2, col3, col4 = st.columns(4)
187
+ parameter_list = []
188
  for i, param in enumerate(node.parameters):
189
+ if isinstance(param.value, str) or param.value is None:
190
+ continue
191
+ else:
192
+ parameter_list.append(param)
193
+ for i, param in enumerate(parameter_list):
194
  if isinstance(param.value, str) or param.value is None:
195
  continue
196
  key = f"{param.id}_{node_index}_{i}"
 
236
  valid_inputs = False
237
 
238
  run_button = st.form_submit_button("Run Simulation")
239
+
240
  if run_button:
241
  if valid_inputs:
242
  for node in nodes:
 
244
  if param.id in param_inputs:
245
  param.value = param_inputs[param.id]
246
  st.session_state.simulation_results = run_simulation(param_inputs, mdf_model, stateful)
247
+ st.session_state.simulation_run = True
248
+ else:
249
+ st.error("Please correct the invalid inputs before running the simulation.")
250
+ view_tabs(mdf_model, param_inputs, stateful_nodes)
251
+
252
 
253
  def upload_file_and_load_to_model():
254
 
 
256
  github_url = st.sidebar.text_input("Enter GitHub raw file URL:", placeholder="Enter GitHub raw file URL")
257
  example_models = {
258
  "Newton Cooling Model": "./examples/NewtonCoolingModel.json",
259
+ "ABCD": "./examples/ABCD.json",
260
  "FN": "./examples/FN.mdf.json",
261
  "States": "./examples/States.json",
262
+ "Switched RLC Circuit": "./examples/switched_rlc_circuit.json",
263
  "Simple":"./examples/Simple.json",
264
+ "Arrays":"./examples/Arrays.json",
265
+ # "RNN":"./examples/RNNs.json", # some issue
266
  "IAF":"./examples/IAFs.json",
267
+ "Izhikevich Test":"./examples/IzhikevichTest.mdf.json",
268
+ "Keras to MDF IRIS":"./examples/keras_to_MDF.json",
269
  }
270
  selected_model = st.sidebar.selectbox("Choose an example model", list(example_models.keys()), index=None, placeholder="Dont have an MDF Model? Try some sample examples here!")
271
 
 
297
  json_data = json.loads(file_content)
298
  mdf_model = Model.from_dict(json_data)
299
  elif file_extension in ['yaml', 'yml']:
300
+ yaml_data = yaml.safe_load(file_content)
301
+ mdf_model = Model.from_dict(yaml_data)
302
+ elif file_extension == 'bson':
303
+ bson_data = bson.decode(file_content)
304
+ mdf_model = Model.from_dict(bson_data)
305
  else:
306
  st.error("Unsupported file format. Please use JSON or YAML files.")
307
  return None
 
322
  mdf_model = upload_file_and_load_to_model() # controller
323
 
324
  if mdf_model:
325
+ st.session_state.current_model = mdf_model
326
  header1, header2 = st.columns([1, 8], vertical_alignment="top")
327
  with header1:
328
  with st.container():
examples/keras_to_MDF.json ADDED
The diff for this file is too large to render. See raw diff
 
page_icon.png ADDED