Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325import streamlit as stimport matplotlib.pyplot as pltfrom vector_physics import Vector2D, VectorPhysicsSimulator, plot_vectors, plot_trajectory, UnitConverter, QuizGenerator# Configure Streamlitst.set_page_config(page_title="Vector Physics Tutorial", layout="wide")# Initialize simulator and quiz generatorsimulator = VectorPhysicsSimulator()quiz_gen = QuizGenerator()converter = UnitConverter()# Initialize session stateif 'quiz_question' not in st.session_state:st.session_state.quiz_question = Noneif 'quiz_answer' not in st.session_state:st.session_state.quiz_answer = Noneif 'quiz_submitted' not in st.session_state:st.session_state.quiz_submitted = Falseif 'show_explanation' not in st.session_state:st.session_state.show_explanation = False# Title and introductionst.title("🚢 Vector Physics Interactive Tutorial")st.markdown("""Welcome to the Vector Physics Tutorial! Vectors are quantities that have both magnitude and direction.Use the controls below to explore different vector scenarios and see how they behave in real-time.""")# Sidebar for navigationst.sidebar.title("Select Physics Problem")problem_type = st.sidebar.selectbox("Choose a problem type:",["Boat Crossing", "Projectile Motion", "Vector Addition", "Quiz Mode"])# Unit selectionst.sidebar.markdown("---")st.sidebar.subheader("🔧 Unit Settings")speed_unit = st.sidebar.selectbox("Speed Units:", list(converter.speed_conversions().keys()))distance_unit = st.sidebar.selectbox("Distance Units:", list(converter.distance_conversions().keys()))# Reset buttonif st.sidebar.button("🔄 Reset to Defaults", help="Reset all controls to default values"):st.rerun()if problem_type == "Boat Crossing":st.header("🚢 Boat Crossing a River")st.markdown("""A boat is trying to cross a river with a current. The boat has its own velocity,and the river current affects the boat's actual path.""")col1, col2 = st.columns([1, 2])with col1:st.subheader("Controls")# Convert default values to selected unitsdefault_boat_speed = converter.convert_speed(5.0, "m/s", speed_unit)default_current_speed = converter.convert_speed(3.0, "m/s", speed_unit)boat_speed_input = st.slider(f"Boat Speed ({speed_unit})", 0.1,converter.convert_speed(10.0, "m/s", speed_unit),default_boat_speed, 0.1)boat_angle = st.slider("Boat Direction (degrees)", -90, 90, 45, 1)current_speed_input = st.slider(f"Current Speed ({speed_unit})", 0.0,converter.convert_speed(8.0, "m/s", speed_unit),default_current_speed, 0.1)current_angle = st.slider("Current Direction (degrees)", -180, 180, 180, 1)# Convert back to m/s for calculationsboat_speed = converter.convert_speed(boat_speed_input, speed_unit, "m/s")current_speed = converter.convert_speed(current_speed_input, speed_unit, "m/s")# Calculate resultsresults = simulator.boat_crossing_problem(boat_speed, boat_angle, current_speed, current_angle)st.subheader("Results")st.write(f"**Boat Velocity:** {converter.convert_speed(results['boat_velocity'].magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {results['boat_velocity'].angle:.1f}°")st.write(f"**Current Velocity:** {converter.convert_speed(results['current_velocity'].magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {results['current_velocity'].angle:.1f}°")st.write(f"**Resultant Velocity:** {converter.convert_speed(results['resultant_velocity'].magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {results['resultant_velocity'].angle:.1f}��")# Show heading differencest.markdown("---")st.subheader("📐 Navigation Analysis")st.write(f"**Heading Difference:** {results['heading_difference']:.1f}°")if results['heading_difference'] > 10:st.warning(f"⚠️ The boat's actual path deviates {results['heading_difference']:.1f}° from intended direction!")else:st.success("✅ The boat is following close to its intended path.")with col2:# Create plotsfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))# Vector diagramvectors = [results['boat_velocity'], results['current_velocity'], results['resultant_velocity']]labels = ['Boat Velocity (intended)', 'Current Velocity', 'Resultant Velocity (actual)']colors = ['blue', 'red', 'green']plot_vectors(ax1, vectors, labels, colors)ax1.set_title("Vector Diagram")# Trajectory plottraj_x_converted = [converter.convert_distance(x, "meters", distance_unit) for x in results['trajectory_x'][:50]]traj_y_converted = [converter.convert_distance(y, "meters", distance_unit) for y in results['trajectory_y'][:50]]plot_trajectory(ax2, traj_x_converted, traj_y_converted, f"Boat Path ({distance_unit})")ax2.set_xlabel(f'X Position ({distance_unit})')ax2.set_ylabel(f'Y Position ({distance_unit})')st.pyplot(fig)elif problem_type == "Projectile Motion":st.header("🎯 Projectile Motion")st.markdown("""A projectile is launched at an angle. Gravity acts downward while the horizontalcomponent of velocity remains constant. **Error analysis** shows how measurementuncertainty affects the results.""")col1, col2 = st.columns([1, 2])with col1:st.subheader("Controls")default_speed = converter.convert_speed(20.0, "m/s", speed_unit)initial_speed_input = st.slider(f"Initial Speed ({speed_unit})", 1.0,converter.convert_speed(50.0, "m/s", speed_unit),default_speed, 1.0)launch_angle = st.slider("Launch Angle (degrees)", 0, 90, 45, 1)gravity = st.slider("Gravity (m/s²)", 1.0, 15.0, 9.81, 0.1)show_error = st.checkbox("Show Error Analysis", value=True, help="Shows uncertainty range from measurement errors")# Convert to m/s for calculationsinitial_speed = converter.convert_speed(initial_speed_input, speed_unit, "m/s")# Calculate resultsresults = simulator.projectile_motion(initial_speed, launch_angle, gravity)st.subheader("Results")st.write(f"**Initial Velocity:** {converter.convert_speed(results['initial_velocity'].magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {results['initial_velocity'].angle:.1f}°")st.write(f"**Max Range:** {converter.convert_distance(results['max_range'], 'meters', distance_unit):.2f} {distance_unit}")st.write(f"**Max Height:** {converter.convert_distance(results['max_height'], 'meters', distance_unit):.2f} {distance_unit}")st.write(f"**Flight Time:** {results['time_points'][-1]:.2f} s")if show_error:st.markdown("---")st.subheader("📊 Uncertainty Analysis")st.write(f"**Speed Uncertainty:** ±{converter.convert_speed(results['speed_uncertainty'], 'm/s', speed_unit):.2f} {speed_unit}")st.write(f"**Angle Uncertainty:** ±{results['angle_uncertainty']:.1f}°")st.info("💡 Small measurement errors can lead to significant differences in trajectory!")with col2:# Create plotsfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))# Vector diagraminitial_vel = results['initial_velocity']velocity_x = Vector2D(initial_vel.x, 0)velocity_y = Vector2D(0, initial_vel.y)vectors = [velocity_x, velocity_y, initial_vel]labels = ['Horizontal Component', 'Vertical Component', 'Initial Velocity']colors = ['blue', 'red', 'green']plot_vectors(ax1, vectors, labels, colors)ax1.set_title("Velocity Components")# Trajectory plot with error analysistraj_x = [converter.convert_distance(x, "meters", distance_unit) for x in results['trajectory_x']]traj_y = [converter.convert_distance(y, "meters", distance_unit) for y in results['trajectory_y']]error_bounds = Noneif show_error:error_bounds = {'upper_x': [converter.convert_distance(x, "meters", distance_unit) for x in results['error_upper_x']],'upper_y': [converter.convert_distance(y, "meters", distance_unit) for y in results['error_upper_y']],'lower_x': [converter.convert_distance(x, "meters", distance_unit) for x in results['error_lower_x']],'lower_y': [converter.convert_distance(y, "meters", distance_unit) for y in results['error_lower_y']]}plot_trajectory(ax2, traj_x, traj_y, f"Projectile Path ({distance_unit})", error_bounds)ax2.set_xlabel(f'X Position ({distance_unit})')ax2.set_ylabel(f'Y Position ({distance_unit})')st.pyplot(fig)elif problem_type == "Vector Addition":st.header("➕ Vector Addition Practice")st.markdown("""Practice adding vectors by adjusting their magnitudes and directions.See how different combinations create different resultant vectors.""")col1, col2 = st.columns([1, 2])with col1:st.subheader("Vector A")default_mag_a = converter.convert_speed(5.0, "m/s", speed_unit)mag_a_input = st.slider(f"Magnitude A ({speed_unit})", 0.1,converter.convert_speed(10.0, "m/s", speed_unit),default_mag_a, 0.1, key="mag_a")angle_a = st.slider("Angle A (degrees)", -180, 180, 30, 1, key="angle_a")st.subheader("Vector B")default_mag_b = converter.convert_speed(3.0, "m/s", speed_unit)mag_b_input = st.slider(f"Magnitude B ({speed_unit})", 0.1,converter.convert_speed(10.0, "m/s", speed_unit),default_mag_b, 0.1, key="mag_b")angle_b = st.slider("Angle B (degrees)", -180, 180, 120, 1, key="angle_b")# Convert to m/s for calculationsmag_a = converter.convert_speed(mag_a_input, speed_unit, "m/s")mag_b = converter.convert_speed(mag_b_input, speed_unit, "m/s")# Create vectorsvector_a = Vector2D(magnitude=mag_a, angle=angle_a)vector_b = Vector2D(magnitude=mag_b, angle=angle_b)resultant = vector_a + vector_bst.subheader("Results")st.write(f"**Vector A:** {converter.convert_speed(vector_a.magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {vector_a.angle:.1f}°")st.write(f"**Vector B:** {converter.convert_speed(vector_b.magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {vector_b.angle:.1f}°")st.write(f"**Resultant:** {converter.convert_speed(resultant.magnitude, 'm/s', speed_unit):.2f} {speed_unit} at {resultant.angle:.1f}°")st.write(f"**Dot Product A·B:** {vector_a.dot_product(vector_b):.2f}")st.write(f"**Angle Between Vectors:** {vector_a.angle_between(vector_b):.1f}°")with col2:fig, ax = plt.subplots(figsize=(8, 8))vectors = [vector_a, vector_b, resultant]labels = ['Vector A', 'Vector B', 'Resultant A+B']colors = ['blue', 'red', 'green']plot_vectors(ax, vectors, labels, colors)ax.set_title("Vector Addition")st.pyplot(fig)elif problem_type == "Quiz Mode":st.header("🎓 Vector Physics Quiz")st.markdown("""Test your understanding of vector concepts! Click 'New Question' to get a random problem.""")col1, col2, col3 = st.columns([1, 1, 1])with col1:if st.button("📝 New Question", type="primary"):st.session_state.quiz_question = quiz_gen.generate_question()st.session_state.quiz_answer = Nonest.session_state.quiz_submitted = Falsest.session_state.show_explanation = Falsewith col2:if st.button("💡 Show Explanation") and st.session_state.quiz_question:st.session_state.show_explanation = Truewith col3:if st.button("🔄 Reset Quiz"):st.session_state.quiz_question = Nonest.session_state.quiz_answer = Nonest.session_state.quiz_submitted = Falsest.session_state.show_explanation = Falseif st.session_state.quiz_question:question = st.session_state.quiz_questionst.markdown("---")st.subheader("Question:")st.write(question["question"])# Answer inputuser_answer = st.number_input("Your answer:", value=0.0, format="%.2f", key="quiz_input")if st.button("Submit Answer"):st.session_state.quiz_answer = user_answerst.session_state.quiz_submitted = True# Check answerif st.session_state.quiz_submitted and st.session_state.quiz_answer is not None:correct_answer = question["answer"]tolerance = question["tolerance"]if abs(st.session_state.quiz_answer - correct_answer) <= tolerance:st.success(f"✅ Correct! The answer is {correct_answer:.2f}")st.balloons()else:st.error(f"❌ Not quite right. The correct answer is {correct_answer:.2f}")st.write(f"Your answer: {st.session_state.quiz_answer:.2f}")# Show explanationif st.session_state.show_explanation:st.markdown("---")st.subheader("💡 Explanation:")st.write(question["explanation"])else:st.info("Click 'New Question' to start the quiz!")# Educational notesst.sidebar.markdown("---")st.sidebar.markdown("### 📚 Key Concepts")st.sidebar.markdown("""- **Magnitude**: Length of the vector- **Direction**: Angle the vector makes- **Components**: x and y parts of vector- **Addition**: Tip-to-tail method- **Resultant**: Sum of multiple vectors""")st.sidebar.markdown("### 💡 Try This")st.sidebar.markdown("""1. Set boat angle to 90° to go straight across2. Increase current speed and watch the path change3. Try launch angles of 45° for maximum range4. Make two vectors perpendicular (90° apart)5. Test the quiz mode to check your understanding6. Change units to see the same physics in different measurements""")st.sidebar.markdown("### ⚙️ Features")st.sidebar.markdown("""- **Unit Conversion**: Change between m/s, km/h, mph, etc.- **Error Analysis**: See how measurement uncertainty affects results- **Quiz Mode**: Test your vector knowledge- **Reset Button**: Restore default values""")
src/streamlit_app.py+323-38