Skip to main content

logicaffeine_web/
grader.rs

1use logicaffeine_language::semantics::lookup_noun_hypernyms;
2
3#[derive(Debug, Clone)]
4pub struct GradeResult {
5    pub correct: bool,
6    pub partial: bool,
7    pub score: u32,
8    pub feedback: String,
9}
10
11impl GradeResult {
12    pub fn correct() -> Self {
13        Self {
14            correct: true,
15            partial: false,
16            score: 100,
17            feedback: "Correct!".to_string(),
18        }
19    }
20
21    pub fn partial(feedback: String, score: u32) -> Self {
22        Self {
23            correct: false,
24            partial: true,
25            score,
26            feedback,
27        }
28    }
29
30    pub fn incorrect(feedback: String) -> Self {
31        Self {
32            correct: false,
33            partial: false,
34            score: 0,
35            feedback,
36        }
37    }
38}
39
40pub fn check_answer(user_input: &str, expected: &str) -> GradeResult {
41    if normalize_logic(user_input) == normalize_logic(expected) {
42        return GradeResult::correct();
43    }
44
45    match (Formula::read(user_input), Formula::read(expected)) {
46        (Some(user), Some(expected)) => {
47            if user.same_as(&expected) {
48                return GradeResult::correct();
49            }
50
51            let similarity = user.similarity(&expected);
52            if similarity > 0.7 {
53                GradeResult::partial(
54                    "Close! Check your quantifier or connective structure.".to_string(),
55                    (similarity * 50.0) as u32,
56                )
57            } else if similarity > 0.4 {
58                GradeResult::partial(
59                    "Partially correct. Review the logical structure.".to_string(),
60                    (similarity * 30.0) as u32,
61                )
62            } else {
63                GradeResult::incorrect(
64                    "Not quite. Consider the relationship between subject and predicate."
65                        .to_string(),
66                )
67            }
68        }
69        (None, _) => {
70            GradeResult::incorrect("Could not parse your answer. Check syntax.".to_string())
71        }
72        (_, None) => {
73            GradeResult::incorrect("Internal error: could not parse expected answer.".to_string())
74        }
75    }
76}
77
78fn normalize_logic(input: &str) -> String {
79    symbolize(input)
80        .chars()
81        .filter(|c| !c.is_whitespace())
82        .collect()
83}
84
85/// The LaTeX and ASCII spellings a reader may type, as the symbols LOGOS prints.
86fn symbolize(input: &str) -> String {
87    let mut result = input.to_string();
88
89    result = result.replace("\\forall", "∀");
90    result = result.replace("\\exists", "∃");
91    result = result.replace("\\neg", "¬");
92    result = result.replace("\\land", "∧");
93    result = result.replace("\\lor", "∨");
94    result = result.replace("\\supset", "→");
95    result = result.replace("\\equiv", "↔");
96    result = result.replace("\\Box", "□");
97    result = result.replace("\\Diamond", "◇");
98
99    // Order matters: the longer arrows before the shorter, and `!=` before `!`
100    result = result.replace("<=>", "↔");
101    result = result.replace("<->", "↔");
102    result = result.replace("->", "→");
103    result = result.replace(">=", "≥");
104    result = result.replace("<=", "≤");
105    result = result.replace("!=", "≠");
106    result = result.replace("==", "=");
107    result = result.replace("&", "∧");
108    result = result.replace("|", "∨");
109    result = result.replace("~", "¬");
110    result = result.replace("!", "¬");
111
112    result
113}
114
115/// A formula as the grader compares it. [`Formula::read`] names each bound variable by how
116/// many binders enclose it, lower-cases free names, and flattens ∧ and ∨ into their operands,
117/// so formulas that differ only in a bound variable's name, a name's case, or the order and
118/// grouping of their conjuncts compare equal.
119#[derive(Debug, Clone)]
120enum Formula {
121    /// ∀, ∃, a counting quantifier (`∃=2`), a generalised one (`MOST`), or λ.
122    Quantifier {
123        kind: String,
124        var: String,
125        body: Box<Formula>,
126    },
127    /// ¬, or a modal (□, ◇); a modal's degree (`◇_{0.5}`) is not compared.
128    Unary { op: String, body: Box<Formula> },
129    /// →, ↔, or the counterfactual □→.
130    Binary {
131        op: String,
132        left: Box<Formula>,
133        right: Box<Formula>,
134    },
135    /// ∧ or ∨ over two or more operands, in any order.
136    Junction { op: String, items: Vec<Formula> },
137    /// A predicate, a relation, or an operator over formulas (`HAB(…)`) applied to its arguments.
138    Apply { name: String, args: Vec<Formula> },
139    /// A constant, or a variable bound above it.
140    Name(String),
141}
142
143/// The generalised quantifiers LOGOS prints as a word: `MOST x(…)`.
144const GENERALISED_QUANTIFIERS: [&str; 3] = ["MOST", "MANY", "FEW"];
145
146/// The deontic operators LOGOS prints before a formula: `O_{0.6} φ` for "should", `P_{0.5} φ` for
147/// "may". Read as the operator applied to φ, as `O(φ)` is.
148const DEONTIC_OPERATORS: [&str; 2] = ["O", "P"];
149
150impl Formula {
151    /// The formula `text` writes, or `None` when it is not one.
152    fn read(text: &str) -> Option<Formula> {
153        let mut parser = Parser {
154            tokens: tokens(&symbolize(text)),
155            at: 0,
156        };
157        let formula = parser.formula()?;
158        (parser.at == parser.tokens.len()).then(|| formula.canonical(&mut Vec::new()))
159    }
160
161    fn canonical(self, bound: &mut Vec<String>) -> Formula {
162        match self {
163            Formula::Quantifier { kind, var, body } => {
164                let level = format!("#{}", bound.len());
165                bound.push(var);
166                let body = body.canonical(bound);
167                bound.pop();
168                Formula::Quantifier {
169                    kind,
170                    var: level,
171                    body: Box::new(body),
172                }
173            }
174            Formula::Unary { op, body } => Formula::Unary {
175                op,
176                body: Box::new(body.canonical(bound)),
177            },
178            Formula::Binary { op, left, right } => Formula::Binary {
179                op,
180                left: Box::new(left.canonical(bound)),
181                right: Box::new(right.canonical(bound)),
182            },
183            Formula::Junction { op, items } => {
184                let mut flat = Vec::new();
185                for item in items {
186                    match item.canonical(bound) {
187                        Formula::Junction { op: inner, items } if inner == op => flat.extend(items),
188                        other => flat.push(other),
189                    }
190                }
191                if op == "∧" {
192                    flat = without_categories(flat);
193                }
194                if flat.len() == 1 {
195                    flat.remove(0)
196                } else {
197                    Formula::Junction { op, items: flat }
198                }
199            }
200            Formula::Apply { name, args } => Formula::Apply {
201                name,
202                args: args.into_iter().map(|arg| arg.canonical(bound)).collect(),
203            },
204            Formula::Name(name) => match bound.iter().rposition(|var| *var == name) {
205                Some(level) => Formula::Name(format!("#{level}")),
206                None => Formula::Name(name.to_lowercase()),
207            },
208        }
209    }
210
211    fn same_as(&self, other: &Formula) -> bool {
212        match (self, other) {
213            (
214                Formula::Quantifier {
215                    kind: k1,
216                    var: v1,
217                    body: b1,
218                },
219                Formula::Quantifier {
220                    kind: k2,
221                    var: v2,
222                    body: b2,
223                },
224            ) => k1 == k2 && v1 == v2 && b1.same_as(b2),
225            (Formula::Unary { op: o1, body: b1 }, Formula::Unary { op: o2, body: b2 }) => {
226                o1 == o2 && b1.same_as(b2)
227            }
228            (
229                Formula::Binary {
230                    op: o1,
231                    left: l1,
232                    right: r1,
233                },
234                Formula::Binary {
235                    op: o2,
236                    left: l2,
237                    right: r2,
238                },
239            ) => {
240                o1 == o2
241                    && ((l1.same_as(l2) && r1.same_as(r2))
242                        || (o1 == "↔" && l1.same_as(r2) && r1.same_as(l2)))
243            }
244            (Formula::Junction { op: o1, items: i1 }, Formula::Junction { op: o2, items: i2 }) => {
245                o1 == o2
246                    && i1.len() == i2.len()
247                    && max_matching(i1, i2, |a, b| a.same_as(b)) == i1.len()
248            }
249            (Formula::Apply { name: n1, args: a1 }, Formula::Apply { name: n2, args: a2 }) => {
250                n1 == n2 && a1.len() == a2.len() && a1.iter().zip(a2).all(|(x, y)| x.same_as(y))
251            }
252            (Formula::Name(a), Formula::Name(b)) => a == b,
253            _ => false,
254        }
255    }
256
257    /// How alike two formulas are, from 0 to 1, for partial credit.
258    fn similarity(&self, other: &Formula) -> f64 {
259        match (self, other) {
260            (
261                Formula::Quantifier {
262                    kind: k1, body: b1, ..
263                },
264                Formula::Quantifier {
265                    kind: k2, body: b2, ..
266                },
267            ) => {
268                let kind_match = if k1 == k2 { 0.4 } else { 0.0 };
269                kind_match + b1.similarity(b2) * 0.6
270            }
271            (Formula::Unary { op: o1, body: b1 }, Formula::Unary { op: o2, body: b2 }) => {
272                let op_match = if o1 == o2 { 0.3 } else { 0.0 };
273                op_match + b1.similarity(b2) * 0.7
274            }
275            (Formula::Apply { name: n1, args: a1 }, Formula::Apply { name: n2, args: a2 }) => {
276                let name_match = if n1 == n2 { 0.7 } else { 0.0 };
277                let arity_match = if a1.len() == a2.len() { 0.3 } else { 0.0 };
278                name_match + arity_match
279            }
280            (Formula::Name(a), Formula::Name(b)) => {
281                if a == b {
282                    1.0
283                } else {
284                    0.0
285                }
286            }
287            _ => match (self.connective(), other.connective()) {
288                (Some((o1, c1)), Some((o2, c2))) => {
289                    let op_match = if o1 == o2 { 0.3 } else { 0.0 };
290                    let unordered = matches!(self, Formula::Junction { .. })
291                        && matches!(other, Formula::Junction { .. });
292                    let total: f64 = if unordered {
293                        c1.iter()
294                            .map(|a| c2.iter().map(|b| a.similarity(b)).fold(0.0, f64::max))
295                            .sum()
296                    } else {
297                        c1.iter().zip(&c2).map(|(a, b)| a.similarity(b)).sum()
298                    };
299                    op_match + total / c1.len().max(c2.len()) as f64 * 0.7
300                }
301                _ => 0.0,
302            },
303        }
304    }
305
306    /// A binary connective or a junction, as its operator and operands.
307    fn connective(&self) -> Option<(&str, Vec<&Formula>)> {
308        match self {
309            Formula::Binary { op, left, right } => Some((op, vec![left.as_ref(), right.as_ref()])),
310            Formula::Junction { op, items } => Some((op, items.iter().collect())),
311            _ => None,
312        }
313    }
314}
315
316/// The conjuncts without the dictionary categories of their siblings: beside `Bird(x)`,
317/// `Animal(x)` says nothing more, because the dictionary makes every bird an animal. LOGOS
318/// writes the categories out; a textbook answer leaves them implicit; both say the same.
319fn without_categories(items: Vec<Formula>) -> Vec<Formula> {
320    let names_a_category = |item: &Formula| {
321        let Formula::Apply { name, args } = item else {
322            return false;
323        };
324        items.iter().any(|noun| match noun {
325            Formula::Apply {
326                name: noun_name,
327                args: noun_args,
328            } => {
329                noun_name != name
330                    && noun_args.len() == args.len()
331                    && noun_args.iter().zip(args).all(|(a, b)| a.same_as(b))
332                    && lookup_noun_hypernyms(noun_name)
333                        .iter()
334                        .any(|category| category.eq_ignore_ascii_case(name))
335            }
336            _ => false,
337        })
338    };
339    let keep: Vec<bool> = items.iter().map(|item| !names_a_category(item)).collect();
340    items
341        .into_iter()
342        .zip(keep)
343        .filter_map(|(item, keep)| keep.then_some(item))
344        .collect()
345}
346
347#[derive(Debug, Clone, PartialEq)]
348enum Token {
349    /// ∀ or ∃, with its count when it has one (`∃=2`, `∃≥3`).
350    Quantifier(String),
351    Word(String),
352    Symbol(char),
353}
354
355fn tokens(text: &str) -> Vec<Token> {
356    let chars: Vec<char> = text.chars().collect();
357    let word_char = |c: char| c.is_alphanumeric() || matches!(c, '_' | '\'' | '-');
358    let mut out = Vec::new();
359    let mut i = 0;
360    while i < chars.len() {
361        let c = chars[i];
362        if c.is_whitespace() {
363            i += 1;
364        } else if c == '∀' || c == '∃' {
365            let mut kind = c.to_string();
366            i += 1;
367            if let Some(&bound) = chars.get(i).filter(|b| matches!(b, '=' | '≥' | '≤')) {
368                let digits: String = chars[i + 1..]
369                    .iter()
370                    .take_while(|d| d.is_ascii_digit())
371                    .collect();
372                if !digits.is_empty() {
373                    kind.push(bound);
374                    kind.push_str(&digits);
375                    i += 1 + digits.len();
376                }
377            }
378            out.push(Token::Quantifier(kind));
379        } else if c == '□' || c == '◇' {
380            out.push(Token::Symbol(c));
381            i += 1;
382            if chars.get(i) == Some(&'_') {
383                i += 1;
384                if chars.get(i) == Some(&'{') {
385                    while i < chars.len() && chars[i] != '}' {
386                        i += 1;
387                    }
388                    i += 1;
389                } else {
390                    while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '.') {
391                        i += 1;
392                    }
393                }
394            }
395        } else if word_char(c) {
396            let start = i;
397            while i < chars.len() {
398                let decimal_point = chars[i] == '.'
399                    && chars[i - 1].is_ascii_digit()
400                    && chars.get(i + 1).is_some_and(|d| d.is_ascii_digit());
401                if !(word_char(chars[i]) || decimal_point) {
402                    break;
403                }
404                i += 1;
405            }
406            let word: String = chars[start..i].iter().collect();
407            // A deontic operator's strength (`O_{0.6}`) is not compared, as a modal's is not.
408            if let Some(operator) = word
409                .strip_suffix('_')
410                .filter(|w| DEONTIC_OPERATORS.contains(w))
411            {
412                if chars.get(i) == Some(&'{') {
413                    while i < chars.len() && chars[i] != '}' {
414                        i += 1;
415                    }
416                    i += 1;
417                    out.push(Token::Word(operator.to_string()));
418                    continue;
419                }
420            }
421            out.push(Token::Word(word));
422        } else {
423            out.push(Token::Symbol(c));
424            i += 1;
425        }
426    }
427    out
428}
429
430/// Recursive descent over the notation LOGOS prints, loosest-binding first:
431/// ↔, then → (right-associative, with □→), then ∨, then ∧, then ¬, modals and binders.
432struct Parser {
433    tokens: Vec<Token>,
434    at: usize,
435}
436
437impl Parser {
438    fn peek(&self, ahead: usize) -> Option<&Token> {
439        self.tokens.get(self.at + ahead)
440    }
441
442    fn eat(&mut self, symbol: char) -> bool {
443        let found = self.peek(0) == Some(&Token::Symbol(symbol));
444        if found {
445            self.at += 1;
446        }
447        found
448    }
449
450    fn formula(&mut self) -> Option<Formula> {
451        let mut left = self.implication()?;
452        while self.eat('↔') {
453            let right = self.implication()?;
454            left = Formula::Binary {
455                op: "↔".to_string(),
456                left: Box::new(left),
457                right: Box::new(right),
458            };
459        }
460        Some(left)
461    }
462
463    fn implication(&mut self) -> Option<Formula> {
464        let left = self.junction('∨')?;
465        let op = if self.eat('→') {
466            "→"
467        } else if self.peek(0) == Some(&Token::Symbol('□'))
468            && self.peek(1) == Some(&Token::Symbol('→'))
469        {
470            self.at += 2;
471            "□→"
472        } else {
473            return Some(left);
474        };
475        let right = self.implication()?;
476        Some(Formula::Binary {
477            op: op.to_string(),
478            left: Box::new(left),
479            right: Box::new(right),
480        })
481    }
482
483    fn junction(&mut self, op: char) -> Option<Formula> {
484        let operand = |parser: &mut Parser| {
485            if op == '∨' {
486                parser.junction('∧')
487            } else {
488                parser.unary()
489            }
490        };
491        let mut items = vec![operand(self)?];
492        while self.eat(op) {
493            items.push(operand(self)?);
494        }
495        Some(if items.len() == 1 {
496            items.remove(0)
497        } else {
498            Formula::Junction {
499                op: op.to_string(),
500                items,
501            }
502        })
503    }
504
505    fn unary(&mut self) -> Option<Formula> {
506        match self.peek(0)?.clone() {
507            Token::Symbol(op @ ('¬' | '□' | '◇')) => {
508                self.at += 1;
509                Some(Formula::Unary {
510                    op: op.to_string(),
511                    body: Box::new(self.unary()?),
512                })
513            }
514            Token::Quantifier(kind) => {
515                self.at += 1;
516                self.binder(kind)
517            }
518            Token::Symbol('λ') => {
519                self.at += 1;
520                self.binder("λ".to_string())
521            }
522            Token::Word(word)
523                if GENERALISED_QUANTIFIERS.contains(&word.as_str())
524                    && matches!(self.peek(1), Some(Token::Word(_)))
525                    && self.peek(2) == Some(&Token::Symbol('(')) =>
526            {
527                self.at += 1;
528                self.binder(word)
529            }
530            Token::Symbol('(') => {
531                self.at += 1;
532                let inner = self.formula()?;
533                self.eat(')').then_some(inner)
534            }
535            Token::Word(word)
536                if DEONTIC_OPERATORS.contains(&word.as_str()) && self.starts_formula(1) =>
537            {
538                self.at += 1;
539                let body = self.unary()?;
540                Some(Formula::Apply {
541                    name: word,
542                    args: vec![body],
543                })
544            }
545            Token::Word(_) => self.atom(),
546            _ => None,
547        }
548    }
549
550    /// Whether the token `ahead` places on starts a formula an operator can govern: a binder, a
551    /// negation or modal, or a predicate applied to arguments. A parenthesis does not count: `O(φ)`
552    /// is read as an application, which comes to the same thing.
553    fn starts_formula(&self, ahead: usize) -> bool {
554        match self.peek(ahead) {
555            Some(Token::Quantifier(_)) | Some(Token::Symbol('¬' | '□' | '◇' | 'λ')) => true,
556            Some(Token::Word(word)) => {
557                DEONTIC_OPERATORS.contains(&word.as_str())
558                    || self.peek(ahead + 1) == Some(&Token::Symbol('('))
559            }
560            _ => false,
561        }
562    }
563
564    /// A binder's variable, then its scope: the parenthesised group right after it, or else
565    /// everything to its right (`∀x. φ`, `∀x φ`, `λx.φ`).
566    fn binder(&mut self, kind: String) -> Option<Formula> {
567        self.eat('.');
568        let Some(Token::Word(var)) = self.peek(0).cloned() else {
569            return None;
570        };
571        self.at += 1;
572        let dotted = self.eat('.');
573        let body = if !dotted && self.peek(0) == Some(&Token::Symbol('(')) {
574            self.unary()?
575        } else {
576            self.formula()?
577        };
578        Some(Formula::Quantifier {
579            kind,
580            var,
581            body: Box::new(body),
582        })
583    }
584
585    /// A name or an application, and the relation it stands in when one follows (`x = y`).
586    fn atom(&mut self) -> Option<Formula> {
587        let Some(Token::Word(name)) = self.peek(0).cloned() else {
588            return None;
589        };
590        self.at += 1;
591        let term = if self.eat('(') {
592            let mut args = Vec::new();
593            if !self.eat(')') {
594                loop {
595                    args.push(self.formula()?);
596                    if self.eat(')') {
597                        break;
598                    }
599                    if !self.eat(',') {
600                        return None;
601                    }
602                }
603            }
604            Formula::Apply { name, args }
605        } else {
606            Formula::Name(name)
607        };
608        for relation in ['=', '≠', '≥', '≤', '<', '>'] {
609            if self.eat(relation) {
610                let right = self.atom()?;
611                return Some(Formula::Apply {
612                    name: relation.to_string(),
613                    args: vec![term, right],
614                });
615            }
616        }
617        Some(term)
618    }
619}
620
621/// How a set of answers covers a sentence's readings.
622#[derive(Debug, Clone, PartialEq, Eq)]
623pub struct ReadingsGrade {
624    /// Readings matched by a distinct answer.
625    pub matched: usize,
626    /// Readings the sentence has.
627    pub total: usize,
628}
629
630impl ReadingsGrade {
631    /// Every reading given, each by its own answer. A sentence with no readings is never correct.
632    pub fn all_correct(&self) -> bool {
633        self.total > 0 && self.matched == self.total
634    }
635}
636
637/// Grade an ambiguous sentence: every reading must be given by a different answer, in any order.
638/// Each answer is graded against each reading exactly as a translation is ([`check_answer`]).
639pub fn check_readings(answers: &[String], readings: &[String]) -> ReadingsGrade {
640    let matched = match_readings(answers, readings, |answer, reading| {
641        !answer.trim().is_empty() && check_answer(answer, reading).correct
642    });
643    ReadingsGrade {
644        matched,
645        total: readings.len(),
646    }
647}
648
649/// The largest set of (answer, reading) pairs where each answer and each reading is used at
650/// most once and every pair `fits` — a maximum bipartite matching by augmenting paths, so an
651/// answer that fits several readings never strands another answer that fits only one.
652fn match_readings(
653    answers: &[String],
654    readings: &[String],
655    fits: impl Fn(&str, &str) -> bool,
656) -> usize {
657    max_matching(answers, readings, |answer, reading| fits(answer, reading))
658}
659
660/// The largest set of (left, right) pairs where each side is used at most once and every pair
661/// `fits`, found by augmenting paths.
662fn max_matching<L, R>(left: &[L], right: &[R], fits: impl Fn(&L, &R) -> bool) -> usize {
663    let edges: Vec<Vec<usize>> = left
664        .iter()
665        .map(|l| (0..right.len()).filter(|&r| fits(l, &right[r])).collect())
666        .collect();
667    let mut owner: Vec<Option<usize>> = vec![None; right.len()];
668
669    fn augment(
670        a: usize,
671        edges: &[Vec<usize>],
672        owner: &mut [Option<usize>],
673        seen: &mut [bool],
674    ) -> bool {
675        for &r in &edges[a] {
676            if seen[r] {
677                continue;
678            }
679            seen[r] = true;
680            if owner[r].map_or(true, |b| augment(b, edges, owner, seen)) {
681                owner[r] = Some(a);
682                return true;
683            }
684        }
685        false
686    }
687
688    (0..left.len())
689        .filter(|&a| augment(a, &edges, &mut owner, &mut vec![false; right.len()]))
690        .count()
691}
692
693#[cfg(test)]
694#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_web/grader/tests.rs"]
695mod tests;