import gradio as gr import numpy as np import torch import sympy as sp from transformers import pipeline import plotly.graph_objects as go import plotly.express as px import matplotlib.pyplot as plt from scipy.integrate import odeint from typing import Dict, List, Tuple class PhysicsSolver: def __init__(self): self.nlp = pipeline("text-classification", model="bert-base-uncased") def solve_mechanics_problem(self, problem_text: str, problem_type: str) -> str: """Solve various physics problems using symbolic mathematics""" try: # Common symbols t, v, a, s, m, F, E, P, W, k, x = sp.symbols('t v a s m F E P W k x') g = 9.81 solutions = { 'kinematics': self._solve_kinematics, 'forces': self._solve_forces, 'energy': self._solve_energy, 'harmonic': self._solve_harmonic_motion } if problem_type in solutions: return solutions[problem_type](problem_text) else: return "Unsupported problem type" except Exception as e: return f"Error solving problem: {str(e)}" def _solve_kinematics(self, problem_text: str) -> str: """Handle kinematics problems""" t, v, a, s = sp.symbols('t v a s') solution = "Kinematics Analysis:\n\n" solution += "Using equations:\n" solution += "1. v = u + at\n" solution += "2. s = ut + ½at²\n" solution += "3. v² = u² + 2as\n\n" return solution def _solve_forces(self, problem_text: str) -> str: """Handle force and Newton's laws problems""" m, a, F = sp.symbols('m a F') solution = "Force Analysis:\n\n" solution += "Using Newton's Laws:\n" solution += "1. F = ma\n" solution += "2. Action = -Reaction\n" return solution def _solve_energy(self, problem_text: str) -> str: """Handle energy conservation problems""" m, v, h, k, E = sp.symbols('m v h k E') solution = "Energy Analysis:\n\n" solution += "Using energy conservation:\n" solution += "1. KE = ½mv²\n" solution += "2. PE = mgh\n" solution += "3. Total E = KE + PE\n" return solution def _solve_harmonic_motion(self, problem_text: str) -> str: """Handle simple harmonic motion problems""" m, k, x, t = sp.symbols('m k x t') solution = "Harmonic Motion Analysis:\n\n" solution += "Using SHM equations:\n" solution += "1. F = -kx\n" solution += "2. ω = √(k/m)\n" solution += "3. x = A cos(ωt)\n" return solution class ExperimentSimulator: def __init__(self): self.supported_experiments = ['pendulum', 'projectile', 'spring', 'wave'] def simulate_pendulum(self, length: float, theta0: float, time_span: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Simulate simple pendulum motion""" def pendulum_eq(state, t, L): theta, omega = state dydt = [omega, -(9.81/L) * np.sin(theta)] return dydt t = np.linspace(0, time_span, 1000) state0 = [theta0, 0] solution = odeint(pendulum_eq, state0, t, args=(length,)) x = length * np.sin(solution[:, 0]) y = -length * np.cos(solution[:, 0]) return x, y, t def simulate_projectile(self, v0: float, angle: float, height: float) -> Tuple[np.ndarray, np.ndarray]: """Simulate projectile motion""" g = 9.81 theta = np.radians(angle) # Calculate time of flight t_flight = (v0 * np.sin(theta) + np.sqrt((v0 * np.sin(theta))**2 + 2*g*height)) / g t = np.linspace(0, t_flight, 1000) # Calculate position x = v0 * np.cos(theta) * t y = height + v0 * np.sin(theta) * t - 0.5 * g * t**2 return x, y def simulate_spring(self, mass: float, k: float, x0: float, time_span: float) -> Tuple[np.ndarray, np.ndarray]: """Simulate spring motion""" omega = np.sqrt(k/mass) t = np.linspace(0, time_span, 1000) x = x0 * np.cos(omega * t) v = -x0 * omega * np.sin(omega * t) return x, v, t def simulate_wave(self, amplitude: float, frequency: float, wavelength: float, time_span: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Simulate wave propagation""" x = np.linspace(0, 5*wavelength, 1000) t = np.linspace(0, time_span, 100) k = 2 * np.pi / wavelength omega = 2 * np.pi * frequency X, T = np.meshgrid(x, t) Y = amplitude * np.sin(k*X - omega*T) return X, T, Y class VisualizationTools: @staticmethod def plot_pendulum(x: np.ndarray, y: np.ndarray, t: np.ndarray) -> go.Figure: """Create an interactive pendulum visualization""" fig = go.Figure() # Add pendulum path fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Pendulum Path')) # Add animation frames frames = [go.Frame(data=[go.Scatter( x=[0, x[i]], y=[0, y[i]], mode='lines+markers', line=dict(color='red', width=2), marker=dict(size=[10, 20]) )]) for i in range(0, len(t), 10)] fig.frames = frames # Add animation controls fig.update_layout( updatemenus=[dict( type='buttons', showactive=False, buttons=[dict(label='Play', method='animate', args=[None, dict(frame=dict(duration=50, redraw=True), fromcurrent=True, mode='immediate')])])]) fig.update_layout( title='Simple Pendulum Motion', xaxis_title='X Position (m)', yaxis_title='Y Position (m)', yaxis=dict(scaleanchor="x", scaleratio=1), ) return fig @staticmethod def plot_projectile(x: np.ndarray, y: np.ndarray) -> go.Figure: """Create projectile motion visualization""" fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Projectile Path')) fig.update_layout( title='Projectile Motion', xaxis_title='Distance (m)', yaxis_title='Height (m)', yaxis=dict(scaleanchor="x", scaleratio=1), ) return fig @staticmethod def plot_spring(x: np.ndarray, v: np.ndarray, t: np.ndarray) -> go.Figure: """Create spring motion visualization""" fig = go.Figure() fig.add_trace(go.Scatter(x=t, y=x, name='Position')) fig.add_trace(go.Scatter(x=t, y=v, name='Velocity')) fig.update_layout( title='Spring Motion', xaxis_title='Time (s)', yaxis_title='Position/Velocity', ) return fig @staticmethod def plot_wave(X: np.ndarray, T: np.ndarray, Y: np.ndarray) -> go.Figure: """Create wave propagation visualization""" fig = go.Figure() # Create animation frames frames = [go.Frame( data=[go.Scatter( x=X[i], y=Y[i], mode='lines', line=dict(width=2) )], name=f'frame{i}' ) for i in range(len(T))] fig.frames = frames # Add initial data fig.add_trace(go.Scatter( x=X[0], y=Y[0], mode='lines', line=dict(width=2) )) # Add animation controls fig.update_layout( updatemenus=[dict( type='buttons', showactive=False, buttons=[dict(label='Play', method='animate', args=[None, dict(frame=dict(duration=50, redraw=True), fromcurrent=True, mode='immediate')])])]) fig.update_layout( title='Wave Propagation', xaxis_title='Position (m)', yaxis_title='Amplitude', ) return fig def create_interface(): # Initialize components solver = PhysicsSolver() simulator = ExperimentSimulator() viz_tools = VisualizationTools() # Define interface functions def solve_physics_problem(problem_text: str, problem_type: str) -> str: return solver.solve_mechanics_problem(problem_text, problem_type) def run_pendulum_simulation(length: float, initial_angle: float, duration: float) -> go.Figure: x, y, t = simulator.simulate_pendulum(length, np.radians(initial_angle), duration) return viz_tools.plot_pendulum(x, y, t) def run_projectile_simulation(velocity: float, angle: float, height: float) -> go.Figure: x, y = simulator.simulate_projectile(velocity, angle, height) return viz_tools.plot_projectile(x, y) def run_spring_simulation(mass: float, k: float, x0: float, duration: float) -> go.Figure: x, v, t = simulator.simulate_spring(mass, k, x0, duration) return viz_tools.plot_spring(x, v, t) def run_wave_simulation(amplitude: float, frequency: float, wavelength: float, duration: float) -> go.Figure: X, T, Y = simulator.simulate_wave(amplitude, frequency, wavelength, duration) return viz_tools.plot_wave(X, T, Y) # Create the interface with gr.Blocks() as interface: gr.Markdown("# Enhanced AI Physics Platform") with gr.Tab("Problem Solver"): problem_input = gr.Textbox( label="Enter your physics problem", placeholder="Describe your physics problem here..." ) problem_type = gr.Dropdown( choices=['kinematics', 'forces', 'energy', 'harmonic'], label="Problem Type" ) solve_button = gr.Button("Solve Problem") solution_output = gr.Textbox(label="Solution") solve_button.click( fn=solve_physics_problem, inputs=[problem_input, problem_type], outputs=solution_output ) with gr.Tab("Pendulum Simulation"): with gr.Row(): length_input = gr.Slider(1, 10, value=2, label="Pendulum Length (m)") angle_input = gr.Slider(0, 90, value=45, label="Initial Angle (degrees)") duration_input = gr.Slider(1, 20, value=10, label="Simulation Duration (s)") pendulum_button = gr.Button("Run Pendulum Simulation") pendulum_plot = gr.Plot(label="Pendulum Motion") pendulum_button.click( fn=run_pendulum_simulation, inputs=[length_input, angle_input, duration_input], outputs=pendulum_plot ) with gr.Tab("Projectile Motion"): with gr.Row(): velocity_input = gr.Slider(0, 50, value=20, label="Initial Velocity (m/s)") proj_angle_input = gr.Slider(0, 90, value=45, label="Launch Angle (degrees)") height_input = gr.Slider(0, 100, value=0, label="Initial Height (m)") projectile_button = gr.Button("Run Projectile Simulation") projectile_plot = gr.Plot(label="Projectile Motion") projectile_button.click( fn=run_projectile_simulation, inputs=[velocity_input, proj_angle_input, height_input], outputs=projectile_plot ) with gr.Tab("Spring Motion"): with gr.Row(): mass_input = gr.Slider(0.1, 10, value=1, label="Mass (kg)") k_input = gr.Slider(1, 100, value=10, label="Spring Constant (N/m)") x0_input = gr.Slider(0.1, 2, value=0.5, label="Initial Displacement (m)") spring_duration = gr.Slider(1, 20, value=10, label="Simulation Duration (s)") spring_button = gr.Button("Run Spring Simulation") spring_plot = gr.Plot(label="Spring Motion") spring_button.click( fn=run_spring_simulation, inputs=[mass_input, k_input, x0_input, spring_duration], outputs=spring_plot ) with gr.Tab("Wave Propagation"): with gr.Row(): amp_input = gr.Slider(0.1, 2, value=1, label="Amplitude (m)") freq_input = gr.Slider(0.1, 5, value=1, label="Frequency (Hz)") wavelength_input = gr.Slider(0.1, 10, value=2, label="Wavelength (m)") wave_duration = gr.Slider(1, 20, value=10, label="Simulation Duration (s)") # Continuing from the previous code... wave_button = gr.Button("Run Wave Simulation") wave_plot = gr.Plot(label="Wave Propagation") wave_button.click( fn=run_wave_simulation, inputs=[amp_input, freq_input, wavelength_input, wave_duration], outputs=wave_plot ) with gr.Tab("Advanced Visualizations"): with gr.Row(): visualization_type = gr.Dropdown( choices=[ 'Phase Space Plot', 'Energy Distribution', 'Vector Field', '3D Motion' ], label="Visualization Type" ) def create_advanced_visualization(viz_type): if viz_type == 'Phase Space Plot': return create_phase_space_plot() elif viz_type == 'Energy Distribution': return create_energy_distribution() elif viz_type == 'Vector Field': return create_vector_field() elif viz_type == '3D Motion': return create_3d_motion() advanced_viz_button = gr.Button("Generate Visualization") advanced_plot = gr.Plot(label="Advanced Visualization") advanced_viz_button.click( fn=create_advanced_visualization, inputs=visualization_type, outputs=advanced_plot ) with gr.Tab("Data Analysis"): data_input = gr.File(label="Upload Experimental Data (CSV)") analysis_type = gr.Dropdown( choices=[ 'Statistical Analysis', 'Curve Fitting', 'Error Analysis', 'Fourier Transform' ], label="Analysis Type" ) def analyze_data(file, analysis_type): # Add data analysis functionality here return f"Analysis results for {analysis_type}" analyze_button = gr.Button("Analyze Data") analysis_output = gr.Textbox(label="Analysis Results") analysis_plot = gr.Plot(label="Analysis Visualization") analyze_button.click( fn=analyze_data, inputs=[data_input, analysis_type], outputs=[analysis_output, analysis_plot] ) return interface # Additional visualization functions def create_phase_space_plot(): """Create a phase space plot for a dynamical system""" fig = go.Figure() # Generate sample phase space data t = np.linspace(0, 20, 1000) x = np.sin(t) v = np.cos(t) fig.add_trace(go.Scatter(x=x, y=v, mode='lines', name='Phase Space Trajectory')) fig.update_layout( title='Phase Space Plot', xaxis_title='Position', yaxis_title='Velocity' ) return fig def create_energy_distribution(): """Create an energy distribution visualization""" fig = go.Figure() # Generate sample energy data E = np.linspace(0, 10, 100) P = np.exp(-E) * np.sqrt(E) # Maxwell-Boltzmann-like distribution fig.add_trace(go.Scatter(x=E, y=P, mode='lines', name='Energy Distribution')) fig.update_layout( title='Energy Distribution', xaxis_title='Energy (J)', yaxis_title='Probability Density' ) return fig def create_vector_field(): """Create a vector field visualization""" fig = go.Figure() # Generate vector field data x = np.linspace(-5, 5, 20) y = np.linspace(-5, 5, 20) X, Y = np.meshgrid(x, y) U = -Y # x-component of vector field V = X # y-component of vector field fig.add_trace(go.Cone( x=X.flatten(), y=Y.flatten(), u=U.flatten(), v=V.flatten(), name='Vector Field' )) fig.update_layout( title='Vector Field Visualization', scene=dict( xaxis_title='X', yaxis_title='Y' ) ) return fig def create_3d_motion(): """Create a 3D motion visualization""" fig = go.Figure() # Generate 3D motion data (e.g., spiral motion) t = np.linspace(0, 10*np.pi, 1000) x = np.cos(t) y = np.sin(t) z = t/10 fig.add_trace(go.Scatter3d( x=x, y=y, z=z, mode='lines', name='3D Motion Path' )) fig.update_layout( title='3D Motion Visualization', scene=dict( xaxis_title='X', yaxis_title='Y', zaxis_title='Z' ) ) return fig class DataAnalyzer: @staticmethod def statistical_analysis(data): """Perform statistical analysis on experimental data""" stats = { 'mean': np.mean(data), 'std': np.std(data), 'median': np.median(data), 'min': np.min(data), 'max': np.max(data) } return stats @staticmethod def curve_fit(x, y): """Perform curve fitting on experimental data""" from scipy.optimize import curve_fit def func(x, a, b, c): return a * np.exp(-b * x) + c popt, pcov = curve_fit(func, x, y) return popt, pcov @staticmethod def error_analysis(data, uncertainties): """Perform error propagation analysis""" # Add error analysis calculations here pass @staticmethod def fourier_transform(data): """Perform Fourier transform analysis""" from scipy.fft import fft, fftfreq n = len(data) freq = fftfreq(n) freq_spectrum = fft(data) return freq, freq_spectrum # Launch the interface if __name__ == "__main__": interface = create_interface() interface.launch(share=True)