Spaces:
Paused
Paused
Download creative_questions.py from jobinv/MathematicsApps: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/spaces/jobinv/MathematicsApps/resolve/main/creative_questions.py
- Command line
-
hf download hf://spaces/jobinv/MathematicsApps/creative_questions.py
-
curl -L -o creative_questions.py https://huggingface.co/spaces/jobinv/MathematicsApps/resolve/main/creative_questions.py
19.6 kB
| """Parameter-driven creative experiments beyond the collision arena.""" | |
| from __future__ import annotations | |
| from hashlib import sha256 | |
| from html import escape | |
| import json | |
| from math import cos, radians, sin, sqrt | |
| from typing import Any | |
| from interactive_lab import IMPACT_MODELS, build_custom_collision_question | |
| G = 9.8 | |
| CREATIVE_SCENARIOS = ( | |
| "Roller collision arena", | |
| "Electric train journey", | |
| "Rocket vertical launch", | |
| "Cargo trolley friction trial", | |
| ) | |
| 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]: | |
| return { | |
| "key": key, | |
| "label": label, | |
| "value": float(value), | |
| "unit": unit, | |
| "tolerance": max(0.02, abs(value) * 0.008), | |
| "display": f"{value:.4g}{(' ' + unit) if unit else ''}", | |
| } | |
| def _context(value: str) -> str: | |
| return escape(" ".join(str(value or "interactive engineering laboratory").split())[:80]) | |
| def _difficulty(value: str) -> str: | |
| return value if value in {"Foundation", "Exam standard", "Challenge"} else "Exam standard" | |
| def _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 _question( | |
| *, | |
| prefix: str, | |
| payload: dict[str, Any], | |
| topic_label: str, | |
| difficulty: str, | |
| title: str, | |
| prompt: str, | |
| answers: list[dict[str, Any]], | |
| steps: list[str], | |
| theory_key: str, | |
| diagram_kind: str, | |
| diagram_data: dict[str, Any], | |
| marks: int, | |
| hints: list[str], | |
| ) -> dict[str, Any]: | |
| seed = _seed(payload) | |
| return { | |
| "id": f"{prefix}-{seed:06d}", | |
| "seed": seed, | |
| "topic": diagram_kind, | |
| "topic_label": topic_label, | |
| "difficulty": difficulty, | |
| "title": title, | |
| "prompt": prompt, | |
| "marks": marks, | |
| "expected_answers": answers, | |
| "solution_steps": steps, | |
| "mark_scheme": [ | |
| {"step": "Correct model and sign convention", "marks": max(2, marks // 3)}, | |
| {"step": "Correct substitution and method", "marks": max(2, marks // 3)}, | |
| {"step": "Accurate answers with units", "marks": marks - 2 * max(2, marks // 3)}, | |
| ], | |
| "theory_key": theory_key, | |
| "hints": hints, | |
| "diagram_kind": diagram_kind, | |
| "diagram_data": diagram_data, | |
| "common_errors": [], | |
| "source_note": "Original parameter-driven mechanics experiment generated from the Creative Mechanics Lab controls.", | |
| } | |
| def build_train_question( | |
| context: str, | |
| difficulty: str, | |
| mass_tonnes: float, | |
| initial_velocity: float, | |
| acceleration: float, | |
| acceleration_time: float, | |
| cruise_time: float, | |
| braking_deceleration: float, | |
| resistance_kn: float, | |
| ) -> dict[str, Any]: | |
| context = _context(context) | |
| difficulty = _difficulty(difficulty) | |
| mass = _number(mass_tonnes, 20, 200) | |
| u = _number(initial_velocity, 0, 35) | |
| a = _number(acceleration, 0.2, 3) | |
| t_acc = _number(acceleration_time, 2, 20) | |
| t_cruise = _number(cruise_time, 2, 30) | |
| braking = _number(braking_deceleration, 0.2, 4) | |
| resistance = _number(resistance_kn, 0, 120) | |
| top_speed = u + a * t_acc | |
| braking_time = top_speed / braking | |
| acceleration_distance = u * t_acc + 0.5 * a * t_acc**2 | |
| cruise_distance = top_speed * t_cruise | |
| braking_distance = top_speed**2 / (2 * braking) | |
| total_distance = acceleration_distance + cruise_distance + braking_distance | |
| total_time = t_acc + t_cruise + braking_time | |
| average_speed = total_distance / total_time | |
| tractive_force = mass * a + resistance | |
| braking_energy = 0.5 * mass * 1000 * top_speed**2 / 1_000_000 | |
| payload = locals().copy() | |
| parts = [ | |
| "(a) Find the maximum speed of the train.", | |
| "(b) Find the time taken for the braking stage.", | |
| ] | |
| answers = [ | |
| _answer("vmax", "maximum speed", top_speed, r"m s$^{-1}$"), | |
| _answer("tbrake", "braking time", braking_time, "s"), | |
| ] | |
| steps = [ | |
| rf"After accelerating, $v={u:g}+({a:g})({t_acc:g})={top_speed:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| rf"During braking, $0={top_speed:.4g}-{braking:g}t$, so $t={braking_time:.4g}\,\mathrm{{s}}$.", | |
| ] | |
| if difficulty != "Foundation": | |
| parts.extend(["(c) Find the total distance travelled.", "(d) Find the average speed for the complete journey."]) | |
| answers.extend( | |
| [ | |
| _answer("distance", "total distance", total_distance, "m"), | |
| _answer("average", "average speed", average_speed, r"m s$^{-1}$"), | |
| ] | |
| ) | |
| steps.extend( | |
| [ | |
| rf"The three speed-time areas are ${acceleration_distance:.4g}$, ${cruise_distance:.4g}$ and ${braking_distance:.4g}$ m, so $s={total_distance:.4g}\,\mathrm{{m}}$.", | |
| rf"Average speed $=s/t={total_distance:.4g}/{total_time:.4g}={average_speed:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| ] | |
| ) | |
| if difficulty == "Challenge": | |
| parts.extend( | |
| [ | |
| "(e) Find the tractive force during the acceleration stage.", | |
| "(f) Find the kinetic energy removed while braking, in MJ.", | |
| ] | |
| ) | |
| answers.extend( | |
| [ | |
| _answer("force", "tractive force", tractive_force, "kN"), | |
| _answer("energy", "kinetic energy removed", braking_energy, "MJ"), | |
| ] | |
| ) | |
| steps.extend( | |
| [ | |
| rf"$F-R=ma$, so $F={mass:g}({a:g})+{resistance:g}={tractive_force:.4g}\,\mathrm{{kN}}$.", | |
| rf"The train stops, so energy removed $=\tfrac12mv^2={braking_energy:.4g}\,\mathrm{{MJ}}$.", | |
| ] | |
| ) | |
| marks = {"Foundation": 5, "Exam standard": 10, "Challenge": 15}[difficulty] | |
| prompt = rf""" | |
| In a {context}, an electric train of mass ${mass:g}$ tonnes moves along a | |
| straight horizontal track with initial speed ${u:g}\,\mathrm{{m\,s^{{-1}}}}$. | |
| It accelerates uniformly at ${a:g}\,\mathrm{{m\,s^{{-2}}}}$ for ${t_acc:g}$ s, | |
| continues at the resulting constant speed for ${t_cruise:g}$ s, and then brakes | |
| uniformly at ${braking:g}\,\mathrm{{m\,s^{{-2}}}}$ until it stops. The resistance | |
| to motion during acceleration is ${resistance:g}$ kN. | |
| {" ".join(parts)} | |
| """ | |
| return _question( | |
| prefix="M1-TRAIN", | |
| payload=payload, | |
| topic_label="Creative lab 路 train kinematics", | |
| difficulty=difficulty, | |
| title=f"Electric Train Experiment 路 {context.title()}", | |
| prompt=prompt, | |
| answers=answers, | |
| steps=steps, | |
| theory_key="custom_train", | |
| diagram_kind="custom_train", | |
| diagram_data={ | |
| "scene": "train", | |
| "mass_tonnes": mass, | |
| "u": u, | |
| "a": a, | |
| "t_acc": t_acc, | |
| "t_cruise": t_cruise, | |
| "braking": braking, | |
| "resistance_kn": resistance, | |
| "top_speed": top_speed, | |
| "braking_time": braking_time, | |
| "total_time": total_time, | |
| "total_distance": total_distance, | |
| "average_speed": average_speed, | |
| "tractive_force": tractive_force, | |
| "braking_energy": braking_energy, | |
| }, | |
| marks=marks, | |
| hints=[ | |
| "Treat the journey as acceleration, constant-speed and braking stages.", | |
| "Distance is the area under the speed-time graph.", | |
| "Average speed is total distance divided by total time.", | |
| ], | |
| ) | |
| def build_rocket_question( | |
| context: str, | |
| difficulty: str, | |
| mass_kg: float, | |
| launch_height: float, | |
| launch_velocity: float, | |
| gravity: float, | |
| ) -> dict[str, Any]: | |
| context = _context(context) | |
| difficulty = _difficulty(difficulty) | |
| mass = _number(mass_kg, 50, 500) | |
| height = _number(launch_height, 0, 50) | |
| velocity = _number(launch_velocity, 5, 80) | |
| g = _number(gravity, 5, 12) | |
| top_time = velocity / g | |
| top_height = height + velocity**2 / (2 * g) | |
| landing_time = (velocity + sqrt(velocity**2 + 2 * g * height)) / g | |
| impact_speed = sqrt(velocity**2 + 2 * g * height) | |
| impact_energy = 0.5 * mass * impact_speed**2 / 1000 | |
| payload = locals().copy() | |
| parts = ["(a) Find the time taken to reach the highest point.", "(b) Find the greatest height above the ground."] | |
| answers = [ | |
| _answer("ttop", "time to highest point", top_time, "s"), | |
| _answer("hmax", "greatest height", top_height, "m"), | |
| ] | |
| steps = [ | |
| rf"At the highest point $v=0$, so $0={velocity:g}-{g:g}t$ and $t={top_time:.4g}\,\mathrm{{s}}$.", | |
| rf"Using $v^2=u^2+2as$, the rise is ${velocity:g}^2/(2\times{g:g})$, giving height ${top_height:.4g}\,\mathrm{{m}}$.", | |
| ] | |
| if difficulty != "Foundation": | |
| parts.extend(["(c) Find the time at which the capsule reaches the ground.", "(d) Find its speed immediately before landing."]) | |
| answers.extend( | |
| [ | |
| _answer("tground", "time to ground", landing_time, "s"), | |
| _answer("vground", "landing speed", impact_speed, r"m s$^{-1}$"), | |
| ] | |
| ) | |
| steps.extend( | |
| [ | |
| rf"Set ground displacement to $-{height:g}$: $-{height:g}={velocity:g}t-\tfrac12({g:g})t^2$. The positive root is ${landing_time:.4g}\,\mathrm{{s}}$.", | |
| rf"$v^2={velocity:g}^2+2({g:g})({height:g})$, so the landing speed is ${impact_speed:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| ] | |
| ) | |
| if difficulty == "Challenge": | |
| parts.append("(e) Find the kinetic energy of the capsule immediately before landing, in kJ.") | |
| answers.append(_answer("energy", "landing kinetic energy", impact_energy, "kJ")) | |
| steps.append(rf"$KE=\tfrac12mv^2={impact_energy:.4g}\,\mathrm{{kJ}}$.") | |
| marks = {"Foundation": 5, "Exam standard": 10, "Challenge": 13}[difficulty] | |
| prompt = rf""" | |
| In a {context}, a ${mass:g}$ kg rocket capsule is launched vertically upward | |
| from a platform ${height:g}$ m above the ground with speed | |
| ${velocity:g}\,\mathrm{{m\,s^{{-1}}}}$. Its engine cuts off immediately after | |
| launch. Air resistance is ignored and gravitational acceleration is | |
| ${g:g}\,\mathrm{{m\,s^{{-2}}}}$ downward. | |
| {" ".join(parts)} | |
| """ | |
| return _question( | |
| prefix="M1-ROCKET", | |
| payload=payload, | |
| topic_label="Creative lab 路 vertical motion", | |
| difficulty=difficulty, | |
| title=f"Rocket Launch Experiment 路 {context.title()}", | |
| prompt=prompt, | |
| answers=answers, | |
| steps=steps, | |
| theory_key="custom_rocket", | |
| diagram_kind="custom_rocket", | |
| diagram_data={ | |
| "scene": "rocket", | |
| "mass_kg": mass, | |
| "height": height, | |
| "u": velocity, | |
| "g": g, | |
| "top_time": top_time, | |
| "top_height": top_height, | |
| "landing_time": landing_time, | |
| "impact_speed": impact_speed, | |
| "impact_energy": impact_energy, | |
| }, | |
| marks=marks, | |
| hints=[ | |
| "Choose upward as positive, so acceleration is negative.", | |
| "At the highest point the velocity is zero, but acceleration is still downward.", | |
| "Use the positive time root when solving for the ground.", | |
| ], | |
| ) | |
| def build_trolley_question( | |
| context: str, | |
| difficulty: str, | |
| mass_kg: float, | |
| pull_force: float, | |
| pull_angle: float, | |
| friction_coefficient: float, | |
| initial_velocity: float, | |
| trial_time: float, | |
| ) -> dict[str, Any]: | |
| context = _context(context) | |
| difficulty = _difficulty(difficulty) | |
| mass = _number(mass_kg, 10, 50) | |
| force = _number(pull_force, 20, 120) | |
| angle = _number(pull_angle, 0, 40) | |
| mu = _number(friction_coefficient, 0, 0.6) | |
| u = _number(initial_velocity, 1, 20) | |
| duration = _number(trial_time, 1, 10) | |
| theta = radians(angle) | |
| reaction = mass * G - force * sin(theta) | |
| friction = mu * reaction | |
| acceleration = (force * cos(theta) - friction) / mass | |
| stopping_time = -u / acceleration if acceleration < 0 else float("inf") | |
| stopped = stopping_time <= duration | |
| motion_time = stopping_time if stopped else duration | |
| final_velocity = 0.0 if stopped else u + acceleration * duration | |
| displacement = u * motion_time + 0.5 * acceleration * motion_time**2 | |
| work_done = force * cos(theta) * displacement / 1000 | |
| payload = { | |
| "context": context, | |
| "difficulty": difficulty, | |
| "mass": mass, | |
| "force": force, | |
| "angle": angle, | |
| "mu": mu, | |
| "u": u, | |
| "duration": duration, | |
| } | |
| parts = ["(a) Find the normal reaction and the frictional resistance.", "(b) Find the acceleration of the trolley."] | |
| answers = [ | |
| _answer("reaction", "normal reaction", reaction, "N"), | |
| _answer("friction", "frictional resistance", friction, "N"), | |
| _answer("acceleration", "acceleration", acceleration, r"m s$^{-2}$"), | |
| ] | |
| steps = [ | |
| rf"Vertically, $R+{force:g}\sin {angle:g}^\circ={mass:g}g$, so $R={reaction:.4g}\,\mathrm{{N}}$.", | |
| rf"Friction is $\mu R={friction:.4g}\,\mathrm{{N}}$.", | |
| rf"Horizontally, ${force:g}\cos {angle:g}^\circ-{friction:.4g}={mass:g}a$, hence $a={acceleration:.4g}\,\mathrm{{m\,s^{{-2}}}}$.", | |
| ] | |
| if stopped: | |
| parts.append(f"(c) Show that it stops within ${duration:g}$ s, and find its stopping distance.") | |
| answers.extend( | |
| [ | |
| _answer("tstop", "stopping time", stopping_time, "s"), | |
| _answer("distance", "stopping distance", displacement, "m"), | |
| ] | |
| ) | |
| steps.extend( | |
| [ | |
| rf"Set $v=0$ in $v=u+at$: $t={stopping_time:.4g}\,\mathrm{{s}}<{duration:g}\,\mathrm{{s}}$.", | |
| rf"The stopping distance is $s=ut+\tfrac12at^2={displacement:.4g}\,\mathrm{{m}}$.", | |
| ] | |
| ) | |
| else: | |
| parts.append(f"(c) Find its speed and displacement after ${duration:g}$ s.") | |
| answers.extend( | |
| [ | |
| _answer("velocity", "final speed", final_velocity, r"m s$^{-1}$"), | |
| _answer("distance", "displacement", displacement, "m"), | |
| ] | |
| ) | |
| steps.extend( | |
| [ | |
| rf"$v=u+at={u:g}+({acceleration:.4g})({duration:g})={final_velocity:.4g}\,\mathrm{{m\,s^{{-1}}}}$.", | |
| rf"$s=ut+\tfrac12at^2={displacement:.4g}\,\mathrm{{m}}$.", | |
| ] | |
| ) | |
| if difficulty == "Challenge": | |
| parts.append("(d) Find the work done by the pulling force during the motion, in kJ.") | |
| answers.append(_answer("work", "work done by pull", work_done, "kJ")) | |
| steps.append(rf"Work $=Ps\cos\theta={work_done:.4g}\,\mathrm{{kJ}}$.") | |
| marks = {"Foundation": 7, "Exam standard": 10, "Challenge": 13}[difficulty] | |
| prompt = rf""" | |
| In a {context}, a ${mass:g}$ kg cargo trolley is already moving to the right at | |
| ${u:g}\,\mathrm{{m\,s^{{-1}}}}$ on a rough horizontal floor. It is pulled by a | |
| force of ${force:g}$ N acting at ${angle:g}^\circ$ above the horizontal. The | |
| coefficient of friction is ${mu:g}$. Take $g=9.8\,\mathrm{{m\,s^{{-2}}}}$ and | |
| assume friction has magnitude $\mu R$ while the trolley is moving. | |
| {" ".join(parts)} | |
| """ | |
| return _question( | |
| prefix="M1-TROLLEY", | |
| payload=payload, | |
| topic_label="Creative lab 路 friction and forces", | |
| difficulty=difficulty, | |
| title=f"Cargo Trolley Experiment 路 {context.title()}", | |
| prompt=prompt, | |
| answers=answers, | |
| steps=steps, | |
| theory_key="custom_trolley", | |
| diagram_kind="custom_trolley", | |
| diagram_data={ | |
| "scene": "trolley", | |
| "mass_kg": mass, | |
| "force": force, | |
| "angle": angle, | |
| "mu": mu, | |
| "u": u, | |
| "trial_time": duration, | |
| "reaction": reaction, | |
| "friction": friction, | |
| "a": acceleration, | |
| "stopped": stopped, | |
| "motion_time": motion_time, | |
| "final_velocity": final_velocity, | |
| "displacement": displacement, | |
| "work_done": work_done, | |
| }, | |
| marks=marks, | |
| hints=[ | |
| "Resolve the pulling force horizontally and vertically.", | |
| "The upward force component reduces the normal reaction.", | |
| "Check whether a negative acceleration brings the trolley to rest before using the full trial time.", | |
| ], | |
| ) | |
| def build_creative_question( | |
| scenario: str, | |
| context: str, | |
| difficulty: str, | |
| impact_model: str, | |
| restitution: float, | |
| mass_p: float, | |
| mass_q: float, | |
| distance: float, | |
| friction_p: float, | |
| friction_q: float, | |
| velocity_p: float, | |
| velocity_q: float, | |
| acceleration_p: float, | |
| acceleration_q: float, | |
| train_mass: float, | |
| train_u: float, | |
| train_a: float, | |
| train_accel_time: float, | |
| train_cruise_time: float, | |
| train_braking: float, | |
| train_resistance: float, | |
| rocket_mass: float, | |
| rocket_height: float, | |
| rocket_u: float, | |
| rocket_g: float, | |
| trolley_mass: float, | |
| trolley_force: float, | |
| trolley_angle: float, | |
| trolley_mu: float, | |
| trolley_u: float, | |
| trolley_time: float, | |
| ) -> dict[str, Any]: | |
| if scenario == CREATIVE_SCENARIOS[1]: | |
| return build_train_question( | |
| context, | |
| difficulty, | |
| train_mass, | |
| train_u, | |
| train_a, | |
| train_accel_time, | |
| train_cruise_time, | |
| train_braking, | |
| train_resistance, | |
| ) | |
| if scenario == CREATIVE_SCENARIOS[2]: | |
| return build_rocket_question(context, difficulty, rocket_mass, rocket_height, rocket_u, rocket_g) | |
| if scenario == CREATIVE_SCENARIOS[3]: | |
| return build_trolley_question( | |
| context, | |
| difficulty, | |
| trolley_mass, | |
| trolley_force, | |
| trolley_angle, | |
| trolley_mu, | |
| trolley_u, | |
| trolley_time, | |
| ) | |
| return build_custom_collision_question( | |
| context, | |
| difficulty, | |
| impact_model if impact_model in IMPACT_MODELS else IMPACT_MODELS[1], | |
| restitution, | |
| mass_p, | |
| mass_q, | |
| distance, | |
| friction_p, | |
| friction_q, | |
| velocity_p, | |
| velocity_q, | |
| acceleration_p, | |
| acceleration_q, | |
| ) | |
| def creative_status_markdown(question: dict[str, Any]) -> str: | |
| data = question.get("diagram_data", {}) | |
| scene = data.get("scene") | |
| if question.get("diagram_kind") == "custom_collision": | |
| from interactive_lab import custom_status_markdown | |
| return custom_status_markdown(question) | |
| if scene == "train": | |
| return ( | |
| f"### Live outcome: train stops after **{data['total_time']:.3g} s**\n\n" | |
| f"Maximum speed **{data['top_speed']:.3g} m/s** 路 total distance **{data['total_distance']:.3g} m**." | |
| ) | |
| if scene == "rocket": | |
| return ( | |
| f"### Live outcome: highest point **{data['top_height']:.3g} m**\n\n" | |
| f"Landing occurs at **{data['landing_time']:.3g} s** with speed **{data['impact_speed']:.3g} m/s**." | |
| ) | |
| return ( | |
| f"### Live outcome: trolley acceleration **{data['a']:.3g} m/s虏**\n\n" | |
| f"It travels **{data['displacement']:.3g} m**" | |
| + (f" and stops after **{data['motion_time']:.3g} s**." if data.get("stopped") else f" in **{data['motion_time']:.3g} s**.") | |
| ) | |