File size: 15,107 Bytes
f9cd71d
06ac5eb
 
f9cd71d
06ac5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
321
322
323
324
325
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
""")