Spaces:
Paused
Paused
Download interactive_lab.py from jobinv/MathematicsApps: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/jobinv/MathematicsApps/resolve/main/interactive_lab.py
- Command line
-
hf download hf://spaces/jobinv/MathematicsApps/interactive_lab.py
-
curl -L -o interactive_lab.py https://huggingface.co/spaces/jobinv/MathematicsApps/resolve/main/interactive_lab.py
15 kB
| """User-authored, mathematically consistent two-body mechanics missions.""" | |
| from __future__ import annotations | |
| from hashlib import sha256 | |
| from html import escape | |
| import json | |
| from math import sqrt | |
| from typing import Any | |
| G = 9.8 | |
| IMPACT_MODELS = ( | |
| "Join together (perfectly inelastic)", | |
| "Separate with coefficient of restitution", | |
| ) | |
| def _number(value: Any, minimum: float, maximum: float) -> float: | |
| try: | |
| parsed = float(value) | |
| except (TypeError, ValueError): | |
| parsed = minimum | |
| return min(maximum, max(minimum, parsed)) | |
| def _answer(key: str, label: str, value: float, unit: str = "") -> dict[str, Any]: | |
| tolerance = max(0.02, abs(value) * 0.008) | |
| return { | |
| "key": key, | |
| "label": label, | |
| "value": float(value), | |
| "unit": unit, | |
| "tolerance": tolerance, | |
| "display": f"{value:.4g}{(' ' + unit) if unit else ''}", | |
| } | |
| def _collision_time(u1: float, u2: float, a1: float, a2: float, distance: float) -> float | None: | |
| """Return the first positive root of x_P(t) = x_Q(t).""" | |
| quadratic = 0.5 * (a1 - a2) | |
| linear = u1 - u2 | |
| if abs(quadratic) < 1e-10: | |
| return distance / linear if linear > 1e-10 else None | |
| discriminant = linear * linear + 4 * quadratic * distance | |
| if discriminant < -1e-10: | |
| return None | |
| root = sqrt(max(0.0, discriminant)) | |
| roots = [ | |
| (-linear - root) / (2 * quadratic), | |
| (-linear + root) / (2 * quadratic), | |
| ] | |
| positive = [value for value in roots if value > 1e-9] | |
| return min(positive) if positive else None | |
| def _stable_seed(payload: dict[str, Any]) -> int: | |
| encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") | |
| return int.from_bytes(sha256(encoded).digest()[:4], "big") % 1_000_000 | |
| def build_custom_collision_question( | |
| context: str = "robotics test track", | |
| difficulty: str = "Exam standard", | |
| impact_model: str = IMPACT_MODELS[1], | |
| restitution: float = 0.65, | |
| mass_p: float = 4.0, | |
| mass_q: float = 7.0, | |
| distance: float = 12.0, | |
| friction_p: float = 0.15, | |
| friction_q: float = 0.20, | |
| velocity_p: float = 8.0, | |
| velocity_q: float = -5.0, | |
| acceleration_p: float = 0.6, | |
| acceleration_q: float = -0.2, | |
| ) -> dict[str, Any]: | |
| """Build a question whose values and validated solution follow the controls.""" | |
| context = escape(" ".join(str(context or "mechanics laboratory").split())[:80]) | |
| difficulty = difficulty if difficulty in {"Foundation", "Exam standard", "Challenge"} else "Exam standard" | |
| impact_model = impact_model if impact_model in IMPACT_MODELS else IMPACT_MODELS[0] | |
| e = _number(restitution, 0.0, 1.0) | |
| m1 = _number(mass_p, 1.0, 12.0) | |
| m2 = _number(mass_q, 1.0, 12.0) | |
| d0 = _number(distance, 3.0, 30.0) | |
| mu1 = _number(friction_p, 0.0, 0.8) | |
| mu2 = _number(friction_q, 0.0, 0.8) | |
| u1 = _number(velocity_p, -20.0, 20.0) | |
| u2 = _number(velocity_q, -20.0, 20.0) | |
| a1 = _number(acceleration_p, -4.0, 4.0) | |
| a2 = _number(acceleration_q, -4.0, 4.0) | |
| payload = { | |
| "context": context, | |
| "difficulty": difficulty, | |
| "impact_model": impact_model, | |
| "e": e, | |
| "m1": m1, | |
| "m2": m2, | |
| "distance": d0, | |
| "mu1": mu1, | |
| "mu2": mu2, | |
| "u1": u1, | |
| "u2": u2, | |
| "a1": a1, | |
| "a2": a2, | |
| } | |
| seed = _stable_seed(payload) | |
| time = _collision_time(u1, u2, a1, a2, d0) | |
| direction_p = 1.0 if u1 > 0 else (-1.0 if u1 < 0 else (1.0 if a1 > 0 else (-1.0 if a1 < 0 else 0.0))) | |
| direction_q = 1.0 if u2 > 0 else (-1.0 if u2 < 0 else (1.0 if a2 > 0 else (-1.0 if a2 < 0 else 0.0))) | |
| friction_force_p = mu1 * m1 * G if direction_p else 0.0 | |
| friction_force_q = mu2 * m2 * G if direction_q else 0.0 | |
| driving_force_p = m1 * a1 + direction_p * friction_force_p | |
| driving_force_q = m2 * a2 + direction_q * friction_force_q | |
| common_diagram_data = { | |
| **payload, | |
| "collision": time is not None, | |
| "friction_force_p": friction_force_p, | |
| "friction_force_q": friction_force_q, | |
| "driving_force_p": driving_force_p, | |
| "driving_force_q": driving_force_q, | |
| "direction_p": direction_p, | |
| "direction_q": direction_q, | |
| } | |
| prompt_intro = rf""" | |
| In a {context}, two spherical rollers $P$ and $Q$ move along the same rough | |
| horizontal line. Take motion to the right as positive. Their masses are ${m1:g}\,\mathrm{{kg}}$ and | |
| ${m2:g}\,\mathrm{{kg}}$. Initially, $Q$ is ${d0:g}\,\mathrm{{m}}$ ahead of | |
| $P$. Their initial velocities are ${u1:g}\,\mathrm{{m\,s^{{-1}}}}$ and | |
| ${u2:g}\,\mathrm{{m\,s^{{-1}}}}$, and their stated constant **net** | |
| accelerations are ${a1:g}\,\mathrm{{m\,s^{{-2}}}}$ and | |
| ${a2:g}\,\mathrm{{m\,s^{{-2}}}}$ respectively. The coefficients of friction | |
| under $P$ and $Q$ are ${mu1:g}$ and ${mu2:g}$. Horizontal driving forces | |
| maintain the stated net accelerations, while friction acts opposite the | |
| instantaneous motion. Take $g=9.8\,\mathrm{{m\,s^{{-2}}}}$. | |
| """ | |
| if time is not None: | |
| x_impact = u1 * time + 0.5 * a1 * time * time | |
| v1 = u1 + a1 * time | |
| v2 = u2 + a2 * time | |
| momentum = m1 * v1 + m2 * v2 | |
| kinetic_before = 0.5 * m1 * v1 * v1 + 0.5 * m2 * v2 * v2 | |
| if impact_model.startswith("Join together"): | |
| post_p = post_q = momentum / (m1 + m2) | |
| impact_sentence = "They join together on impact." | |
| impact_answers = [_answer("v", "common velocity after impact", post_p, r"m s$^{-1}$")] | |
| impact_parts = ["(c) Find their common velocity immediately after impact."] | |
| impact_steps = [ | |
| rf"Conserve momentum during impact: $({m1:g})({v1:.4g})+({m2:g})({v2:.4g})=({m1 + m2:g})v$.", | |
| rf"Hence $v={post_p:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| ] | |
| else: | |
| relative_after = e * (v1 - v2) | |
| post_p = (momentum - m2 * relative_after) / (m1 + m2) | |
| post_q = (momentum + m1 * relative_after) / (m1 + m2) | |
| impact_sentence = rf"After impact they separate, and the coefficient of restitution is $e={e:g}$." | |
| impact_answers = [ | |
| _answer("vp", "velocity of P after impact", post_p, r"m s$^{-1}$"), | |
| _answer("vq", "velocity of Q after impact", post_q, r"m s$^{-1}$"), | |
| ] | |
| impact_parts = ["(c) Find the velocity of each roller immediately after impact."] | |
| impact_steps = [ | |
| rf"Momentum: $({m1:g})({v1:.4g})+({m2:g})({v2:.4g})={m1:g}v_P+{m2:g}v_Q$.", | |
| rf"Restitution: $v_Q-v_P={e:g}({v1:.4g}-{v2:.4g})$.", | |
| rf"Solving gives $v_P={post_p:.4g}$ and $v_Q={post_q:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| ] | |
| impulse = abs(m1 * (post_p - v1)) | |
| kinetic_after = 0.5 * m1 * post_p * post_p + 0.5 * m2 * post_q * post_q | |
| energy_loss = max(0.0, kinetic_before - kinetic_after) | |
| parts = [ | |
| "(a) Find the time at which $P$ first reaches $Q$.", | |
| "(b) Find the velocity of each roller immediately before impact.", | |
| ] | |
| answers = [ | |
| _answer("t", "time to impact", time, "s"), | |
| _answer("uP_impact", "velocity of P before impact", v1, r"m s$^{-1}$"), | |
| _answer("uQ_impact", "velocity of Q before impact", v2, r"m s$^{-1}$"), | |
| ] | |
| steps = [ | |
| rf"Use $x_P={u1:g}t+\tfrac12({a1:g})t^2$ and $x_Q={d0:g}+{u2:g}t+\tfrac12({a2:g})t^2$.", | |
| rf"Set $x_P=x_Q$ and take the first positive root, giving $t={time:.4g}\,\mathrm{{s}}$.", | |
| rf"Immediately before impact, $v_P={u1:g}+({a1:g})({time:.4g})={v1:.4g}$ and $v_Q={u2:g}+({a2:g})({time:.4g})={v2:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| ] | |
| if difficulty != "Foundation": | |
| parts.extend(impact_parts) | |
| parts.append("(d) Find the magnitude of the impulse exerted on $P$.") | |
| answers.extend(impact_answers) | |
| answers.append(_answer("J", "impulse on P", impulse, "N s")) | |
| steps.extend(impact_steps) | |
| steps.append(rf"Impulse on $P$ is $|m_P(v_P-u_P)|={impulse:.4g}\,\mathrm{{N\,s}}$.") | |
| if difficulty == "Challenge": | |
| parts.extend( | |
| [ | |
| "(e) Find the kinetic energy lost in the impact.", | |
| "(f) Find the initial horizontal driving force on each roller, taking right as positive.", | |
| ] | |
| ) | |
| answers.extend( | |
| [ | |
| _answer("E", "kinetic energy lost", energy_loss, "J"), | |
| _answer("XP", "driving force on P", driving_force_p, "N"), | |
| _answer("XQ", "driving force on Q", driving_force_q, "N"), | |
| ] | |
| ) | |
| steps.extend( | |
| [ | |
| rf"Energy lost $=KE_{{before}}-KE_{{after}}={energy_loss:.4g}\,\mathrm{{J}}$.", | |
| rf"Taking right as positive, $X_P=m_Pa_P+\operatorname{{sgn}}(u_P)\mu_Pm_Pg={driving_force_p:.4g}\,\mathrm{{N}}$.", | |
| rf"Similarly $X_Q=m_Qa_Q+\operatorname{{sgn}}(u_Q)\mu_Qm_Qg={driving_force_q:.4g}\,\mathrm{{N}}$.", | |
| ] | |
| ) | |
| marks = {"Foundation": 6, "Exam standard": 10, "Challenge": 15}[difficulty] | |
| common_diagram_data.update( | |
| { | |
| "time": time, | |
| "x_impact": x_impact, | |
| "v1_impact": v1, | |
| "v2_impact": v2, | |
| "post_p": post_p, | |
| "post_q": post_q, | |
| "impulse": impulse, | |
| "energy_loss": energy_loss, | |
| } | |
| ) | |
| common_errors = [] | |
| relative_speed = u1 - u2 | |
| if relative_speed > 0: | |
| common_errors.append( | |
| { | |
| "value": d0 / relative_speed, | |
| "title": "Relative acceleration was omitted", | |
| "explanation": "Distance divided by initial relative speed is valid only when the relative acceleration is zero.", | |
| } | |
| ) | |
| prompt = prompt_intro + "\n" + impact_sentence + "\n\n" + "\n".join(parts) | |
| hints = [ | |
| "Write separate displacement functions for P and Q from the same origin.", | |
| "Impact occurs when the two displacement functions give the same position.", | |
| "Use velocities at the impact time鈥攏ot the initial velocities鈥攊n the momentum equation.", | |
| ] | |
| else: | |
| gap_acceleration = a2 - a1 | |
| if gap_acceleration > 1e-10: | |
| closest_time = max(0.0, (u1 - u2) / gap_acceleration) | |
| else: | |
| closest_time = 0.0 | |
| closest_gap = d0 + (u2 - u1) * closest_time + 0.5 * gap_acceleration * closest_time**2 | |
| parts = [ | |
| "(a) Show that $P$ does not reach $Q$, and find the time at which their separation is least.", | |
| "(b) Find their least separation.", | |
| ] | |
| answers = [ | |
| _answer("tmin", "time of least separation", closest_time, "s"), | |
| _answer("dmin", "least separation", closest_gap, "m"), | |
| ] | |
| steps = [ | |
| rf"The separation is $s(t)={d0:g}+({u2:g}-{u1:g})t+\tfrac12({a2:g}-{a1:g})t^2$.", | |
| "The equation $s(t)=0$ has no positive real root, so the particles do not collide.", | |
| rf"Set $ds/dt=0$ to obtain $t={closest_time:.4g}\,\mathrm{{s}}$.", | |
| rf"Substitution gives the least separation $s_{{min}}={closest_gap:.4g}\,\mathrm{{m}}$.", | |
| ] | |
| if difficulty != "Foundation": | |
| parts.append("(c) Find the magnitude of the frictional resistance acting on each particle.") | |
| answers.extend( | |
| [ | |
| _answer("FP", "friction on P", friction_force_p, "N"), | |
| _answer("FQ", "friction on Q", friction_force_q, "N"), | |
| ] | |
| ) | |
| steps.append( | |
| rf"Using $F=\mu mg$, $F_P={friction_force_p:.4g}\,\mathrm{{N}}$ and $F_Q={friction_force_q:.4g}\,\mathrm{{N}}$." | |
| ) | |
| if difficulty == "Challenge": | |
| parts.append("(d) Find the initial horizontal driving force on each roller, taking right as positive.") | |
| answers.extend( | |
| [ | |
| _answer("XP", "driving force on P", driving_force_p, "N"), | |
| _answer("XQ", "driving force on Q", driving_force_q, "N"), | |
| ] | |
| ) | |
| steps.append( | |
| rf"Using $X=ma+\operatorname{{sgn}}(u)\mu mg$, $X_P={driving_force_p:.4g}\,\mathrm{{N}}$ and $X_Q={driving_force_q:.4g}\,\mathrm{{N}}$." | |
| ) | |
| marks = {"Foundation": 5, "Exam standard": 9, "Challenge": 13}[difficulty] | |
| common_diagram_data.update( | |
| { | |
| "closest_time": closest_time, | |
| "closest_gap": closest_gap, | |
| } | |
| ) | |
| common_errors = [] | |
| prompt = prompt_intro + "\n" + "\n".join(parts) | |
| hints = [ | |
| "Write the separation as position of Q minus position of P.", | |
| "A collision needs the separation equation to have a positive real zero.", | |
| "At closest approach, the derivative of separation is zero.", | |
| ] | |
| mark_scheme = [ | |
| {"step": "Correct displacement model and relative signs", "marks": 3}, | |
| {"step": "Correct physical root or closest-approach test", "marks": 3}, | |
| {"step": "Correct impact/friction model and units", "marks": max(1, marks - 6)}, | |
| ] | |
| return { | |
| "id": f"M1-LAB-{seed:06d}", | |
| "seed": seed, | |
| "topic": "custom_collision", | |
| "topic_label": "Creative lab 路 two-body mechanics", | |
| "difficulty": difficulty, | |
| "title": f"Custom Sphere Mission 路 {context.title()}", | |
| "prompt": prompt, | |
| "marks": marks, | |
| "expected_answers": answers, | |
| "solution_steps": steps, | |
| "mark_scheme": mark_scheme, | |
| "theory_key": "custom_collision", | |
| "hints": hints, | |
| "diagram_kind": "custom_collision", | |
| "diagram_data": common_diagram_data, | |
| "common_errors": common_errors, | |
| "source_note": "Original user-authored procedural mechanics scenario generated from the Creative Mechanics Lab controls.", | |
| } | |
| def custom_status_markdown(question: dict[str, Any]) -> str: | |
| data = question.get("diagram_data", {}) | |
| if data.get("collision"): | |
| impact = "join together" if data.get("impact_model", "").startswith("Join") else f"separate with e = {data.get('e', 0):g}" | |
| return ( | |
| f"### Live outcome: collision at **{data['time']:.3g} s**\n\n" | |
| rf"Before impact: $v_P={data['v1_impact']:.3g}\,\mathrm{{m\,s^{{-1}}}}$, " | |
| rf"$v_Q={data['v2_impact']:.3g}\,\mathrm{{m\,s^{{-1}}}}$ 路 particles {impact}." | |
| ) | |
| return ( | |
| "### Live outcome: no collision\n\n" | |
| f"Closest approach occurs at **{data['closest_time']:.3g} s**, with separation " | |
| f"**{data['closest_gap']:.3g} m**. The generated mission automatically changes to a closest-approach problem." | |
| ) | |