Rimjhim Mittal commited on
Commit
4eb270e
β€’
1 Parent(s): c4726a7

tried adding yaml component, a lot needs to be fixed

Browse files
app.py CHANGED
@@ -1,30 +1,173 @@
1
  import streamlit as st
 
 
 
 
 
 
2
 
3
  st.set_page_config(layout="wide")
 
4
 
5
- def main():
6
- st.markdown("## Introduction to Model Description Format (MDF)")
7
- st.markdown("""
8
- The Model Description Format (MDF) is a standardized format used to represent computational models. MDF aims to facilitate the exchange and reuse of models across different simulation platforms. It provides a structured way to describe the components and behaviors of models in a machine-readable format.
 
 
 
 
 
 
 
 
 
 
9
 
10
- ### Key Components of MDF:
11
-
12
- - **Model**: The top-level container that holds all the information about the model.
13
- - **Graphs**: A model can contain one or more graphs, which represent different parts of the model or different modeling scenarios.
14
- - **Nodes**: Each graph contains nodes, which are the fundamental units of the model representing entities or processes.
15
- - **Parameters**: Nodes have parameters that define their properties and behaviors.
16
- - **OutputPorts**: Nodes can have output ports, which specify the outputs of the nodes that can be connected to inputs of other nodes.
17
- - **Edges**: Edges define the connections between nodes, representing the flow of information or material.
18
-
19
- ### Benefits of Using MDF:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- - **Standardization**: Ensures consistency and compatibility across different tools and platforms.
22
- - **Interoperability**: Facilitates the integration of models from different sources.
23
- - **Reusability**: Encourages the reuse of models and model components.
24
- - **Transparency**: Provides a clear and comprehensive description of models, aiding in understanding and validation.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- MDF is designed to be extensible and flexible, allowing for the inclusion of additional metadata and custom components as needed. By using MDF, researchers and engineers can create, share, and collaborate on models more effectively.
27
- """)
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  if __name__ == "__main__":
30
  main()
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ import os
4
+ from modeci_mdf.mdf import Model, Graph, Node, Parameter, OutputPort
5
+ from modeci_mdf.utils import load_mdf_json, load_mdf, load_mdf_yaml
6
+ from modeci_mdf.execution_engine import EvaluableGraph
7
+ from code_editor import code_editor
8
 
9
  st.set_page_config(layout="wide")
10
+ st.title("πŸ”‹ MDF Simulator")
11
 
12
+ height = [19, 22]
13
+ theme = "default"
14
+ shortcuts = "vscode"
15
+ focus = False
16
+ wrap = True
17
+ editor_btns = [{
18
+ "name": "Run",
19
+ "feather": "Play",
20
+ "primary": True,
21
+ "hasText": True,
22
+ "showWithIcon": True,
23
+ "commands": ["submit"],
24
+ "style": {"bottom": "0.44rem", "right": "0.4rem"}
25
+ }]
26
 
