Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import matplotlib.pyplot as plt | |
| from vector_physics import Vector2D, VectorPhysicsSimulator, plot_vectors, plot_trajectory, UnitConverter, QuizGenerator | |
| # Configure Streamlit | |
| st.set_page_config(page_title="Vector Physics Tutorial", layout="wide") | |
| # Initialize simulator and quiz generator | |
| simulator = VectorPhysicsSimulator() | |
| quiz_gen = QuizGenerator() | |
| converter = UnitConverter() | |
| # Initialize session state | |
| if 'quiz_question' not in st.session_state: | |
| st.session_state.quiz_question = None | |
| if 'quiz_answer' not in st.session_state: | |
| st.session_state.quiz_answer = None | |
| if 'quiz_submitted' not in st.session_state: | |
| st.session_state.quiz_submitted = False | |
| if 'show_explanation' not in st.session_state: | |
| st.session_state.show_explanation = False | |
| # Title and introduction | |
| st.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 navigation | |
| st.sidebar.title("Select Physics Problem") | |
| problem_type = st.sidebar.selectbox( | |
| "Choose a problem type:", | |
| ["Boat Crossing", "Projectile Motion", "Vector Addition", "Quiz Mode"] | |
| ) | |
| # Unit selection | |
| st.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 button | |
| if 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 units | |
| default_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 calculations | |
| boat_speed = converter.convert_speed(boat_speed_input, speed_unit, "m/s") | |
| current_speed = converter.convert_speed(current_speed_input, speed_unit, "m/s") | |
| # Calculate results | |
| results = 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 difference | |
| st.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 plots | |
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) | |
| # Vector diagram | |
| vectors = [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 plot | |
| traj_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 horizontal | |
| component of velocity remains constant. **Error analysis** shows how measurement | |
| uncertainty 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 calculations | |
| initial_speed = converter.convert_speed(initial_speed_input, speed_unit, "m/s") | |
| # Calculate results | |
| results = 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 plots | |
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) | |
| # Vector diagram | |
| initial_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 analysis | |
| traj_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 = None | |
| if 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 calculations | |
| mag_a = converter.convert_speed(mag_a_input, speed_unit, "m/s") | |
| mag_b = converter.convert_speed(mag_b_input, speed_unit, "m/s") | |
| # Create vectors | |
| vector_a = Vector2D(magnitude=mag_a, angle=angle_a) | |
| vector_b = Vector2D(magnitude=mag_b, angle=angle_b) | |
| resultant = vector_a + vector_b | |
| st.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 = None | |
| st.session_state.quiz_submitted = False | |
| st.session_state.show_explanation = False | |
| with col2: | |
| if st.button("π‘ Show Explanation") and st.session_state.quiz_question: | |
| st.session_state.show_explanation = True | |
| with col3: | |
| if st.button("π Reset Quiz"): | |
| st.session_state.quiz_question = None | |
| st.session_state.quiz_answer = None | |
| st.session_state.quiz_submitted = False | |
| st.session_state.show_explanation = False | |
| if st.session_state.quiz_question: | |
| question = st.session_state.quiz_question | |
| st.markdown("---") | |
| st.subheader("Question:") | |
| st.write(question["question"]) | |
| # Answer input | |
| user_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_answer | |
| st.session_state.quiz_submitted = True | |
| # Check answer | |
| if 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 explanation | |
| if 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 notes | |
| st.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 across | |
| 2. Increase current speed and watch the path change | |
| 3. Try launch angles of 45Β° for maximum range | |
| 4. Make two vectors perpendicular (90Β° apart) | |
| 5. Test the quiz mode to check your understanding | |
| 6. 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 | |
| """) |