""" app.py - Projectile / missile simulator (Gradio app) Features: - 2D simulator with gravity, quadratic air drag, wind, optional thrust (boost phase), and a simple guidance (steering) mode that tries to steer to a target. - RK4 integrator for stability. - Animated frames produced and streamed to the frontend via a Python generator. - Allows input by structured controls (sliders) or a short natural-language prompt (rule-based parsing). - Exports final trajectory CSV. Run locally: pip install -r requirements.txt python app.py Deploy: drop these two files into a Hugging Face Space (Gradio). Gradio auto-detects app.py. """ import io import math import csv import time from typing import Tuple, Iterator, List import numpy as np import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from PIL import Image import gradio as gr # ---------------------------- # Physics / simulation utils # ---------------------------- g = 9.81 # m/s^2 def drag_force(v_vec: np.ndarray, rho: float, Cd: float, A: float) -> np.ndarray: # Quadratic drag: 0.5 * rho * Cd * A * v^2, direction opposite velocity v = np.linalg.norm(v_vec) if v == 0.0: return np.zeros_like(v_vec) mag = 0.5 * rho * Cd * A * v * v return -mag * (v_vec / v) def thrust_force(thrust: float, mass: float, direction: np.ndarray) -> np.ndarray: # thrust: Newtons, direction: unit vector if thrust <= 0: return np.zeros_like(direction) nd = direction / (np.linalg.norm(direction) + 1e-12) return (thrust / mass) * nd def integrate_rk4(state: np.ndarray, dt: float, deriv_func) -> np.ndarray: # state: [x, y, vx, vy] k1 = deriv_func(state) k2 = deriv_func(state + 0.5 * dt * k1) k3 = deriv_func(state + 0.5 * dt * k2) k4 = deriv_func(state + dt * k3) return state + (dt / 6.0) * (k1 + 2*k2 + 2*k3 + k4) # ---------------------------- # Simulator # ---------------------------- def simulate_trajectory( v0: float, angle_deg: float, launch_height: float, target_x: float, target_y: float, mass: float, Cd: float, area: float, rho: float, wind: float, thrust: float, boost_time: float, guidance: bool, steering_accel_limit: float, dt: float = 0.02, max_time: float = 200.0, ) -> Tuple[List[Tuple[float,float]], dict]: """ Simulate 2D flight and return list of (x,y) positions and summary dict. guidance: if True, apply simple Proportional steering acceleration toward target. steering_accel_limit: max lateral acceleration magnitude (m/s^2) missile can command. """ angle = math.radians(angle_deg) vx0 = v0 * math.cos(angle) vy0 = v0 * math.sin(angle) state = np.array([0.0, launch_height, vx0, vy0], dtype=float) # x,y,vx,vy t = 0.0 traj = [] impact_time = None impact_pos = None closest_dist = float("inf") time_of_closest = 0.0 while t < max_time: x, y, vx, vy = state traj.append((x, y)) # stop if crashed into ground (y <= 0) if y <= 0 and t > 1e-6: impact_time = t impact_pos = (x, y) break # store closest approach to target dist = math.hypot(x - target_x, y - target_y) if dist < closest_dist: closest_dist = dist time_of_closest = t # prepare derivative function (closure using t and state) def deriv(s): sx, sy, svx, svy = s vel = np.array([svx, svy]) # wind affects relative velocity (wind speed is horizontal) vel_rel = vel - np.array([wind, 0.0]) Fd = drag_force(vel_rel, rho, Cd, area) # gravity ag = np.array([0.0, -g]) # thrust (only if t < boost_time) if t < boost_time and thrust > 0: # thrust direction: current velocity direction (prograde) unless nearly zero vnorm = np.linalg.norm(vel) if vnorm < 1e-6: thrust_dir = np.array([math.cos(angle), math.sin(angle)]) else: thrust_dir = vel / vnorm a_thrust = thrust_force(thrust, mass, thrust_dir) else: a_thrust = np.zeros(2) # guidance steering acceleration (adds to a_thrust) a_guidance = np.zeros(2) if guidance: # simple proportional steering towards target position pos = np.array([sx, sy]) to_target = np.array([target_x, target_y]) - pos dist_to_target = np.linalg.norm(to_target) + 1e-12 # desired acceleration magnitude proportional to closing velocity/distance # we bound the magnitude to steering_accel_limit desired_dir = to_target / dist_to_target # compute needed lateral acceleration to rotate velocity toward desired_dir # Simplest: command acceleration in desired_dir a_desired = desired_dir * steering_accel_limit a_guidance = a_desired # total acceleration a_total = ag + (Fd / mass) + a_thrust + a_guidance return np.array([svx, svy, a_total[0], a_total[1]]) state = integrate_rk4(state, dt, deriv) t += dt # if no impact detected, approximate impact by linear interpolation to ground if impact_time is None: # find last crossing where y becomes negative if len(traj) >= 2: x1, y1 = traj[-2] x2, y2 = traj[-1] if y1 > 0 and y2 <= 0: frac = y1 / (y1 - y2 + 1e-12) xi = x1 + frac * (x2 - x1) yi = 0.0 impact_pos = (xi, yi) impact_time = (len(traj)-2) * dt + frac*dt # summary xs = [p[0] for p in traj] ys = [p[1] for p in traj] summary = { "flight_time": impact_time if impact_time is not None else t, "impact_pos": impact_pos, "range_est": impact_pos[0] if impact_pos is not None else xs[-1] if xs else 0.0, "max_height": max(ys) if ys else 0.0, "closest_distance_to_target": closest_dist, "time_of_closest": time_of_closest, "num_steps": len(traj) } return traj, summary # ---------------------------- # Visualization: generate frames and stream # ---------------------------- def make_frame_image(traj_so_far, target, launch_height, xlim=None, ylim=None, show_annotations=True) -> Image.Image: fig, ax = plt.subplots(figsize=(8,4.5), dpi=100) xs = [p[0] for p in traj_so_far] ys = [p[1] for p in traj_so_far] if len(xs) > 0: ax.plot(xs, ys, linewidth=2) ax.scatter(xs[-1:], ys[-1:], s=80, marker='o') # current missile # ground line ax.axhline(0.0, color='k', linewidth=0.8) # launch marker ax.scatter([0.0], [launch_height], marker='^', s=70) # target marker ax.scatter([target[0]], [target[1]], marker='x', s=80) # axis limits if xlim is None: xspread = max(50.0, max(xs) if xs else 100.0) ax.set_xlim(-0.1 * xspread, 1.1 * xspread) else: ax.set_xlim(xlim) if ylim is None: ymax = max( max(ys) if ys else 50.0, launch_height + 10.0, target[1]+10.0 ) ax.set_ylim(min(-10.0, min(ys) if ys else -10.0), ymax*1.1) else: ax.set_ylim(ylim) ax.set_xlabel("x (m)") ax.set_ylabel("y (m)") ax.set_title("Missile trajectory (streaming animation)") if show_annotations: ax.grid(True, linestyle='--', linewidth=0.4) # show last coordinates if len(xs)>0: ax.text(0.02, 0.92, f"pos: {xs[-1]:.1f} m, {ys[-1]:.1f} m", transform=ax.transAxes) buf = io.BytesIO() plt.tight_layout() fig.canvas.draw() plt.savefig(buf, format='png') plt.close(fig) buf.seek(0) im = Image.open(buf).convert("RGB") return im # ---------------------------- # Rule-based prompt parser (simple) # ---------------------------- def parse_prompt(prompt: str): # Very simple heuristic extraction for values like "speed 300 m/s angle 30 target 8000 0" out = {} toks = prompt.lower().replace(',', ' ').split() def get_num_after(key): if key in toks: i = toks.index(key) if i+1 < len(toks): try: return float(toks[i+1]) except: return None return None # try some keys maybe_v = get_num_after("speed") or get_num_after("v0") or get_num_after("v") maybe_angle = get_num_after("angle") or get_num_after("theta") maybe_targetx = get_num_after("target") # if user writes 'target 8000' # if 'target' followed by two numbers capture both if "target" in toks: i = toks.index("target") if i+2 < len(toks): try: tx = float(toks[i+1]); ty = float(toks[i+2]) out["target_x"] = tx out["target_y"] = ty except: pass if maybe_v is not None: out["v0"] = maybe_v if maybe_angle is not None: out["angle_deg"] = maybe_angle # fallback: parse first two numbers as speed and angle if no keys present nums = [float(x) for x in toks if is_number(x)] if "v0" not in out and len(nums) >= 1: out["v0"] = nums[0] if "angle_deg" not in out and len(nums) >= 2: out["angle_deg"] = nums[1] return out def is_number(s): try: float(s) return True except: return False # ---------------------------- # Gradio app function (generator) # ---------------------------- def run_sim_stream( # prompt + structured inputs prompt: str, v0: float, angle: float, launch_height: float, target_x: float, target_y: float, mass: float, Cd: float, area: float, rho: float, wind: float, thrust: float, boost_time: float, guidance: bool, steering_limit: float, dt: float, speed_multiplier: float ): # parse prompt if provided (overrides values if present) if prompt and prompt.strip(): parsed = parse_prompt(prompt) if "v0" in parsed: v0 = parsed["v0"] if "angle_deg" in parsed: angle = parsed["angle_deg"] if "target_x" in parsed: target_x = parsed["target_x"] if "target_y" in parsed: target_y = parsed["target_y"] # Run the simulation but stream frames as we go. We'll step the integrator in small chunks # and yield a frame every N steps to avoid huge bandwidth. # To keep the UI responsive, we create a small internal dt for physics and optionally speed up visualization. phys_dt = dt # run simulation step-by-step, but re-use simulate_trajectory inner logic for convenience: traj, summary = simulate_trajectory( v0=v0, angle_deg=angle, launch_height=launch_height, target_x=target_x, target_y=target_y, mass=mass, Cd=Cd, area=area, rho=rho, wind=wind, thrust=thrust, boost_time=boost_time, guidance=guidance, steering_accel_limit=steering_limit, dt=phys_dt, max_time=200.0 ) # Determine plotting windows xs = [p[0] for p in traj] ys = [p[1] for p in traj] xlim = (min(0.0, min(xs)-50), max(xs)+50) if xs else (-100, 100) ylim = (min(-10.0, min(ys)-10), max(max(ys)+20, launch_height+50)) if ys else (-50, 200) # Stream frames: we'll produce up to ~200 frames uniformly sampled along trajectory n_frames = min(250, len(traj)) if n_frames <= 0: # nothing to show, yield a blank image and message blank = Image.new("RGB", (800, 450), (255,255,255)) yield blank, "No flight computed (check inputs)." return step = max(1, len(traj) // n_frames) for i in range(0, len(traj), step): subtraj = traj[:i+1] im = make_frame_image(subtraj, (target_x, target_y), launch_height, xlim=xlim, ylim=ylim) status = f"t ≈ {i*phys_dt:.2f} s, x ≈ {traj[i][0]:.1f} m, y ≈ {traj[i][1]:.1f} m" yield im, status # small sleep to make streaming visible in some environments (Hugging Face / local) time.sleep(max(0.01, 0.02 / speed_multiplier)) # final frame and summary final_im = make_frame_image(traj, (target_x, target_y), launch_height, xlim=xlim, ylim=ylim) summary_text = ( f"Flight time: {summary['flight_time']:.2f} s\n" f"Range (impact x): {summary['range_est']:.1f} m\n" f"Max height: {summary['max_height']:.1f} m\n" f"Closest distance to target: {summary['closest_distance_to_target']:.1f} m\n" f"Steps simulated: {summary['num_steps']}\n" ) yield final_im, summary_text # Helper to produce downloadable CSV (trajectory) def traj_to_csv_bytes(traj: List[Tuple[float,float]], dt: float) -> bytes: buf = io.StringIO() writer = csv.writer(buf) writer.writerow(["step", "t_s", "x_m", "y_m"]) for i, (x,y) in enumerate(traj): writer.writerow([i, i*dt, x, y]) return buf.getvalue().encode("utf-8") # ---------------------------- # Gradio UI definition # ---------------------------- title = "Missile / Projectile Simulator (streaming)" description = "2D projectile/missile simulator with drag, wind, thrust, and simple guidance. Use sliders to set physical parameters or type a short prompt like 'speed 300 angle 30 target 8000 0'." with gr.Blocks(title=title) as demo: gr.Markdown(f"# {title}") gr.Markdown(description) with gr.Row(): with gr.Column(scale=2): prompt = gr.Textbox(label="Natural-language prompt (optional)", placeholder="e.g. speed 300 angle 30 target 8000 0", lines=2) with gr.Row(): v0_in = gr.Number(value=300.0, label="Initial speed v0 (m/s)") angle_in = gr.Slider(minimum=0, maximum=90, value=30, label="Launch angle (deg)") with gr.Row(): launch_height_in = gr.Number(value=0.0, label="Launch height (m)") target_x_in = gr.Number(value=8000.0, label="Target x (m)") target_y_in = gr.Number(value=0.0, label="Target y (m)") gr.Markdown("**Aerodynamics**") with gr.Row(): mass_in = gr.Number(value=100.0, label="Mass (kg)") Cd_in = gr.Number(value=0.5, label="Drag coefficient Cd") area_in = gr.Number(value=0.1, label="Cross-sectional area A (m^2)") with gr.Row(): rho_in = gr.Number(value=1.225, label="Air density rho (kg/m^3)") wind_in = gr.Number(value=0.0, label="Wind speed (m/s, +ve is tailwind)") gr.Markdown("**Propulsion & guidance**") with gr.Row(): thrust_in = gr.Number(value=0.0, label="Thrust (N, constant during boost)") boost_time_in = gr.Number(value=0.0, label="Boost duration (s)") guidance_in = gr.Checkbox(label="Enable simple guidance (steer toward target)", value=False) steering_in = gr.Number(value=10.0, label="Guidance accel limit (m/s^2)") gr.Markdown("**Simulation controls**") with gr.Row(): dt_in = gr.Slider(minimum=0.001, maximum=0.05, value=0.02, step=0.001, label="Simulation dt (s)") speed_mult = gr.Slider(minimum=0.1, maximum=5.0, value=1.0, step=0.1, label="Playback speed multiplier") run_btn = gr.Button("Run simulation (stream)") with gr.Column(scale=3): img_out = gr.Image(label="Simulation (streaming frames)", height=450, width=800) status_out = gr.Textbox(label="Status / Summary", lines=6) # Wire the generator-based function (yields image, status) run_btn.click( fn=run_sim_stream, inputs=[prompt, v0_in, angle_in, launch_height_in, target_x_in, target_y_in, mass_in, Cd_in, area_in, rho_in, wind_in, thrust_in, boost_time_in, guidance_in, steering_in, dt_in, speed_mult], outputs=[img_out, status_out], ) gr.Markdown("---") gr.Markdown("Tip: If you want to deploy on Hugging Face Spaces, just upload this file and the requirements.txt. Gradio will auto-detect the app.") if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)