-
Notifications
You must be signed in to change notification settings - Fork 2
/
pendulum_app.py
320 lines (279 loc) · 12 KB
/
pendulum_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import dash
from dash import html, dcc, no_update, Dash
from dash.dependencies import Input, Output, State, ClientsideFunction
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
from flask import Flask, redirect, request
import plotly.tools as tls
import plotly.graph_objs as go
import plotly.io as pio
import matplotlib.pyplot as plt
import sympy as sp
import os
from layouts.layout_main import get_main_layout
from layouts.layout_math import get_lagrangian_layout, get_hamiltonian_layout
from layouts.layout_chaos import get_chaos_layout
from layouts.layout_404 import get_404_layout
from layouts.layout_matplotlib import mpl_layout
from AppFunctions import validate_inputs, generate_pendulum_figures, set_display_styles
from DoublePendulumLagrangian import DoublePendulumLagrangian
from DoublePendulumHamiltonian import DoublePendulumHamiltonian
# Sympy variables for parameters
M1, M2, m1, m2, l1, l2, g = sp.symbols("M1, M2, m1, m2, l1, l2, g", positive=True, real=True)
server = Flask(__name__)
app = dash.Dash(
__name__,
suppress_callback_exceptions=True, # May not be warned about genuine mistakes like typos in component IDs
external_scripts=[
# ... (other scripts if any)
'https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.0/es5/tex-mml-chtml.js'
],
external_stylesheets=[
dbc.themes.BOOTSTRAP,
"https://fonts.googleapis.com/css2?family=Red+Hat+Display:ital,wght@0,300..900;1,300..900&display=swap"
],
server=server
)
# Comment out to launch locally (development)
@server.before_request
def before_request():
if not request.is_secure:
url = request.url.replace('http://', 'https://', 1)
return redirect(url, code=301)
# App set up
app.title = 'Double Pendulum Simulation - pineapple-bois'
app.index_string = open('assets/custom-header.html', 'r').read()
app.layout = html.Div([
dcc.Location(id='url', refresh=False), # Tracks the url
dcc.Store(id='update-state', data={'clear': False, 'update': False}),
html.Div(id='page-content', children=get_main_layout()), # Set initial content
dcc.Store(id='trigger-js') # Hidden div to trigger JS
])
# Navigate to page layout based on url
@app.callback(
Output('page-content', 'children'),
[Input('url', 'pathname')]
)
def display_page(pathname):
if pathname == '/chaos':
return get_chaos_layout()
elif pathname == '/lagrangian':
return get_lagrangian_layout()
elif pathname == '/hamiltonian':
return get_hamiltonian_layout()
else:
return get_main_layout() if pathname == '/' else get_404_layout()
# Client-side callback to run scroll.js when on the home page
app.clientside_callback(
"""
function(pathname) {
if (pathname === '/') {
initializeHomePage(); // Call the JS function to reinitialize
}
return '';
}
""",
Output('trigger-js', 'data'),
Input('url', 'pathname')
)
@app.callback(
[Output("info-popup", "style"),
Output("info-button", "children"),
Output("info-button", "n_clicks")],
[Input("info-button", "n_clicks"),
Input("close-info-button", "n_clicks")],
[State("info-popup", "style"),
State("info-button", "n_clicks")]
)
def toggle_info(info_n_clicks, close_n_clicks, current_style, current_info_n_clicks):
ctx = dash.callback_context
if not ctx.triggered:
button_id = 'No clicks yet'
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "info-button":
if info_n_clicks % 2 == 1:
return {"display": "block"}, "Close Information", info_n_clicks
else:
return {"display": "none"}, "What do I even choose?", info_n_clicks
elif button_id == "close-info-button":
return {"display": "none"}, "What do I even choose?", current_info_n_clicks + 1
return current_style, "What do I even choose?", info_n_clicks
# Callback for the unity parameters
@app.callback(
[Output('param_l1', 'value'),
Output('param_l2', 'value'),
Output('param_m1', 'value'),
Output('param_m2', 'value'),
Output('param_M1', 'value'),
Output('param_M2', 'value'),
Output('param_g', 'value')],
[Input('unity-parameters', 'n_clicks')],
)
def set_unity_parameters(n_clicks):
if n_clicks > 0:
# Return unity values for the parameters, except g which is set to 9.81
return 1, 1, 1, 1, 1, 1, 9.81
return dash.no_update # Prevents updating before button click
# Adjust parameters to model selection
@app.callback(
[Output('param_m1', 'style'),
Output('param_m2', 'style'),
Output('param_M1', 'style'),
Output('param_M2', 'style')],
[Input('model-type', 'value')]
)
def adjust_parameters_visibility(model_type):
if model_type == 'simple':
# Hide M1 and M2 for the simple model
return ({'display': 'block'}, {'display': 'block'},
{'display': 'none'}, {'display': 'none'})
elif model_type == 'compound':
# Show M1 and M2 for the compound model
return ({'display': 'none'}, {'display': 'none'},
{'display': 'block'}, {'display': 'block'})
@app.callback(
[
Output('time-graph', 'figure', allow_duplicate=True),
Output('phase-graph', 'figure', allow_duplicate=True),
Output('pendulum-animation', 'figure', allow_duplicate=True),
Output('animation-phase-container', 'style', allow_duplicate=True),
Output('time-graph-container', 'style', allow_duplicate=True),
Output('time-graph-section', 'style', allow_duplicate=True),
Output('error-message', 'children', allow_duplicate=True)
],
[
Input('init_cond_theta1', 'value'),
Input('init_cond_theta2', 'value'),
Input('init_cond_omega1', 'value'),
Input('init_cond_omega2', 'value'),
Input('time_start', 'value'),
Input('time_end', 'value'),
Input('param_l1', 'value'),
Input('param_l2', 'value'),
Input('param_m1', 'value'),
Input('param_m2', 'value'),
Input('param_M1', 'value'),
Input('param_M2', 'value'),
Input('param_g', 'value'),
Input('model-type', 'value'),
Input('system-type', 'value')
],
[State('error-message', 'children')],
prevent_initial_call=True
)
def clear_graphs_on_input_change(init_cond_theta1, init_cond_theta2, init_cond_omega1, init_cond_omega2,
time_start, time_end, param_l1, param_l2, param_m1, param_m2, param_M1,
param_M2, param_g, model_type, system_type, current_error_message):
# Step 1: Validate inputs
initial_conditions = [init_cond_theta1, init_cond_theta2, init_cond_omega1, init_cond_omega2]
new_error_message = validate_inputs([initial_conditions],
time_start, time_end, model_type, param_l1, param_l2, param_m1, param_m2,
param_M1, param_M2, param_g)
# If the error message hasn't changed, prevent updating to avoid flickering
if new_error_message == current_error_message:
raise PreventUpdate
# Step 2: If there's an error, return empty graphs and hide graph containers
if new_error_message:
empty_figure = go.Figure()
return (
empty_figure, empty_figure, empty_figure,
{'display': 'none'}, {'display': 'none'}, {'display': 'none'},
new_error_message
)
# Step 3: If no error, update graphs and show graph containers
# (Your logic to generate the figures goes here. For now, returning empty for example)
time_figure = go.Figure() # Replace with actual figure generation logic
phase_figure = go.Figure() # Replace with actual figure generation logic
animation_figure = go.Figure() # Replace with actual figure generation logic
return (
time_figure, phase_figure, animation_figure,
{'display': 'none'}, {'display': 'none'}, {'display': 'none'},
new_error_message # Should be an empty string or None if no error
)
# Callback to update the graphs - main page
@app.callback(
[Output('time-graph', 'figure'),
Output('phase-graph', 'figure'),
Output('pendulum-animation', 'figure'),
Output('animation-phase-container', 'style'),
Output('time-graph-container', 'style'),
Output('time-graph-section', 'style'),
Output('error-message', 'children')],
[Input('submit-val', 'n_clicks')],
[State('init_cond_theta1', 'value'),
State('init_cond_theta2', 'value'),
State('init_cond_omega1', 'value'),
State('init_cond_omega2', 'value'),
State('time_start', 'value'),
State('time_end', 'value'),
State('param_l1', 'value'),
State('param_l2', 'value'),
State('param_m1', 'value'),
State('param_m2', 'value'),
State('param_M1', 'value'),
State('param_M2', 'value'),
State('param_g', 'value'),
State('model-type', 'value'),
State('system-type', 'value')]
)
def update_graphs(n_clicks, init_cond_theta1, init_cond_theta2, init_cond_omega1, init_cond_omega2,
time_start, time_end,
param_l1, param_l2, param_m1, param_m2, param_M1, param_M2, param_g,
model_type, system_type):
if n_clicks > 0:
initial_conditions = [init_cond_theta1, init_cond_theta2, init_cond_omega1, init_cond_omega2]
# Validate inputs
error_message = validate_inputs([initial_conditions],
time_start, time_end, model_type, param_l1, param_l2, param_m1, param_m2,
param_M1, param_M2, param_g)
if error_message:
# If there are errors, return immediately
return (no_update, no_update, no_update,
{'display': 'none'}, {'display': 'none'}, {'display': 'none'}, error_message)
time_steps = int((time_end - time_start) * 200)
time_vector = [time_start, time_end, time_steps]
# Conditional parameter assignment based on model type
if model_type == 'simple':
weights = {m1: param_m1, m2: param_m2}
else:
weights = {M1: param_M1, M2: param_M2}
# Combine all parameters
parameters = {l1: param_l1, l2: param_l2, g: param_g, **weights}
# Create an instance of DoublePendulum
if system_type == 'lagrangian':
pendulum = DoublePendulumLagrangian(parameters, initial_conditions, time_vector, model=model_type)
else:
pendulum = DoublePendulumHamiltonian(parameters, initial_conditions, time_vector, model=model_type)
# Convert the Matplotlib graphs to Plotly graphs
matplotlib_time_fig = pendulum.time_graph()
# Set the layout to be responsive
time_fig = tls.mpl_to_plotly(matplotlib_time_fig)
time_fig.update_layout(
autosize=True,
margin=dict(l=20, r=20, t=20, b=20),
)
plt.close(matplotlib_time_fig)
matplotlib_phase_fig = pendulum.phase_path()
# Set the layout with a fixed aspect ratio for the phase-path graph
phase_fig = tls.mpl_to_plotly(matplotlib_phase_fig)
phase_fig.update_layout(
autosize=True,
margin=dict(l=20, r=20, t=20, b=20),
width=600,
height=600
)
plt.close(matplotlib_phase_fig)
# Apply the layout to graphs
time_fig.update_layout(mpl_layout)
phase_fig.update_layout(mpl_layout)
# Generate the animation figure
pendulum.precompute_positions() # Make sure positions are precomputed
animation_fig = pendulum.animate_pendulum(trace=True, fig_width=600, fig_height=600, static=True)
return (time_fig, phase_fig, animation_fig, # graph figures
{'display': 'flex'}, {'display': 'block'}, {'display': 'flex'}, '')
# If the button hasn't been clicked yet, return empty figures and keep everything hidden
return (go.Figure(), go.Figure(), go.Figure(),
{'display': 'none'}, {'display': 'none'}, {'display': 'none'}, '')
if __name__ == '__main__':
app.run_server(debug=False)