"""Precalculus perceptual-learning item generator — sympy is the ground-truth oracle. Two PLM categories (classification at a glance, not problem solving — Kellman, Massey & Son 2010; their algebra/graphing PLMs trained exactly this kind of mapping): - `function_family` — GraphSense: see a graph, name its function family. Each item is a random transformation (shift / stretch / reflection) of a parent function, so learners must see past surface variation (high exemplar variability). - `conic_type` — ConicSense: see a general-form equation Ax² + Bxy + Cy² + Dx + Ey + F = 0 and name the conic. The key comes from the discriminant B² − 4AC (and A = C, B = 0 for circles), checked by sympy; degenerate draws are rejected. """ from __future__ import annotations import random import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import sympy as sp from PIL import Image X, Y = sp.symbols("x y", real=True) CATEGORIES = { "function_family": { "prompt": "Which function family does this graph belong to?", "choices": ["linear", "quadratic", "cubic", "exponential", "logarithmic", "rational", "sinusoidal"], "rt_threshold_s": 8.0, }, "conic_type": { "prompt": "This equation describes which conic section?", "choices": ["circle", "ellipse", "parabola", "hyperbola"], "rt_threshold_s": 15.0, # symbol → shape mapping is multi-representational }, } _FEEDBACK = { "linear": "Constant rate of change: a straight line with no curvature (§2.1–2.2).", "quadratic": "Symmetric U-shape with one vertex and one axis of symmetry (§3.2).", "cubic": "Ends go in opposite directions; can have a local max and min plus an inflection (§3.3–3.4).", "exponential": "Horizontal asymptote on one side, rapid growth/decay on the other; never crosses the asymptote (§4.2).", "logarithmic": "Vertical asymptote, slow unbounded growth — the reflection of an exponential over y = x (§4.4).", "rational": "Separate branches around a vertical asymptote, levelling off to a horizontal asymptote (§3.7).", "sinusoidal": "Repeating waves between a fixed max and min around a midline (§6.1).", "circle": "A = C and no xy-term: equal pull in x and y (§10.1).", "ellipse": "B² − 4AC < 0 with A ≠ C: both squared terms, same sign, different coefficients (§10.1).", "parabola": "B² − 4AC = 0: only one variable is squared (§10.3).", "hyperbola": "B² − 4AC > 0: squared terms with opposite signs (§10.2).", } def _parent(family: str, rng: random.Random): a = rng.choice([-1, 1]) * rng.choice([0.5, 1, 1.5, 2]) h, k = rng.randint(-2, 2), rng.randint(-2, 2) if family == "linear": return a * (X - h) + k if family == "quadratic": return a * (X - h) ** 2 / 2 + k if family == "cubic": r = rng.choice([0, 1, 2]) return a * (X - h) * ((X - h) ** 2 - r) / 3 + k if family == "exponential": b = rng.choice([sp.Rational(1, 2), 2, sp.E, 3]) return a * b ** (X - h) + k if family == "logarithmic": return a * sp.log(X - h) + k if family == "rational": return a / (X - h) + k if family == "sinusoidal": return a * sp.sin(rng.choice([1, 2, sp.pi / 2]) * (X - h)) + k raise ValueError(family) def _plot_function(expr) -> Image.Image: f = sp.lambdify(X, expr, "numpy") xs = np.linspace(-6, 6, 1200) with np.errstate(all="ignore"): ys = np.asarray(f(xs), dtype=complex) ys = np.where(np.abs(ys.imag) > 1e-9, np.nan, ys.real) ys[np.abs(ys) > 12] = np.nan # clip blow-ups so asymptotes show as gaps fig, ax = plt.subplots(figsize=(4.2, 4.2), dpi=110) ax.axhline(0, color="#888", lw=0.8) ax.axvline(0, color="#888", lw=0.8) ax.plot(xs, ys, lw=2.4, color="#1f5fbf") ax.set_xlim(-6, 6) ax.set_ylim(-8, 8) ax.grid(alpha=0.25) ax.set_xticks([]) ax.set_yticks([]) fig.tight_layout() fig.canvas.draw() img = Image.frombuffer("RGBA", fig.canvas.get_width_height(), fig.canvas.buffer_rgba()).convert("RGB") plt.close(fig) return img def _conic_key(A, B, C) -> str: disc = sp.nsimplify(B**2 - 4 * A * C) if disc < 0: return "circle" if (A == C and B == 0) else "ellipse" return "parabola" if disc == 0 else "hyperbola" def _conic_equation(target: str, rng: random.Random): for _ in range(500): A, C = rng.randint(-5, 5), rng.randint(-5, 5) if target == "circle": C = A = rng.choice([1, 2, 3, 4]) elif target == "parabola": A, C = (rng.choice([1, 2, 3, -1, -2]), 0) if rng.random() < 0.5 else (0, rng.choice([1, 2, 3, -1, -2])) B = 0 D, E, F = rng.randint(-8, 8), rng.randint(-8, 8), rng.randint(-12, 12) if A == 0 and C == 0: continue if _conic_key(A, B, C) != target: continue expr = A * X**2 + B * X * Y + C * Y**2 + D * X + E * Y + F # Reject degenerate conics (empty set / point / line pairs) by checking the curve has # real points and a non-zero 3x3 determinant. M = sp.Matrix([[A, sp.Rational(B, 2), sp.Rational(D, 2)], [sp.Rational(B, 2), C, sp.Rational(E, 2)], [sp.Rational(D, 2), sp.Rational(E, 2), F]]) if M.det() == 0: continue if target in ("circle", "ellipse"): # Completing the square: A(x+D/2A)² + C(y+E/2C)² = R. With AC > 0 the curve is # a real (non-empty, non-point) ellipse iff R has the same sign as A. R = sp.Rational(D**2, 4 * A) + sp.Rational(E**2, 4 * C) - F if R * A <= 0: continue return expr raise RuntimeError(f"could not draw a non-degenerate {target}") def _render_equation(expr) -> Image.Image: fig = plt.figure(figsize=(5.2, 1.4), dpi=110) fig.text(0.5, 0.5, f"${sp.latex(sp.Eq(sp.expand(expr), 0))}$", ha="center", va="center", fontsize=20) fig.canvas.draw() img = Image.frombuffer("RGBA", fig.canvas.get_width_height(), fig.canvas.buffer_rgba()).convert("RGB") plt.close(fig) return img def make_item(category: str, difficulty: int = 1, seed: int | None = None) -> dict: if category not in CATEGORIES: raise ValueError(f"unknown category {category!r}; expected one of {list(CATEGORIES)}") seed = seed if seed is not None else random.randrange(10**6) rng = random.Random(seed) spec = CATEGORIES[category] choices = list(spec["choices"]) target = rng.choice(choices) if category == "function_family": expr = _parent(target, rng) image = _plot_function(expr) method = f"constructed from the {target} parent function: y = {sp.sstr(expr)}" else: expr = _conic_equation(target, rng) A, C = expr.coeff(X, 2), expr.coeff(Y, 2) B = expr.coeff(X, 1).coeff(Y, 1) assert _conic_key(A, B, C) == target # oracle re-check on the final expression image = _render_equation(expr) method = f"discriminant B²−4AC = {sp.sstr(B**2 - 4 * A * C)} (sympy)" return { "id": f"precalc.{category}.{seed:06d}", "course": "PRECALC", "category": "GraphSense" if category == "function_family" else "ConicSense", "subcategory": category, "stimulus": {"image": image}, "prompt": spec["prompt"], "choices": choices, "correct": choices.index(target), "feedback": _FEEDBACK[target], "ground_truth_method": method, "difficulty": difficulty, "transfer": False, "provenance": {"generator": "src.generators.precalc", "seed": seed}, }