27
+ def mdf_model_to_paramters_dictionary(param_inputs, mdf_model):
28
+ mod_graph = mdf_model.graphs[0]
29
+ nodes = mod_graph.nodes[0]
30
+ parameters = nodes.parameters
31
+ for param in parameters:
32
+ if isinstance(param.value, str) or param.value is None:
33
+ continue
34
+ st.session_state.param_inputs[param.id] = param.value
35
+ return st.session_state.param_inputs
36
+
37
+ def run_simulation(param_inputs, mdf_model):
38
+ mod_graph = mdf_model.graphs[0]
39
+ nodes = mod_graph.nodes[0]
40
+ parameters = nodes.parameters
41
+ outputs = nodes.output_ports
42
+ eg = EvaluableGraph(mod_graph, verbose=False)
43
+ duration = param_inputs["Simulation Duration (s)"]
44
+ dt = param_inputs["Time Step (s)"]
45
+ t = 0
46
+ times = []
47
+ output_values = {op.value: [] for op in outputs}
48
+ while t <= duration:
49
+ times.append(t)
50
+ if t == 0:
51
+ eg.evaluate()
52
+ else:
53
+ eg.evaluate(time_increment=dt)
54
+
55
+ for param in output_values:
56
+ eval_param = eg.enodes[nodes.id].evaluable_parameters[param]
57
+ output_values[param].append(eval_param.curr_value)
58
+ t += dt
59
+ chart_data = pd.DataFrame(output_values)
60
+ chart_data['Time'] = times
61
+ chart_data.set_index('Time', inplace=True)
62
+ return chart_data
63
+
64
+ def show_simulation_results():
65
+ if 'chart_data' in st.session_state:
66
+ st.line_chart(st.session_state.chart_data, use_container_width=True, height=400)
67
+ st.write("Input Values")
68
+ st.write(st.session_state.param_inputs)
69
+ st.write("Output Values")
70
+ st.write(st.session_state.chart_data)
71
+
72
+ def show_mdf_graph():
73
+ if 'mdf_model_graph' in st.session_state:
74
+ st.subheader("MDF Graph")
75
+ image_path = st.session_state.mdf_model.id + ".png"
76
+ st.image(image_path, caption="Model Graph Visualization")
77
+
78
+ def show_json_output():
79
+ if 'mdf_model_json' in st.session_state:
80
+ st.subheader("JSON Output")
81
+ st.json(st.session_state.mdf_model_json)
82
+
83
+ def update_view_tabs(mdf_model, param_inputs):
84
+ tab1, tab2, tab3, tab4 = st.tabs(["Simulation Results", "MDF Graph", "Json Output", "Yaml Output"])
85
+ with tab1:
86
+ show_simulation_results()
87
+ with tab2:
88
+ show_mdf_graph()
89
+ with tab3:
90
+ show_json_output()
91
+ with tab4:
92
+ changes_in_yaml_to_update_model()
93
+
94
+ def parameter_form_to_update_model_and_view(mdf_model, param_inputs):
95
+ mod_graph = mdf_model.graphs[0]
96
+ nodes = mod_graph.nodes[0]
97
+ parameters = nodes.parameters
98
+ form = st.form(key="parameter_form")
99
+ for i, param in enumerate(parameters):
100
+ if isinstance(param.value, str) or param.value is None:
101
+ continue
102
+ key = f"{param.id}_{i}"
103
+ if mdf_model.metadata:
104
+ param_inputs[param.id] = float(form.text_input(f"{param.metadata.get('description', param.id)} ({param.id})", value=param.value, key=key))
105
+ else:
106
+ param_inputs[param.id] = float(form.text_input(f"{param.id}", value=param.value, key=key))
107
+ param_inputs["Simulation Duration (s)"] = float(form.text_input("Simulation Duration (s)", value=st.session_state.param_inputs.get("Simulation Duration (s)", 10), key="sim_duration"))
108
+ param_inputs["Time Step (s)"] = float(form.text_input("Time Step (s)", value=st.session_state.param_inputs.get("Time Step (s)", 0.1), key="time_step"))
109
 
110
+ run_button = form.form_submit_button("Run Simulation")
111
+ if run_button:
112
+ st.session_state.run_button_clicked = True
113
+ for i in param_inputs:
114
+ st.session_state.param_inputs[i] = float(param_inputs[i])
115
+ st.session_state.chart_data = run_simulation(param_inputs, mdf_model)
116
+ st.session_state.mdf_model_graph = mdf_model.to_graph_image(engine="dot", output_format="png", view_on_render=False, level=3, filename_root=mdf_model.id, only_warn_on_fail=(os.name == "nt"))
117
+ st.session_state.mdf_model_json = mdf_model.to_json()
118
+ st.session_state.update_button_clicked = False
119
+
120
+ def upload_file_and_load_to_model():
121
+ uploaded_file = st.file_uploader("Choose a JSON/YAML/BSON file", type=["json", "yaml", "bson"])
122
+ if uploaded_file is not None:
123
+ filename = uploaded_file.name
124
+ with open(filename, "wb") as f:
125
+ f.write(uploaded_file.getbuffer())
126
+ mdf_model = load_mdf(filename)
127
+ st.session_state.original_mdf_model = mdf_model # Save the original model
128
+ st.session_state.mdf_model_yaml = mdf_model # Save the current model state
129
+ return mdf_model
130
 
 
 
131
 
