|
| 1 | +import matplotlib.pyplot as plt |
| 2 | +import numpy as np |
| 3 | +import streamlit as st |
| 4 | +import time |
| 5 | + |
| 6 | + |
| 7 | +max_x = 50 |
| 8 | +scale = 5 |
| 9 | + |
| 10 | +x = np.arange(0, max_x) |
| 11 | + |
| 12 | +# from WormView import get_plot |
| 13 | +# from WormView import parse_args |
| 14 | + |
| 15 | +# args = parse_args() |
| 16 | + |
| 17 | +print("Loading...") |
| 18 | + |
| 19 | + |
| 20 | +def get_y(t): |
| 21 | + """Get the y values for the plot based on time t.""" |
| 22 | + return scale * np.sin( |
| 23 | + 2 * np.pi * (x / 50 + t / 5) |
| 24 | + ) # Example function, can be modified |
| 25 | + |
| 26 | + |
| 27 | +def init(): # give a clean slate to start |
| 28 | + print("Initializing the plot...") |
| 29 | + fig, ax = plt.subplots() |
| 30 | + ax.set_ylim(-1.1 * scale, scale * 1.1) |
| 31 | + ax.set_xlim(-1, max_x + 1) |
| 32 | + |
| 33 | + (st.session_state.line,) = ax.plot(x, get_y(0), color="red") |
| 34 | + st.session_state.the_plot = st.pyplot(plt) |
| 35 | + |
| 36 | + |
| 37 | +def animate(t): # update the y values (every 1000ms) |
| 38 | + print("Animating the plot for time:", t) |
| 39 | + plt.close() |
| 40 | + fig, ax = plt.subplots() |
| 41 | + ax.set_ylim(-1.1 * scale, scale * 1.1) |
| 42 | + ax.set_xlim(-1, max_x + 1) |
| 43 | + (st.session_state.line,) = ax.plot(x, get_y(t), color="green", label=f"t={t:.2f}") |
| 44 | + plt.legend() |
| 45 | + # st.session_state.line.set_ydata(get_y(t)) |
| 46 | + st.session_state.the_plot.pyplot(plt) |
| 47 | + |
| 48 | + |
| 49 | +if "t" not in st.session_state: |
| 50 | + print("Initializing...") |
| 51 | + init() |
| 52 | + st.session_state.t = 0 |
| 53 | + animate(0) # initial animation to set the plot |
| 54 | + |
| 55 | + |
| 56 | +if st.button("Step"): |
| 57 | + print("Stepping...") |
| 58 | + st.session_state.t += 0.1 |
| 59 | + animate(st.session_state.t) |
| 60 | + |
| 61 | +if st.button("Stop"): |
| 62 | + print("Stopping...") |
| 63 | + st.session_state.t += 0.1 |
| 64 | + animate(st.session_state.t) |
| 65 | + |
| 66 | +play = False |
| 67 | + |
| 68 | +if st.button("Play"): |
| 69 | + play = True |
| 70 | + print("Playing...") |
| 71 | + for i in range(50): |
| 72 | + if not play: |
| 73 | + break |
| 74 | + animate(st.session_state.t) |
| 75 | + st.session_state.t += 0.1 |
| 76 | + time.sleep(0.1) |
| 77 | + |
| 78 | + |
| 79 | +st.markdown(f"Time {st.session_state.t}.") |
0 commit comments