diff --git a/src/analysis/diagnostic.rs b/src/analysis/diagnostic.rs index 1453999..69508f6 100644 --- a/src/analysis/diagnostic.rs +++ b/src/analysis/diagnostic.rs @@ -181,6 +181,10 @@ pub struct StudentDiagnostic { /// One row per question, with no question in it. #[serde(skip_serializing_if = "Vec::is_empty")] pub questions: Vec, + /// Registry mistakes behind more than one missed question, so the report + /// can group those misses under the one thing to fix. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub mistakes: Vec, /// Questions thrown out, in number order. /// /// Reported separately from the question rows so the document can say once, @@ -337,6 +341,41 @@ pub struct Measured { pub objective: Option, /// The target the question was written against. pub target: String, + /// The target's explanation, with references rendered as words: what + /// meeting it looks like, which is what to practise towards. + #[serde(skip_serializing_if = "Option::is_none")] + pub explanation: Option, +} + +/// A named mistake behind a student's answer, from the course's misconception +/// registry. Student-facing: the belief and its correction are written for the +/// student. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "kebab-case")] +pub struct Mistake { + /// The misconception id. + pub id: String, + /// The wrong idea as a student holds it. Absent when the chosen option + /// carries its own misconception text, which overrides the registry's for + /// that item and already reaches the student as feedback. + #[serde(skip_serializing_if = "Option::is_none")] + pub belief: Option, + /// Why it fails and what is true instead. + pub correction: String, +} + +/// A mistake that more than one missed question drew on. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "kebab-case")] +pub struct MistakeGroup { + /// The misconception id. + pub id: String, + /// The registry's belief. + pub belief: String, + /// The registry's correction. + pub correction: String, + /// The questions, by recorded number. + pub questions: Vec, } /// One question, described without being reproduced. @@ -397,6 +436,10 @@ pub struct QuestionRow { /// The worked solution, when [`Options::solutions`] is on. #[serde(skip_serializing_if = "Option::is_none")] pub worked: Option, + /// The registry misconception the chosen option encodes, with its + /// correction, when [`Options::feedback`] is on. + #[serde(skip_serializing_if = "Option::is_none")] + pub mistake: Option, /// Where the material was taught. #[serde(skip_serializing_if = "Vec::is_empty")] pub taught_in: Vec, @@ -678,6 +721,7 @@ pub fn student( objectives, strengths, focus, + mistakes: shared_mistakes(&questions, course), questions, dropped_questions, review_lectures, @@ -706,6 +750,7 @@ fn question_row( let mut hint = None; let mut misconception = None; let mut worked = None; + let mut mistake = None; let mut taught_in = Vec::new(); let mut review = Vec::new(); @@ -714,6 +759,20 @@ fn question_row( if missed { if let Some(letter) = row.chosen().first() { if let Some(choice) = entry.item.option(letter) { + if opts.feedback { + let course = &catalog.course; + mistake = choice.misconception_id.as_deref().and_then(|id| { + let registered = course.misconceptions.get(id)?; + Some(Mistake { + id: id.to_string(), + belief: choice + .misconception + .is_none() + .then(|| course.plain_refs(®istered.belief)), + correction: course.plain_refs(®istered.correction), + }) + }); + } if opts.feedback { // `student_text` falls back to `explanation`, which is // written for a grader and often names the right @@ -783,6 +842,11 @@ fn question_row( // objective is left out. objective: (objective != id).then(|| course.text_for(objective)), target: course.text_for(id), + explanation: course + .learning_targets + .get(id) + .and_then(|t| t.explanation.as_deref()) + .map(|e| course.plain_refs(e)), } }) .collect() @@ -804,11 +868,47 @@ fn question_row( hint, misconception, worked, + mistake, taught_in, review, } } +/// The registry mistakes that more than one of a student's missed questions +/// drew on, so a report can name the thing to fix once. +/// +/// # Arguments +/// +/// * `questions` - the student's question rows. +/// * `course` - the course, for the registry's wording. +/// +/// # Returns +/// +/// One group per shared misconception, in order of its first question. +pub fn shared_mistakes(questions: &[QuestionRow], course: &CourseFile) -> Vec { + let mut groups: Vec = Vec::new(); + for q in questions { + let Some(mistake) = &q.mistake else { + continue; + }; + if let Some(group) = groups.iter_mut().find(|g| g.id == mistake.id) { + group.questions.push(q.number); + continue; + } + let Some(entry) = course.misconceptions.get(&mistake.id) else { + continue; + }; + groups.push(MistakeGroup { + id: mistake.id.clone(), + belief: course.plain_refs(&entry.belief), + correction: course.plain_refs(&entry.correction), + questions: vec![q.number], + }); + } + groups.retain(|g| g.questions.len() > 1); + groups +} + /// Resolves an item's `review` citations against the course reference registry. /// /// # Arguments @@ -2565,6 +2665,7 @@ mod tests { strengths: Vec::new(), focus: Vec::new(), questions: Vec::new(), + mistakes: Vec::new(), dropped_questions: Vec::new(), review_lectures: Vec::new(), study: Vec::new(), diff --git a/src/analysis/students.rs b/src/analysis/students.rs index 9f96cb5..00a1eed 100644 --- a/src/analysis/students.rs +++ b/src/analysis/students.rs @@ -184,6 +184,9 @@ pub struct MissedItem { pub learning_targets: Vec, /// The misconception the chosen distractor was written to detect. pub misconception: Option, + /// The registry misconception the chosen distractor encodes, when it names + /// one. Misses that share it are grouped in the report. + pub misconception_id: Option, /// Feedback written for a student who chose that option. pub feedback: Option, /// Where to go back to: lecture titles and slide numbers. @@ -675,6 +678,7 @@ fn missed_items( continue; } let mut misconception = None; + let mut misconception_id = None; let mut feedback = None; let mut study = Vec::new(); @@ -685,6 +689,7 @@ fn missed_items( if let Some(letter) = r.chosen().first() { if let Some(choice) = entry.item.option(letter) { misconception = choice.misconception.clone(); + misconception_id = choice.misconception_id.clone(); feedback = choice.student_text().map(|s| s.to_string()); } } @@ -716,6 +721,7 @@ fn missed_items( level: r.level, learning_targets: r.learning_targets.clone(), misconception, + misconception_id, feedback, study, }); diff --git a/src/cli.rs b/src/cli.rs index 60354d5..bd0f2f5 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -327,6 +327,37 @@ pub(crate) enum LectureCommand { #[arg(long)] out: Option, }, + /// Write the whole page for one lecture. + /// + /// Its description; each objective with its targets, their ceilings, and + /// their explanations; the terms new here and those from earlier lectures; + /// the equations, numbers, and common mistakes its targets turn on; the + /// readings with their times; and the materials. Only student-facing + /// fields are read. + Page { + /// Lecture id, e.g. L1.1. + id: String, + /// Which flavour of Markdown to write. + #[arg(long, value_enum, default_value = "quarto")] + style: StyleArg, + /// Where the course glossary page lives, for links to entries this page + /// does not define. + #[arg(long, default_value = coursebank::lecture::DEFAULT_GLOSSARY_HREF)] + glossary_href: String, + /// Output path; prints to stdout when omitted. + #[arg(long)] + out: Option, + }, + /// Write the course glossary page: every term, equation, and value, with + /// the lecture that introduces it. + Glossary { + /// Which flavour of Markdown to write. + #[arg(long, value_enum, default_value = "quarto")] + style: StyleArg, + /// Output path; prints to stdout when omitted. + #[arg(long)] + out: Option, + }, /// Show the readings behind each learning target, and which have none. Coverage { /// Only this lecture's targets. diff --git a/src/commands/lectures.rs b/src/commands/lectures.rs index c4bbfe7..c35407a 100644 --- a/src/commands/lectures.rs +++ b/src/commands/lectures.rs @@ -10,7 +10,9 @@ use coursebank::course::CourseFile; use coursebank::error::Result; -use coursebank::lecture::{objectives_markdown, readings_markdown}; +use coursebank::lecture::{ + PageOptions, glossary_markdown, objectives_markdown, page_markdown, readings_markdown, +}; use coursebank::yaml; use crate::cli::{Cli, LectureCommand}; @@ -29,6 +31,25 @@ pub(crate) fn lecture(cli: &Cli, sub: &LectureCommand) -> Result { objectives_markdown(&course, id, style.as_style())?, out.as_deref(), ), + LectureCommand::Page { + id, + style, + glossary_href, + out, + } => { + let options = PageOptions { + style: style.as_style(), + glossary_href: glossary_href.clone(), + }; + emit(page_markdown(&course, id, &options)?, out.as_deref()) + } + LectureCommand::Glossary { style, out } => { + let options = PageOptions { + style: style.as_style(), + ..PageOptions::default() + }; + emit(glossary_markdown(&course, &options), out.as_deref()) + } LectureCommand::Coverage { lecture: only } => coverage(&course, only.as_deref(), cli.quiet), } } diff --git a/src/export/lecture.rs b/src/export/lecture.rs index 6d7446d..4170942 100644 --- a/src/export/lecture.rs +++ b/src/export/lecture.rs @@ -20,7 +20,26 @@ //! What this module does not do is invent prose. Everything printed comes from //! `summary`, `focus`, and `skip` on the reading, in that order, and a reading with //! none of the three renders as a bare citation. +//! +//! # The lecture page and the glossary page +//! +//! Since 2.1 a lecture is more than its objectives and readings, and +//! [`page_markdown`] renders all of it, in the order the specification gives: +//! the lecture's description; each objective with its description and its +//! targets (by ceiling, each labelled with the course's own level name and +//! followed by its explanation); the terms new in this lecture, then the ones +//! from earlier lectures; the equations its targets turn on; the numbers to +//! know; the common mistakes; the readings, with minutes; and the materials. +//! [`glossary_markdown`] renders the course glossary page that every term on a +//! lecture page links to. +//! +//! Both pages are student pages, so they read only student-facing fields. A +//! target's `authoring`, an entry's `notes_private`, `status`, a value's +//! `conflicts`, and a misconception's `evidence` are never touched here. +use std::collections::BTreeSet; + +use crate::course::glossary::{RefKind, TermKind}; use crate::course::{CourseFile, Reading, ReadingRole, Reference}; use crate::error::{Error, Result}; use crate::taxonomy::Level; @@ -331,9 +350,10 @@ fn entry( .into_iter() .flatten() .map(|prose| { - course.expand_objective_refs(prose, |id| match number(id) { - Some(n) => format!("T {n}"), - None => course.text_for(id), + course.expand_refs(prose, |id| { + reference_markdown(course, id, number, &|id| { + format!("{DEFAULT_GLOSSARY_HREF}#{}", anchor(id)) + }) }) }) .collect(); @@ -388,6 +408,637 @@ fn heading(reading: &Reading, key: &str, reference: &Reference, style: Style) -> } } +/// Where a term or equation link points when no other page is named: the +/// course glossary page, as [`glossary_markdown`] writes it and a Quarto site +/// renders it. +pub const DEFAULT_GLOSSARY_HREF: &str = "glossary.html"; + +/// How to render a lecture page or the glossary page. +#[derive(Debug, Clone)] +pub struct PageOptions { + /// Which flavour of Markdown to emit. Quarto gives each glossary entry an + /// anchor and links to it on the same page when it is there; Plain links + /// every entry to the glossary page. + pub style: Style, + /// The course glossary page, which entries not on this page link to. + pub glossary_href: String, +} + +impl Default for PageOptions { + fn default() -> PageOptions { + PageOptions { + style: Style::Quarto, + glossary_href: DEFAULT_GLOSSARY_HREF.to_string(), + } + } +} + +/// The HTML anchor of a glossary entry. +/// +/// Prefixed, because Quarto reserves `eq-` (and `fig-`, `tbl-`, `sec-`) for its +/// own cross-references and would claim an equation's id. +/// +/// # Arguments +/// +/// * `id` - the entry id. +/// +/// # Returns +/// +/// The anchor, without `#`. +pub fn anchor(id: &str) -> String { + format!("glossary-{id}") +} + +/// One brace reference as Markdown, following the specification's table: a +/// term as its name linked to its entry, an equation as its name linked to its +/// display, a value as its `say`, a misconception as its belief in quotation +/// marks, and a target or objective as its number on the page (`T 4`), or its +/// text when it is not numbered here. +/// +/// # Arguments +/// +/// * `course` - the course. +/// * `id` - the referenced id. +/// * `number` - a target's position on this page, if it has one. +/// * `href` - where a term or equation link points. +/// +/// # Returns +/// +/// The Markdown. +fn reference_markdown( + course: &CourseFile, + id: &str, + number: &impl Fn(&str) -> Option, + href: &dyn Fn(&str) -> String, +) -> String { + match RefKind::of(id) { + Some(RefKind::Term | RefKind::Equation) if course.resolves(id) => { + format!("[{}]({})", course.ref_words(id), href(id)) + } + Some(RefKind::Value | RefKind::Misconception) if course.resolves(id) => { + course.ref_words(id) + } + _ => match number(id) { + Some(n) => format!("T {n}"), + None => course.text_for(id), + }, + } +} + +/// What one page needs to render prose: target numbers, and which glossary +/// entries have an anchor on it. +struct Page<'a> { + course: &'a CourseFile, + options: &'a PageOptions, + numbers: Vec, + anchored: BTreeSet, +} + +impl Page<'_> { + /// A target's position on the page. + fn number(&self, id: &str) -> Option { + self.numbers.iter().position(|o| o == id).map(|i| i + 1) + } + + /// Where a link to a glossary entry points from this page. + fn href(&self, id: &str) -> String { + if self.options.style == Style::Quarto && self.anchored.contains(id) { + format!("#{}", anchor(id)) + } else { + format!("{}#{}", self.options.glossary_href, anchor(id)) + } + } + + /// Student-facing prose, with references rendered and whitespace runs + /// collapsed, since YAML folding leaves them behind. + fn prose(&self, text: &str) -> String { + let collapsed = text.split_whitespace().collect::>().join(" "); + self.course.expand_refs(&collapsed, |id| { + reference_markdown(self.course, id, &|t| self.number(t), &|e| self.href(e)) + }) + } + + /// A LaTeX fragment as inline math, or as written in the Plain style. + fn math(&self, tex: &str) -> String { + match self.options.style { + Style::Quarto => format!("${}$", tex.trim()), + Style::Plain => tex.trim().to_string(), + } + } + + /// A bolded glossary label, with an anchor in the Quarto style. + fn label(&self, id: &str, text: &str) -> String { + match self.options.style { + Style::Quarto => format!("[**{text}**]{{#{}}}", anchor(id)), + Style::Plain => format!("**{text}**"), + } + } +} + +/// The glossary entries a lecture's targets list, each kind in the order its +/// targets first list them. +#[derive(Debug, Default)] +struct Needs { + terms: Vec, + equations: Vec, + values: Vec, + misconceptions: Vec, +} + +impl Needs { + /// Collects from targets in page order. + fn of(course: &CourseFile, targets: &[&str]) -> Needs { + let mut needs = Needs::default(); + for id in targets { + let Some(target) = course.learning_targets.get(*id) else { + continue; + }; + for (into, from) in [ + (&mut needs.terms, &target.terms), + (&mut needs.equations, &target.equations), + (&mut needs.values, &target.values), + (&mut needs.misconceptions, &target.misconceptions), + ] { + for x in from { + if !into.contains(x) { + into.push(x.clone()); + } + } + } + } + needs + } +} + +/// Renders the whole page for one lecture: what the lecture is, what it asks of +/// a student, and everything they study from. +/// +/// # Arguments +/// +/// * `course` - the loaded course file. +/// * `lecture` - the lecture id. +/// * `options` - the Markdown flavour and the glossary page's address. +/// +/// # Returns +/// +/// The Markdown, ending in a newline. A section with nothing in it is left +/// out. +/// +/// # Errors +/// +/// Returns [`Error::Unresolved`] when the lecture id, or a reference a reading +/// cites, is not registered. +pub fn page_markdown(course: &CourseFile, lecture: &str, options: &PageOptions) -> Result { + let lec = course.lecture(lecture, "lecture page")?; + let numbers = numbered_targets(course, lecture); + let ordered: Vec<&str> = numbers + .iter() + .filter(|id| course.is_target(id)) + .map(String::as_str) + .collect(); + let needs = Needs::of(course, &ordered); + let (new_terms, earlier_terms): (Vec<&String>, Vec<&String>) = needs + .terms + .iter() + .filter(|id| course.terms.contains_key(*id)) + .partition(|id| course.first_lecture(id) == Some(lecture)); + + let anchored: BTreeSet = new_terms + .iter() + .map(|id| id.to_string()) + .chain(needs.equations.iter().cloned()) + .collect(); + let page = Page { + course, + options, + numbers, + anchored, + }; + + let mut out = format!("# {lecture}: {}\n\n", lec.title); + if let Some(description) = &lec.description { + out.push_str(&format!("{}\n\n", page.prose(description))); + } + out.push_str(&objectives_section(&page, lecture)); + out.push_str(&terms_section(&page, &new_terms, &earlier_terms)); + out.push_str(&equations_section(&page, &needs.equations)); + out.push_str(&values_section(&page, &needs.values)); + out.push_str(&mistakes_section(&page, &needs.misconceptions)); + out.push_str(&page_readings_section(&page, lec.readings.as_slice())?); + out.push_str(&materials_section(&page, lec)); + Ok(format!("{}\n", out.trim_end())) +} + +/// One target or untiered objective, as a list item with its level label and +/// explanation. +fn target_item(page: &Page<'_>, id: &str) -> String { + let course = page.course; + let text = page.prose(&course.text_for(id)); + let level = course + .effective_level_ceiling(id) + .map(|l| format!(" ({})", course.policy.level_name(l))) + .unwrap_or_default(); + let explanation = course + .learning_targets + .get(id) + .and_then(|t| t.explanation.as_deref()) + .map(|e| page.prose(e)); + match page.options.style { + Style::Quarto => { + let mut item = format!("(@) **{text}**{level}\n"); + if let Some(e) = explanation { + item.push_str(&format!("\n {e}\n\n")); + } + item + } + Style::Plain => { + let mut item = format!("- **{text}**{level}\n"); + if let Some(e) = explanation { + item.push_str(&format!(" {e}\n")); + } + item + } + } +} + +/// Each objective with its description and its targets. +fn objectives_section(page: &Page<'_>, lecture: &str) -> String { + let course = page.course; + let mut out = String::new(); + if !is_tiered(course, lecture) { + // Every entry is an objective standing as its own target, so the + // objectives are the list, in the numbering the readings point at. + out.push_str("## Objectives\n\n"); + for id in &page.numbers { + out.push_str(&target_item(page, id)); + } + out.push('\n'); + return out; + } + let (groups, leftovers) = target_layout(course, lecture); + for (objective, targets) in groups { + out.push_str(&format!( + "## {}\n\n", + page.prose(&course.text_for(objective)) + )); + if let Some(description) = course + .learning_objectives + .get(objective) + .and_then(|o| o.description.as_deref()) + { + out.push_str(&format!("{}\n\n", page.prose(description))); + } + for target in targets { + out.push_str(&target_item(page, target)); + } + out.push('\n'); + } + if !leftovers.is_empty() { + out.push_str("## Also covered\n\n"); + for id in leftovers { + out.push_str(&target_item(page, id)); + } + out.push('\n'); + } + out +} + +/// The terms new in this lecture, then those introduced earlier. +fn terms_section(page: &Page<'_>, new: &[&String], earlier: &[&String]) -> String { + let course = page.course; + let mut out = String::new(); + if !new.is_empty() { + out.push_str("## New terms\n\n"); + for id in new { + let term = &course.terms[id.as_str()]; + let symbol = term + .symbol + .as_deref() + .map(|s| format!(" {}", s.trim())) + .unwrap_or_default(); + // The textbook name matters for a renamed or coined term, which a + // student cannot otherwise look up; for a standard one it repeats + // the term. + let textbook = if matches!(term.kind, TermKind::Renamed | TermKind::Coined) + && !term.textbook.is_empty() + { + let names: Vec<&str> = term.textbook.iter().map(|t| t.term.as_str()).collect(); + format!(" (textbooks: {})", names.join("; ")) + } else { + String::new() + }; + out.push_str(&format!( + "- {}{symbol}: {}{textbook}\n", + page.label(id, &term.term), + page.prose(&term.definition) + )); + } + out.push('\n'); + } + if !earlier.is_empty() { + if new.is_empty() { + out.push_str("## Terms\n\n"); + } + let listed: Vec = earlier + .iter() + .map(|id| { + let first = course.first_lecture(id).unwrap_or("?"); + format!( + "[{}]({}) ({first})", + course.terms[id.as_str()].term, + page.href(id) + ) + }) + .collect(); + out.push_str(&format!( + "Terms from earlier lectures: {}\n\n", + listed.join(", ") + )); + } + out +} + +/// The equations the lecture's targets turn on, each in full. +fn equations_section(page: &Page<'_>, ids: &[String]) -> String { + let course = page.course; + let present: Vec<&String> = ids + .iter() + .filter(|id| course.equations.contains_key(*id)) + .collect(); + if present.is_empty() { + return String::new(); + } + let mut out = String::from("## Equations\n\n"); + for id in present { + let eq = &course.equations[id.as_str()]; + match page.options.style { + Style::Quarto => { + out.push_str(&format!("### {} {{#{}}}\n\n", eq.name, anchor(id))); + } + Style::Plain => out.push_str(&format!("### {}\n\n", eq.name)), + } + out.push_str(&format!("$${}$$\n\n", eq.tex.trim())); + out.push_str(&format!("{}\n\n", page.prose(&eq.says))); + let mut lines = Vec::new(); + for symbol in &eq.symbols { + let term = symbol.term.as_deref().and_then(|t| course.terms.get(t)); + let meaning = term + .map(|t| t.term.clone()) + .or_else(|| symbol.meaning.as_deref().map(|m| page.prose(m))) + .unwrap_or_default(); + let units = symbol + .units + .as_deref() + .or_else(|| term.and_then(|t| t.units.as_deref())) + .map(|u| format!(" ({u})")) + .unwrap_or_default(); + lines.push(format!("{}: {meaning}{units}", page.math(&symbol.symbol))); + } + for implication in &eq.implications { + lines.push(format!( + "What it tells you ({}): {}", + implication.form.label(), + page.prose(&implication.statement) + )); + } + for a in &eq.assumes { + lines.push(format!("Assumes: {}", page.prose(a))); + } + for a in &eq.fails_when { + lines.push(format!("Fails when: {}", page.prose(a))); + } + for line in lines { + out.push_str(&format!("- {line}\n")); + } + out.push('\n'); + } + out +} + +/// The numbers the lecture's targets use, in their one approved wording. +fn values_section(page: &Page<'_>, ids: &[String]) -> String { + let course = page.course; + let present: Vec<&String> = ids + .iter() + .filter(|id| course.values.contains_key(*id)) + .collect(); + if present.is_empty() { + return String::new(); + } + let mut out = String::from("## Numbers to know\n\n"); + for id in present { + let value = &course.values[id.as_str()]; + let recall = if value.recall == Some(true) { + " (know this one)" + } else { + "" + }; + out.push_str(&format!("- {}: {}{recall}\n", value.name, value.say)); + } + out.push('\n'); + out +} + +/// The mistakes the lecture's targets draw on, each with its correction. +fn mistakes_section(page: &Page<'_>, ids: &[String]) -> String { + let course = page.course; + let present: Vec<&String> = ids + .iter() + .filter(|id| course.misconceptions.contains_key(*id)) + .collect(); + if present.is_empty() { + return String::new(); + } + let mut out = String::from("## Common mistakes\n\n"); + for id in present { + let m = &course.misconceptions[id.as_str()]; + out.push_str(&format!( + "- *{}* {}\n", + page.prose(&m.belief), + page.prose(&m.correction) + )); + } + out.push('\n'); + out +} + +/// The readings, each with its reading time, and what to take from it. +fn page_readings_section(page: &Page<'_>, readings: &[Reading]) -> Result { + if readings.is_empty() { + return Ok(String::new()); + } + let course = page.course; + let mut out = String::from("## Readings\n\n"); + let minutes: u32 = readings + .iter() + .filter(|r| r.role == ReadingRole::Assigned) + .filter_map(|r| r.minutes) + .sum(); + if minutes > 0 { + out.push_str(&format!("About {minutes} minutes of assigned reading.\n\n")); + } + for role in [ReadingRole::Assigned, ReadingRole::Supplemental] { + let group: Vec<&Reading> = readings.iter().filter(|r| r.role == role).collect(); + if group.is_empty() { + continue; + } + if role == ReadingRole::Supplemental { + out.push_str("\n### Supplemental\n\n"); + } + for reading in group { + let Some(key) = reading.reference.as_deref() else { + if let Some(text) = &reading.text { + out.push_str(&format!("- {text}\n")); + } + continue; + }; + let reference = course.reference(key, "lecture page")?; + let label = reference.label_or(key); + let locator = reading.locator.as_deref().unwrap_or(""); + let place = match (page.options.style, reading.resolve_url(reference)) { + (Style::Quarto, Some(url)) if !locator.is_empty() => format!("[{locator}]({url})"), + (Style::Quarto, Some(url)) => format!("[{}]({url})", reference.title), + _ if !locator.is_empty() => locator.to_string(), + _ => reference.title.clone(), + }; + let time = reading + .minutes + .map(|m| format!(" ({m} min)")) + .unwrap_or_default(); + let focus = reading + .focus + .as_deref() + .map(|f| format!(": {}", page.prose(f))) + .unwrap_or_default(); + out.push_str(&format!("- {label} {place}{time}{focus}\n")); + for extra in [&reading.summary, &reading.skip].into_iter().flatten() { + out.push_str(&format!(" {}\n", page.prose(extra))); + } + } + } + out.push('\n'); + Ok(out) +} + +/// The lecture's links: its materials, and the older `slides_url` when no +/// material is the slides. +fn materials_section(page: &Page<'_>, lecture: &crate::course::Lecture) -> String { + let mut links: Vec<(String, String)> = lecture + .materials + .iter() + .map(|m| (m.label().to_string(), m.url.clone())) + .collect(); + let has_slides = lecture + .materials + .iter() + .any(|m| m.kind == crate::course::glossary::MaterialKind::Slides); + if let (Some(url), false) = (&lecture.slides_url, has_slides) { + links.insert(0, ("slides".to_string(), url.clone())); + } + if links.is_empty() { + return String::new(); + } + let mut out = String::from("## Materials\n\n"); + for (title, url) in links { + match page.options.style { + Style::Quarto => out.push_str(&format!("- [{title}]({url})\n")), + Style::Plain => out.push_str(&format!("- {title}: {url}\n")), + } + } + out +} + +/// Renders the course glossary page: every term alphabetically with its +/// definition and the lecture that introduces it, then every equation and every +/// value with theirs. +/// +/// # Arguments +/// +/// * `course` - the loaded course file. +/// * `options` - the Markdown flavour. Links between entries stay on this +/// page. +/// +/// # Returns +/// +/// The Markdown, ending in a newline. +pub fn glossary_markdown(course: &CourseFile, options: &PageOptions) -> String { + let options = PageOptions { + glossary_href: String::new(), + ..options.clone() + }; + let page = Page { + course, + options: &options, + numbers: Vec::new(), + anchored: course + .terms + .keys() + .chain(course.equations.keys()) + .cloned() + .collect(), + }; + let first = |id: &str| match course.first_lecture(id) { + Some(lecture) => { + let title = course + .lectures + .get(lecture) + .map(|l| format!(": {}", l.title)) + .unwrap_or_default(); + format!(" *First in {lecture}{title}.*") + } + None => String::new(), + }; + + let mut out = String::from("# Glossary\n\n"); + if !course.terms.is_empty() { + out.push_str("## Terms\n\n"); + let mut terms: Vec<(&String, &crate::course::glossary::Term)> = + course.terms.iter().collect(); + terms.sort_by_key(|(id, t)| (t.term.to_lowercase(), (*id).clone())); + for (id, term) in terms { + let symbol = term + .symbol + .as_deref() + .map(|s| format!(" {}", s.trim())) + .unwrap_or_default(); + out.push_str(&format!( + "- {}{symbol}: {}{}\n", + page.label(id, &term.term), + page.prose(&term.definition), + first(id) + )); + } + out.push('\n'); + } + if !course.equations.is_empty() { + out.push_str("## Equations\n\n"); + let mut equations: Vec<_> = course.equations.iter().collect(); + equations.sort_by_key(|(id, e)| (e.name.to_lowercase(), (*id).clone())); + for (id, eq) in equations { + match options.style { + Style::Quarto => out.push_str(&format!("### {} {{#{}}}\n\n", eq.name, anchor(id))), + Style::Plain => out.push_str(&format!("### {}\n\n", eq.name)), + } + out.push_str(&format!( + "$${}$$\n\n{}{}\n\n", + eq.tex.trim(), + page.prose(&eq.says), + first(id) + )); + } + } + if !course.values.is_empty() { + out.push_str("## Numbers\n\n"); + let mut values: Vec<_> = course.values.iter().collect(); + values.sort_by_key(|(id, v)| (v.name.to_lowercase(), (*id).clone())); + for (id, value) in values { + out.push_str(&format!("- {}: {}{}\n", value.name, value.say, first(id))); + } + out.push('\n'); + } + format!("{}\n", out.trim_end()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/export/report.rs b/src/export/report.rs index 674a1c9..3aca027 100644 --- a/src/export/report.rs +++ b/src/export/report.rs @@ -336,7 +336,26 @@ pub fn student( course.text_for(objective) )); } + // What meeting the target looks like, which is what to + // practise towards. + if let Some(explanation) = course + .learning_targets + .get(target) + .and_then(|t| t.explanation.as_deref()) + { + out.push_str(&format!( + "What meeting it looks like: {}\n\n", + course.plain_refs(explanation) + )); + } } + // A named registry misconception carries a student-facing belief + // and correction. The option's own text, when it has one, wins for + // the belief, and keeps the sentence it has always had. + let registry = m + .misconception_id + .as_deref() + .and_then(|id| course.misconceptions.get(id)); if let Some(text) = &m.feedback { out.push_str(&format!("{text}\n\n")); } else if let Some(misconception) = &m.misconception { @@ -344,10 +363,38 @@ pub fn student( "The option you chose is the one students pick when {misconception}\n\n" )); } + if let Some(entry) = registry { + if m.misconception.is_none() { + out.push_str(&format!( + "This answer reflects a common mistake: *{}*\n\n", + course.plain_refs(&entry.belief) + )); + } + out.push_str(&format!("{}\n\n", course.plain_refs(&entry.correction))); + } if !m.study.is_empty() { out.push_str(&format!("Review: {}\n\n", m.study.join("; "))); } } + + // The same mistake behind more than one answer is worth more than any + // one question: it is the thing to fix once. + let groups = shared_mistakes(&summary.missed); + if !groups.is_empty() { + out.push_str("## The same mistake, more than once\n\n"); + for (id, numbers) in groups { + let Some(entry) = course.misconceptions.get(id) else { + continue; + }; + let numbers: Vec = numbers.iter().map(u32::to_string).collect(); + out.push_str(&format!( + "**Questions {}**: *{}*\n\n{}\n\n", + numbers.join(", "), + course.plain_refs(&entry.belief), + course.plain_refs(&entry.correction) + )); + } + } } if let Some(closing) = &opts.closing { @@ -366,6 +413,31 @@ pub fn student( out } +/// Registry misconceptions that more than one missed question drew on. +/// +/// # Arguments +/// +/// * `missed` - a student's missed items. +/// +/// # Returns +/// +/// Each shared misconception id with the question numbers, in order of the +/// first question that drew it. +pub fn shared_mistakes(missed: &[crate::students::MissedItem]) -> Vec<(&str, Vec)> { + let mut groups: Vec<(&str, Vec)> = Vec::new(); + for m in missed { + let Some(id) = m.misconception_id.as_deref() else { + continue; + }; + match groups.iter_mut().find(|(g, _)| *g == id) { + Some((_, numbers)) => numbers.push(m.number), + None => groups.push((id, vec![m.number])), + } + } + groups.retain(|(_, numbers)| numbers.len() > 1); + groups +} + /// Writes the instructor's report on one administration. /// /// # Arguments diff --git a/src/export/typst/diagnostic.rs b/src/export/typst/diagnostic.rs index 412bdf7..09a43f3 100644 --- a/src/export/typst/diagnostic.rs +++ b/src/export/typst/diagnostic.rs @@ -368,6 +368,12 @@ pub fn student_value(diagnostic: &StudentDiagnostic, config: &RenderConfig) -> V .map(|text| markup_value(text, content)), ); pair.insert("target", markup_value(&m.target, content)); + pair.insert_some( + "explanation", + m.explanation + .as_ref() + .map(|text| markup_value(text, content)), + ); pair }) .collect(), @@ -381,6 +387,22 @@ pub fn student_value(diagnostic: &StudentDiagnostic, config: &RenderConfig) -> V ] { value.insert_some(key, text.map(|t| markup_value(t, content))); } + value.insert_some( + "mistake", + question.mistake.as_ref().map(|mistake| { + let mut entry = Value::dict(); + entry.insert("id", Value::str(&mistake.id)); + entry.insert_some( + "belief", + mistake + .belief + .as_ref() + .map(|text| markup_value(text, content)), + ); + entry.insert("correction", markup_value(&mistake.correction, content)); + entry + }), + ); value.insert( "taught-in", Value::Array(question.taught_in.iter().map(Value::str).collect()), @@ -410,6 +432,33 @@ pub fn student_value(diagnostic: &StudentDiagnostic, config: &RenderConfig) -> V ), ); + out.insert( + "mistakes", + Value::Array( + diagnostic + .mistakes + .iter() + .map(|group| { + let mut entry = Value::dict(); + entry.insert("id", Value::str(&group.id)); + entry.insert("belief", markup_value(&group.belief, content)); + entry.insert("correction", markup_value(&group.correction, content)); + entry.insert( + "questions", + Value::Array( + group + .questions + .iter() + .map(|n| Value::Int(*n as i64)) + .collect(), + ), + ); + entry + }) + .collect(), + ), + ); + let dropped_questions = if config.student_sections.dropped_questions { diagnostic.dropped_questions.as_slice() } else { diff --git a/src/export/typst/templates/student-report.typ b/src/export/typst/templates/student-report.typ index 27f3758..fe98f0c 100644 --- a/src/export/typst/templates/student-report.typ +++ b/src/export/typst/templates/student-report.typ @@ -146,6 +146,7 @@ ( objective: [A sample objective to work on.], target: [A sample learning target under it.], + explanation: [What a student who has met the target could say about it.], ), ), correct: false, @@ -155,9 +156,28 @@ class-rate: 0.58, feedback: [This is the note written for the option that was chosen.], hint: [This is the question you would ask someone reconsidering that option.], + mistake: ( + id: "mis-sample", + belief: [A wrong idea, as a student would hold it.], + correction: [Why it fails, and what is true instead.], + ), taught-in: ("Enthalpy (L1.1), slides 12, 13",), review: ((citation: "KKW §6.2", title: "Molecules and Medicine", url: "https://example.edu/6/2"),), ), + ( + number: 14, + level: 2, + targets: ("t-sample-gap",), + measured: ((target: [A sample learning target under it.],),), + correct: false, + credit: 0.0, + bonus: false, + blank: false, + class-rate: 0.61, + mistake: (id: "mis-sample", correction: [Why it fails, and what is true instead.]), + taught-in: (), + review: (), + ), ( number: 37, level: 1, @@ -183,6 +203,14 @@ review: (), ), ), + mistakes: ( + ( + id: "mis-sample", + belief: [A wrong idea, as a student would hold it.], + correction: [Why it fails, and what is true instead.], + questions: (2, 14), + ), + ), dropped-questions: ((number: 35, full-credit: true),), review-lectures: ( ( @@ -960,17 +988,24 @@ let target = [ #text(weight: "bold")[This question asked you to:] #markup(m.target) ] - if objective == none { + // What meeting the target looks like: the account to practise + // towards, from the target's own explanation. + let explanation = m.at("explanation", default: none) + let lines = (target,) + if explanation != none { + lines.push(text(size: size-small)[ + #text(weight: "bold")[What meeting it looks like:] #markup(explanation) + ]) + } + if objective != none { + lines.push(text(size: size-small, fill: luma(110))[ + Counts toward: #markup(objective) + ]) + } + if lines.len() == 1 { target } else { - stack( - dir: ttb, - spacing: step * 0.3, - target, - text(size: size-small, fill: luma(110))[ - Counts toward: #markup(objective) - ], - ) + stack(dir: ttb, spacing: step * 0.3, ..lines) } }), ) @@ -982,6 +1017,18 @@ let feedback = q.at("feedback", default: none) if feedback != none { parts.push(markup(feedback)) } + // A named mistake from the course's registry, written for the student: the + // belief (absent when the option's own text already said it) and why it + // fails. + let mistake = q.at("mistake", default: none) + if mistake != none { + let belief = mistake.at("belief", default: none) + parts.push(callout("A common mistake", { + if belief != none [#emph(markup(belief)) ] + markup(mistake.correction) + })) + } + let hint = q.at("hint", default: none) if hint != none { parts.push(callout("Try this", markup(hint))) } @@ -1045,7 +1092,9 @@ q.at("feedback", default: none) != none or q.at("hint", default: none) != none or q.at("worked", default: none) != none + or q.at("mistake", default: none) != none or q.at("review", default: ()).len() > 0 + or q.at("measured", default: ()).any(m => m.at("explanation", default: none) != none) ) )) @@ -1063,6 +1112,24 @@ ] ] +// The same registry mistake behind more than one missed question: the thing +// to fix once, with the questions it cost. +#let mistakes = cb-data.at("mistakes", default: ()) +#if show-feedback and mistakes.len() > 0 [ + = The same mistake, more than once + + #for group in mistakes [ + #block(breakable: false, above: entry-gap, width: 100%)[ + #pad(right: prose-pad-inset)[#stack( + dir: ttb, + spacing: step, + [#text(weight: "bold")[Questions #group.questions.map(str).join(", "):] #emph(markup(group.belief))], + markup(group.correction), + )] + ] + ] +] + // ───────────────────────────────────────────────────────────────────────────── // Footer note // ───────────────────────────────────────────────────────────────────────────── diff --git a/src/model/course/glossary.rs b/src/model/course/glossary.rs index d27b535..223ba24 100644 --- a/src/model/course/glossary.rs +++ b/src/model/course/glossary.rs @@ -818,6 +818,91 @@ impl super::CourseFile { out } + /// Replaces each brace reference in prose with whatever the caller renders + /// for it. + /// + /// A reference is a brace pair around a declared id: a prefixed glossary + /// id (`{term-...}`, `{eq-...}`, `{val-...}`, `{mis-...}`) or any declared + /// objective or target id, which is the 2.0 rule and keeps unprefixed + /// target ids working. Anything else, `$U_\text{final}$` or `10^{59}` + /// included, passes through untouched. + /// + /// # Arguments + /// + /// * `prose` - the field to expand. + /// * `render` - called with each referenced id. + /// + /// # Returns + /// + /// The prose with references replaced. + pub fn expand_refs(&self, prose: &str, render: impl Fn(&str) -> String) -> String { + let mut out = String::with_capacity(prose.len()); + let mut rest = prose; + while let Some(open) = rest.find('{') { + let (head, tail) = rest.split_at(open); + out.push_str(head); + let Some(close) = tail.find('}') else { + out.push_str(tail); + return out; + }; + let name = &tail[1..close]; + if self.resolves(name) + || self.learning_objectives.contains_key(name) + || self.learning_targets.contains_key(name) + { + out.push_str(&render(name)); + } else { + out.push_str(&tail[..=close]); + } + rest = &tail[close + 1..]; + } + out.push_str(rest); + out + } + + /// Prose with every reference rendered as plain words, for a report or a + /// terminal: a term as its name, an equation as its name, a value as its + /// `say`, a misconception as its belief in quotation marks, and an + /// objective or target as its text. + /// + /// # Arguments + /// + /// * `prose` - the field to expand. + /// + /// # Returns + /// + /// The prose, with whitespace runs collapsed to single spaces. + pub fn plain_refs(&self, prose: &str) -> String { + let collapsed = prose.split_whitespace().collect::>().join(" "); + self.expand_refs(&collapsed, |id| self.ref_words(id)) + } + + /// The words a reference stands for, as [`plain_refs`](Self::plain_refs) + /// prints them. + /// + /// # Arguments + /// + /// * `id` - a declared id of any registry. + /// + /// # Returns + /// + /// The words. + pub fn ref_words(&self, id: &str) -> String { + if let Some(t) = self.terms.get(id) { + return t.term.clone(); + } + if let Some(e) = self.equations.get(id) { + return e.name.clone(); + } + if let Some(v) = self.values.get(id) { + return v.say.clone(); + } + if let Some(m) = self.misconceptions.get(id) { + return format!("\u{201c}{}\u{201d}", m.belief.trim()); + } + self.text_for(id) + } + /// A lecture's targets in teaching order: its objectives in the order the /// lecture page prints them, each objective's targets by ceiling and then /// id, and then any target the lecture covers whose objective it does not diff --git a/tests/render_2_1.rs b/tests/render_2_1.rs new file mode 100644 index 0000000..dcd712c --- /dev/null +++ b/tests/render_2_1.rs @@ -0,0 +1,516 @@ +// SPDX-License-Identifier: Prosperity-3.0.0 +// Copyright Scienting +// Source: https://git.scient.ing/education/coursebank + +//! What 2.1 renders: the lecture page, the glossary page, and the student +//! reports, and what it must never render for a student. + +mod common; + +use std::path::Path; + +use common::{design, v21_course}; +use coursebank::assessment::{AssessmentFile, Form}; +use coursebank::catalog::Catalog; +use coursebank::lecture::{PageOptions, Style, glossary_markdown, page_markdown}; +use coursebank::responses::{Response, ResponseSet}; +use coursebank::typst::config::{RenderConfig, Variant}; + +/// The example lecture page in the Plain style, which is the style the +/// preview was written in. +fn plain_page(catalog: &Catalog) -> String { + let options = PageOptions { + style: Style::Plain, + ..PageOptions::default() + }; + page_markdown(&catalog.course, "l09", &options).expect("renders") +} + +/// A page line with its link targets removed: `[gap](glossary.html#x)` +/// becomes `[gap]`, which is how the prototype's preview writes a link. +fn unlinked(line: &str) -> String { + let mut out = String::new(); + let mut rest = line; + while let Some(at) = rest.find("](") { + out.push_str(&rest[..=at]); + let after = &rest[at + 2..]; + match after.find(')') { + Some(close) => rest = &after[close + 1..], + None => { + rest = after; + break; + } + } + } + out.push_str(rest); + out +} + +#[test] +fn the_lecture_page_has_the_content_and_order_of_the_preview() { + let catalog = Catalog::load(&v21_course("page-snapshot")).unwrap(); + let rendered: Vec = plain_page(&catalog) + .lines() + .map(unlinked) + .filter(|l| !l.trim().is_empty()) + .collect(); + + let preview_text = + std::fs::read_to_string(design().join("examples/v21/lecture-page-preview.md")).unwrap(); + // The prototype prints a target reference as the raw id; coursebank prints + // its number on the page, as the 2.0 readings page always has. + let preview_text = preview_text.replace("(T t-align-fill-matrix)", "(T 3)"); + let preview: Vec<&str> = preview_text + .lines() + .filter(|l| !l.trim().is_empty() && !l.starts_with("