132
+ def changes_in_yaml_to_update_model():
133
+ response = code_editor(st.session_state.mdf_model_yaml.to_yaml(), height=height, lang="yaml", theme=theme, shortcuts=shortcuts, focus=focus, buttons=editor_btns, options={"wrap": wrap})
134
+ st.write("First, make changes in the YAML code above, press Ctrl + Enter (or Run button inside code editor) and then click on the 'Update Model' button below to update the model. Sometimes you have to follow these steps twice.")
135
+ if len(response['id']) != 0 and (response['type'] == "selection" or response['type'] == "submit"):
136
+ code_text = response['text']
137
+ update_button = st.button("Update Model")
138
+ if update_button:
139
+ mdf_model = Model.from_yaml(code_text)
140
+ mdf_model_to_paramters_dictionary(st.session_state.param_inputs, mdf_model)
141
+ st.session_state.mdf_model_yaml = mdf_model
142
+ st.session_state.chart_data = run_simulation(st.session_state.param_inputs, mdf_model)
143
+ st.session_state.mdf_model_graph = mdf_model.to_graph_image(engine="dot", output_format="png", view_on_render=False, level=3, filename_root=mdf_model.id, only_warn_on_fail=(os.name == "nt"))
144
+ st.session_state.mdf_model_json = mdf_model.to_json()
145
+ st.session_state.update_button_clicked = True
146
+
147
+
148
+
149
+
150
+ def main():
151
+ mdf_model = upload_file_and_load_to_model()
152
+ st.write("Latest changes here: Working on making YAML editor.")
153
+ if mdf_model:
154
+ st.session_state.mdf_model = mdf_model
155
+ if 'run_button_clicked' not in st.session_state:
156
+ st.session_state.run_button_clicked = False
157
+ if 'update_button_clicked' not in st.session_state:
158
+ st.session_state.update_button_clicked = False
159
+ param_inputs = {}
160
+ if mdf_model.metadata:
161
+ preferred_duration = float(mdf_model.metadata.get("preferred_duration", 10))
162
+ preferred_dt = float(mdf_model.metadata.get("preferred_dt", 0.1))
163
+ else:
164
+ preferred_duration = 100
165
+ preferred_dt = 0.1
166
+ param_inputs["Simulation Duration (s)"] = preferred_duration
167
+ param_inputs["Time Step (s)"] = preferred_dt
168
+ st.session_state.param_inputs = param_inputs
169
+ parameter_form_to_update_model_and_view(st.session_state.mdf_model, st.session_state.param_inputs)
170
+ update_view_tabs(mdf_model, param_inputs)
171
+
172
  if __name__ == "__main__":
173
  main()
