rimjhimittal commited on
Commit
97cf187
β€’
1 Parent(s): 919b149

Create mvc

Browse files
Files changed (1) hide show
  1. pages/mvc +136 -0
pages/mvc ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+