other_files/app.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 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
5
+ st.set_page_config(layout="wide")
6
+ st.title("πŸ”‹ MDF Simulator")
7
+
8
+ # models: Purpose: To store the state of the model and update the model
9
+ def run_simulation(param_inputs, mdf_model):
10
+ mod_graph = mdf_model.graphs[0]
11
+ nodes = mod_graph.nodes[0]
12
+ parameters = nodes.parameters
13
+ outputs = nodes.output_ports
14
+ eg = EvaluableGraph(mod_graph, verbose=False)
15
+ duration = param_inputs["Simulation Duration (s)"]
16
+ dt = param_inputs["Time Step (s)"]
17
+ t = 0
18
+ times = []
19
+ output_values = {op.value: [] for op in outputs}
20
+ while t <= duration:
21
+ times.append(t)
22
+ if t == 0:
23
+ eg.evaluate()
24
+ else:
25
+ eg.evaluate(time_increment=dt)
26
+
27
+ for param in output_values:
28
+ eval_param = eg.enodes[nodes.id].evaluable_parameters[param]
29
+ output_values[param].append(eval_param.curr_value)
30
+ t += dt
31
+ chart_data = pd.DataFrame(output_values)
32
+ chart_data['Time'] = times
33
+ chart_data.set_index('Time', inplace=True)
34
+ return chart_data
35
+
36
+ # views: Purpose: To display the state of the model and update the view
37
+ def show_simulation_results(chart_data):
38
+ st.line_chart(chart_data, use_container_width=True, height=400)
39
+ st.write("Output Values")
40
+ st.write(chart_data)
41
+
42
+ def show_mdf_graph(mdf_model):
43
+ st.subheader("MDF Graph")
44
+ mdf_model.to_graph_image(engine="dot", output_format="png", view_on_render=False, level=3, filename_root=mdf_model.id, only_warn_on_fail=(os.name == "nt"))
45
+ image_path = mdf_model.id + ".png"
46
+ st.image(image_path, caption="Model Graph Visualization")
47
+
48
+ def show_json_output(mdf_model):
49
+ st.subheader("JSON Output")
50
+ st.json(mdf_model.to_json())
51
+
52
+ def view_tabs(mdf_model, param_inputs): # view
53
+ tab1, tab2, tab3, tab4 = st.tabs(["Simulation Results", "MDF Graph", "Json Output", "Yaml Output"])
54
+ with tab1:
55
+ chart_data = run_simulation(param_inputs, mdf_model) # model
56
+ show_simulation_results(chart_data) # view
57
+ with tab2:
58
+ show_mdf_graph(mdf_model) # view
59
+ with tab3:
60
+ show_json_output(mdf_model) # view
61
+ with tab4:
62
+ update_model_button = st.button("Update Model", key="updateModelButton")
63
+ if update_model_button:
64
+ changes_in_modelcode_to_update_model(mdf_model, param_inputs)
65
+
66
+ def parameter_form_to_update_model_and_view(mdf_model, parameters, param_inputs, mod_graph, nodes):
67
+ form = st.form(key="parameter_form")
68
+ for i, param in enumerate(parameters):
69
+ if isinstance(param.value, str) or param.value is None:
70
+ continue
71
+ key = f"{param.id}_{i}"
72
+ if mdf_model.metadata:
73
+ param_inputs[param.id] = float(form.text_input(f"{param.metadata.get('description', param.id)} ({param.id})", value=param.value, key=key))
74
+ else:
75
+ param_inputs[param.id] = float(form.text_input(f"{param.id}", value=param.value, key=key))
76
+ param_inputs["Simulation Duration (s)"] = float(form.text_input("Simulation Duration (s)", value=param_inputs["Simulation Duration (s)"], key="sim_duration"))
77
+ param_inputs["Time Step (s)"] = float(form.text_input("Time Step (s)", value=param_inputs["Time Step (s)"], key="time_step"))
78
+ for param in parameters:
79
+ if param.id in param_inputs:
80
+ param.value = param_inputs[param.id]
81
+ form.form_submit_button(on_click=view_tabs(mdf_model, param_inputs))
82
+
83
+ def upload_file_and_load_to_model():
84
+ uploaded_file = st.file_uploader("Choose a JSON/YAML/BSON file", type=["json", "yaml", "bson"])
85
+ if uploaded_file is not None:
86
+ filename = uploaded_file.name
87
+ with open(filename, "wb") as f:
88
+ f.write(uploaded_file.getbuffer())
89
+ mdf_model = load_mdf(filename)
90
+ st.session_state.original_mdf_model = mdf_model # Save the original model
91
+ st.session_state.mdf_model_yaml = mdf_model # Save the current model state
92
+ return mdf_model
93
+
94
+ def changes_in_modelcode_to_update_model(mdf_model, param_inputs):
95
+ update_model_button = st.button("Update Model") # this is working
96
+ if update_model_button:
97
+ print("Failed to update model:")
98
+ st.balloons()
99
+ st.toast("Failed to update model", "Failed to update model", "error")
100
+ st.text_area("Update the model parameters", height=700, value=st.session_state.mdf_model)
101
+ new_mdf_model_text = st.text_area("Update the model parameters", height=700, value=st.session_state.mdf_model)
102
+ if st.button("Reset Code"):
103
+ st.session_state.mdf_model = st.session_state.original_mdf_model
104
+ mdf_model = load_mdf_json(io.BytesIO(st.session_state.original_mdf_model.encode('utf-8'))) # Load from stored JSON string
105
+ view_tabs(mdf_model, param_inputs)
106
+
107
+ try:
108
+ st.session_state.mdf_model = new_mdf_model_text
109
+ mdf_model = load_mdf_json(io.BytesIO(new_mdf_model_text.encode('utf-8'))) # Attempt to load updated model from JSON string
110
+ view_tabs(mdf_model, param_inputs)
111
+ except Exception as e:
112
+ print(f"Failed to update model: {e}") #yahan tak pohoch hi nahi raha hai
113
+
114
+ def main():
115
+ mdf_model = upload_file_and_load_to_model() # controller
116
+
117
+ if mdf_model:
118
+ mod_graph = mdf_model.graphs[0]
119
+ nodes = mod_graph.nodes[0]
120
+ parameters = nodes.parameters
121
+ param_inputs = {}
122
+ if mdf_model.metadata:
123
+ preferred_duration = float(mdf_model.metadata.get("preferred_duration", 10))
124
+ preferred_dt = float(mdf_model.metadata.get("preferred_dt", 0.1))
125
+ else:
126
+ preferred_duration = 100
127
+ preferred_dt = 0.1
128
+ param_inputs["Simulation Duration (s)"] = preferred_duration
129
+ param_inputs["Time Step (s)"] = preferred_dt
130
+ parameter_form_to_update_model_and_view(mdf_model, parameters, param_inputs, mod_graph, nodes)
131
+
132
+ if __name__ == "__main__":
133
+ main()
134
+
135
+
136
+
137
+
138
+ # def changes_in_yaml_to_update_model(mdf_model, param_inputs ):
139
+ # if 'original_mdf_model' not in st.session_state:
140
+ # st.session_state.original_mdf_model = mdf_model.to_yaml()
141
+ # if 'mdf_model_yaml' not in st.session_state:
142
+ # st.session_state.mdf_model_yaml = mdf_model.to_yaml()
143
+
144
+ # new_mdf_model_yaml = st.text_area("Update the model parameters", height=700, value=st.session_state.mdf_model_yaml)
145
+
146
+ # if st.button("Reset Code"):
147
+ # st.session_state.mdf_model_yaml = st.session_state.original_mdf_model
148
+ # mdf_model = load_mdf_yaml(io.BytesIO(st.session_state.original_mdf_model.encode('utf-8')))
149
+ # view_tabs(mdf_model, param_inputs)
150
+
151
+ # if st.button("Update Model"):
152
+ # st.session_state.mdf_model_yaml = new_mdf_model_yaml
153
+ # mdf_model = load_mdf_yaml(io.BytesIO(new_mdf_model_yaml.encode('utf-8')))
154
+ # view_tabs(mdf_model, param_inputs)
other_files/extra_fiel.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Download the files to be uploaded from here:
2
+ files=["switched_rlc_circuit.json", "NewtonCoolingModel.json"]
3
+ for filename in files:
4
+ with open(filename, 'rb') as f:
5
+ file_data = f.read()
6
+ b64 = base64.b64encode(file_data).decode()
7
+
8
+ # Generate the download link
9
+ href = f'<a href="data:application/json;base64,{b64}" download="{filename}">Download the {filename} JSON file from here</a>'
10
+
11
+ # Use st.markdown to display the link
12
+ st.markdown(href, unsafe_allow_html=True)
{pages β†’ other_files}/❄️_HardCoded_Newton_Cooling_Law.py RENAMED
File without changes
{pages β†’ other_files}/πŸ“‰_HardCoded_RLC_Circuit.py RENAMED
File without changes
{pages β†’ other_files}/πŸ€–_ModelViewController.py RENAMED
@@ -129,7 +129,6 @@ def main():
129
  st.header(f"Model: {model_name}")
130
  controller.view.display_parameters(controller.model.parameters, controller.model.mdf_model.metadata or {})
131
  run_simulation_button = st.button("Run Simulation")
132
- # time.sleep(10)
133
  if run_simulation_button:
134
  controller.update_model_parameters()
135
  controller.run_simulation()
 
129
  st.header(f"Model: {model_name}")
130
  controller.view.display_parameters(controller.model.parameters, controller.model.mdf_model.metadata or {})
131
  run_simulation_button = st.button("Run Simulation")
 
132
  if run_simulation_button:
133
  controller.update_model_parameters()
134
  controller.run_simulation()
pages/{πŸš€_MDF_Simulator.py β†’ old_MDF_Simulator.py} RENAMED
File without changes