/**
* Mathematical Logic Explanation Generator
* Generates detailed explanations for mathematical logic proofs
* Part of simplified Phase 4d Implementation
*/
import {
SolutionStep
} from '../types.js';
import {
ProofContext
} from '../types-explanations.js';
import { BaseExplanationGenerator } from './BaseExplanationGenerator.js';
/**
* Explanation generator for mathematical logic.
*/
export class MathematicalExplanationGenerator extends BaseExplanationGenerator {
// Map of mathematical operations to their explanations
private readonly operationExplanations: Record<string, string> = {
'Pattern Recognition': 'Pattern Recognition identifies the underlying pattern in a sequence of numbers or elements.',
'Sequence Prediction': 'Sequence Prediction uses the identified pattern to determine the next element(s) in the sequence.',
'Equation Solving': 'Equation Solving uses algebraic manipulations to find the value of unknown variables.',
'System Solving': 'System Solving handles multiple equations with multiple unknowns simultaneously.',
'Inequality Solving': 'Inequality Solving finds the range of values that satisfy an inequality constraint.',
'Expression Simplification': 'Expression Simplification reduces a mathematical expression to its simplest form.',
'Arithmetic Sequence': 'An Arithmetic Sequence has a constant difference between consecutive terms.',
'Geometric Sequence': 'A Geometric Sequence has a constant ratio between consecutive terms.',
'Fibonacci Sequence': 'A Fibonacci Sequence is where each number is the sum of the two preceding ones.',
'Quadratic Sequence': 'A Quadratic Sequence has second differences that are constant.',
'Algebraic Manipulation': 'Algebraic Manipulation applies standard algebraic rules to transform expressions.',
'Substitution': 'Substitution replaces variables with their known values or expressions.',
'Factorization': 'Factorization breaks down an expression into a product of simpler expressions.',
'Distribution': 'Distribution applies the distributive property of multiplication over addition.',
'Formula Application': 'Formula Application uses established mathematical formulas to solve problems.',
'Term Combination': 'Term Combination simplifies expressions by collecting like terms.'
};
// Mathematical symbols and their explanations
private readonly symbolExplanations: Record<string, string> = {
'+': 'Addition operator.',
'-': 'Subtraction operator or negative sign.',
'*': 'Multiplication operator.',
'/': 'Division operator.',
'=': 'Equality, indicating that the expressions on both sides have the same value.',
'≠': 'Inequality, indicating that the expressions on both sides have different values.',
'<': 'Less than, indicating that the left expression is less than the right expression.',
'>': 'Greater than, indicating that the left expression is greater than the right expression.',
'≤': 'Less than or equal to.',
'≥': 'Greater than or equal to.',
'(': 'Opening parenthesis, used to group sub-expressions.',
')': 'Closing parenthesis, used to group sub-expressions.',
'√': 'Square root operation.',
'^': 'Exponentiation operator.',
'∑': 'Summation, the sum of a set of terms.',
'∏': 'Product, the product of a set of terms.',
'Δ': 'Difference, often used to represent change in a value.',
'…': 'Ellipsis, indicating a pattern that continues in the same manner.'
};
// Common sequence patterns and their explanations
private readonly patternExplanations: Record<string, string> = {
'arithmetic': 'An arithmetic sequence has a constant difference (d) between consecutive terms: a_n = a_1 + (n-1)d.',
'geometric': 'A geometric sequence has a constant ratio (r) between consecutive terms: a_n = a_1 * r^(n-1).',
'fibonacci': 'A Fibonacci sequence has each term equal to the sum of the two preceding ones: a_n = a_(n-1) + a_(n-2).',
'quadratic': 'A quadratic sequence has a constant second difference, following the pattern a_n = an² + bn + c.',
'cubic': 'A cubic sequence has a constant third difference, following the pattern a_n = an³ + bn² + cn + d.',
'exponential': 'An exponential sequence follows the pattern a_n = a * b^n, where b is the base.',
'alternating': 'An alternating sequence switches between different patterns, often between positive and negative values.'
};
// Common algebraic rules and their explanations
private readonly algebraicRules: Record<string, string> = {
'commutative': 'The commutative property states that a + b = b + a and a * b = b * a.',
'associative': 'The associative property states that (a + b) + c = a + (b + c) and (a * b) * c = a * (b * c).',
'distributive': 'The distributive property states that a * (b + c) = a * b + a * c.',
'identity': 'The identity properties state that a + 0 = a and a * 1 = a.',
'inverse': 'The inverse properties state that a + (-a) = 0 and a * (1/a) = 1 (for a ≠ 0).',
'exponent': 'Exponent rules include a^m * a^n = a^(m+n) and (a^m)^n = a^(m*n).'
};
protected getLogicSystemName(): string {
return 'mathematical logic';
}
protected getRuleExplanations(): Record<string, string> {
return this.operationExplanations;
}
protected getSymbolExplanations(): Record<string, string> {
return this.symbolExplanations;
}
protected getSpecificExplanation(step: SolutionStep, context: ProofContext): string {
// Extract explanation based on the rule type
if (step.rule.includes('Sequence') || step.rule.includes('Pattern')) {
return this.getSequenceExplanation(step, context);
}
if (step.rule.includes('Equation') || step.rule.includes('Solving')) {
return this.getEquationExplanation(step, context);
}
if (step.rule.includes('Simplification') || step.rule.includes('Manipulation')) {
return this.getSimplificationExplanation(step, context);
}
// Default explanation
return `This step applies ${step.rule} to progress toward the solution.`;
}
protected generateSystemSpecificVisualization(step: SolutionStep, context: ProofContext): string {
// Based on the rule, generate different visualizations
if (step.rule.includes('Sequence')) {
return this.generateSequenceVisualization(step, context);
}
if (step.rule.includes('Equation') || step.rule.includes('Solving')) {
return this.generateEquationVisualization(step, context);
}
if (step.rule.includes('Simplification')) {
return this.generateExpressionVisualization(step, context);
}
// Default to a formula visualization
return this.generateFormulaVisualization(step, context);
}
protected getRuleExample(rule: string): string {
switch (rule) {
case 'Equation Solving':
return "Example:\nProblem: Solve 2x + 5 = 13\nStep 1: Subtract 5 from both sides: 2x = 8\nStep 2: Divide both sides by 2: x = 4\n\n";
case 'Pattern Recognition':
case 'Sequence Prediction':
return "Example:\nSequence: 2, 4, 6, 8, ...\nPattern: Each term is 2 more than the previous term (arithmetic sequence with d = 2)\nNext term prediction: 8 + 2 = 10\n\n";
case 'Arithmetic Sequence':
return "Example:\nSequence: 3, 7, 11, 15, ...\nFirst term (a₁) = 3\nCommon difference (d) = 4\nGeneral formula: aₙ = 3 + (n-1)4 = 3 + 4n - 4 = 4n - 1\nTo find the 10th term: a₁₀ = 4(10) - 1 = 39\n\n";
case 'Geometric Sequence':
return "Example:\nSequence: 2, 6, 18, 54, ...\nFirst term (a₁) = 2\nCommon ratio (r) = 3\nGeneral formula: aₙ = 2 * 3^(n-1)\nTo find the 5th term: a₅ = 2 * 3^4 = 2 * 81 = 162\n\n";
case 'Fibonacci Sequence':
return "Example:\nSequence: 1, 1, 2, 3, 5, 8, 13, ...\nEach term is the sum of the two preceding terms\nTo find the next term: 8 + 13 = 21\n\n";
case 'System Solving':
return "Example:\nSystem: x + y = 5, 2x - y = 1\nFrom the first equation: y = 5 - x\nSubstitute into the second equation: 2x - (5 - x) = 1\nSolve: 2x - 5 + x = 1, 3x = 6, x = 2\nThen y = 5 - 2 = 3\nSolution: x = 2, y = 3\n\n";
case 'Inequality Solving':
return "Example:\nInequality: 2x + 3 > 7\nSubtract 3 from both sides: 2x > 4\nDivide both sides by 2: x > 2\nSolution: x > 2\n\n";
case 'Expression Simplification':
return "Example:\nExpression: 3x + 4 + 2x - 7\nCombine like terms: 5x - 3\n\n";
default:
return "";
}
}
protected assessRuleDifficulty(rule: string): number {
// Basic operations
if (rule === 'Pattern Recognition' || rule === 'Arithmetic Sequence') {
return 1;
}
// Assess based on specific operations
switch (rule) {
case 'Geometric Sequence':
case 'Equation Solving':
return 2;
case 'Fibonacci Sequence':
case 'System Solving':
case 'Quadratic Sequence':
case 'Expression Simplification':
return 3;
case 'Inequality Solving':
return 4;
default:
// Default moderate difficulty
return 2;
}
}
protected getSystemSpecificDetails(step: SolutionStep, context: ProofContext): string {
let details = '';
// Get pattern explanation if relevant
details += this.getPatternExplanation(step.statement, step.rule);
// Get algebraic rule explanation if relevant
details += this.getAlgebraicRuleExplanation(step);
// Add step-by-step calculation breakdown
details += `\n\n${this.getCalculationBreakdown(step, context)}`;
return details;
}
protected generateProofStrategy(steps: SolutionStep[], context: ProofContext): string {
// Look for patterns in the steps to determine the strategy
const rules = steps.map(step => step.rule);
if (rules.some(r => r.includes('Sequence') || r.includes('Pattern'))) {
return 'This solution applies pattern recognition techniques to identify the underlying rule in a sequence. It analyzes the relationships between consecutive terms to determine the general formula and predict additional terms.';
}
if (rules.some(r => r.includes('Equation') || r.includes('Solving'))) {
return 'This solution uses algebraic techniques to solve equations. It systematically isolates the variable of interest through a series of equivalent transformations that maintain the equality relationship.';
}
if (rules.some(r => r.includes('System'))) {
return 'This solution tackles a system of equations by using methods such as substitution, elimination, or matrices. It finds values for multiple variables that simultaneously satisfy all equations in the system.';
}
if (rules.some(r => r.includes('Simplification'))) {
return 'This solution simplifies a mathematical expression by applying algebraic properties and rules. It transforms the expression into an equivalent but more concise or useful form.';
}
// Default strategy description
return 'This solution applies mathematical reasoning and operations to solve the problem systematically, breaking it down into manageable steps.';
}
protected generateKeyInsights(steps: SolutionStep[], context: ProofContext): string[] {
const insights: string[] = [];
// Add general insight about mathematical logic
insights.push(
"Mathematical logic combines formal logical reasoning with mathematical operations to solve problems and analyze patterns."
);
// Add insights based on the types of operations used
if (steps.some(step => step.rule.includes('Sequence') || step.rule.includes('Pattern'))) {
insights.push(
"Pattern recognition is a powerful problem-solving strategy that involves identifying regularities and relationships within a set of values."
);
}
if (steps.some(step => step.rule.includes('Equation') || step.rule.includes('Solving'))) {
insights.push(
"Equation solving relies on the principle that performing the same operation on both sides of an equation maintains the equality relationship."
);
}
if (steps.some(step => step.rule.includes('Simplification'))) {
insights.push(
"Expression simplification involves transforming complex expressions into equivalent but more manageable forms by applying algebraic properties."
);
}
if (steps.some(step => step.rule.includes('System'))) {
insights.push(
"Systems of equations represent interconnected relationships between variables, requiring sophisticated techniques to find solutions that satisfy all constraints simultaneously."
);
}
return insights;
}
protected generateAlternativeApproaches(steps: SolutionStep[], context: ProofContext): string[] {
const alternatives: string[] = [];
// Add alternative approaches based on the types of operations used
if (steps.some(step => step.rule.includes('Sequence') || step.rule.includes('Pattern'))) {
alternatives.push(
"Recursive Formula Approach: Instead of deriving a closed-form formula, one could define the sequence recursively, expressing each term as a function of previous terms."
);
alternatives.push(
"Difference Method: For complex sequences, analyzing successive differences between consecutive terms can reveal underlying patterns."
);
}
if (steps.some(step => step.rule.includes('Equation') || step.rule.includes('Solving'))) {
alternatives.push(
"Graphical Method: Instead of algebraic manipulation, one could use graphical representations to visualize the solution, particularly useful for inequalities or systems of equations."
);
alternatives.push(
"Numerical Approximation: For complex equations without exact solutions, numerical methods like the Newton-Raphson method could be used to approximate the solution."
);
}
if (steps.some(step => step.rule.includes('System'))) {
alternatives.push(
"Matrix Method: Systems of equations can be solved using matrix algebra, particularly Gaussian elimination or Cramer's rule."
);
alternatives.push(
"Substitution Method: Instead of elimination, one could solve for one variable in terms of others and substitute into the remaining equations."
);
}
if (steps.some(step => step.rule.includes('Simplification'))) {
alternatives.push(
"Different Factorization Approach: There are often multiple ways to factor an expression, each leading to different but equivalent forms."
);
alternatives.push(
"Completing the Square: For quadratic expressions, completing the square can provide an alternative to direct factorization."
);
}
return alternatives;
}
/**
* Get explanation for sequence operations.
* @param step The solution step
* @param context The proof context
* @returns Explanation of the sequence operation
*/
private getSequenceExplanation(step: SolutionStep, context: ProofContext): string {
// Extract the sequence from the statement if possible
const sequenceMatch = step.statement.match(/\[([\d\s,\.]+)\]/);
if (!sequenceMatch) {
return `This step analyzes the sequence pattern and applies ${step.rule}.`;
}
const sequence = sequenceMatch[1].split(/[,\s]+/).map(Number);
// Analyze the pattern based on the rule
if (step.rule === 'Arithmetic Sequence' || step.rule.includes('Arithmetic')) {
const difference = sequence[1] - sequence[0];
return `This is an arithmetic sequence with a common difference of ${difference}. Each term is ${difference} more than the previous term.`;
}
if (step.rule === 'Geometric Sequence' || step.rule.includes('Geometric')) {
const ratio = sequence[1] / sequence[0];
return `This is a geometric sequence with a common ratio of ${ratio}. Each term is ${ratio} times the previous term.`;
}
if (step.rule === 'Fibonacci Sequence' || step.rule.includes('Fibonacci')) {
return `This is a Fibonacci-like sequence where each term is the sum of the two previous terms. For example, ${sequence[2]} = ${sequence[0]} + ${sequence[1]}.`;
}
if (step.rule === 'Quadratic Sequence' || step.rule.includes('Quadratic')) {
return `This is a quadratic sequence where the second differences are constant. This follows a pattern of the form an² + bn + c.`;
}
// Default sequence explanation
return `This step identifies the pattern in the sequence [${sequence.join(', ')}] and determines it follows a ${step.rule} pattern.`;
}
/**
* Get explanation for equation operations.
* @param step The solution step
* @param context The proof context
* @returns Explanation of the equation operation
*/
private getEquationExplanation(step: SolutionStep, context: ProofContext): string {
// Check if this is a solution step (contains =)
if (step.statement.includes('=')) {
const sides = step.statement.split('=').map(s => s.trim());
// Look for a known variable
const variableMatch = sides[0].match(/^[a-zA-Z]$/);
if (variableMatch) {
const variable = variableMatch[0];
const value = sides[1];
return `This step solves for the variable ${variable}, determining that ${variable} = ${value}.`;
}
// General equation explanation
return `This step manipulates the equation to isolate the variable on one side.`;
}
// System of equations
if (step.rule.includes('System')) {
return `This step applies methods for solving systems of equations, such as substitution or elimination, to find values for multiple variables that satisfy all equations simultaneously.`;
}
// Inequality
if (step.rule.includes('Inequality')) {
return `This step solves the inequality by applying algebraic manipulations while preserving the inequality relationship, resulting in a range of values that satisfy the constraint.`;
}
// Default equation explanation
return `This step applies algebraic manipulations to solve the equation.`;
}
/**
* Get explanation for simplification operations.
* @param step The solution step
* @param context The proof context
* @returns Explanation of the simplification operation
*/
private getSimplificationExplanation(step: SolutionStep, context: ProofContext): string {
// Check for specific simplification types
if (step.rule.includes('Factorization')) {
return `This step factors the expression to identify common terms and rewrite it as a product of simpler expressions.`;
}
if (step.rule.includes('Distribution')) {
return `This step applies the distributive property to multiply terms and expand the expression.`;
}
if (step.rule.includes('Term Combination')) {
return `This step combines like terms to simplify the expression.`;
}
// Default simplification explanation
return `This step simplifies the expression by applying algebraic rules and properties.`;
}
/**
* Get explanation for pattern in a statement.
* @param statement The mathematical statement
* @param rule The mathematical rule
* @returns Explanation of the pattern
*/
private getPatternExplanation(statement: string, rule: string): string {
// Check if this is a pattern recognition step
if (!rule.includes('Pattern') && !rule.includes('Sequence')) {
return '';
}
let explanation = '\nPattern Analysis:\n';
// Check for common patterns
for (const [pattern, desc] of Object.entries(this.patternExplanations)) {
if (rule.toLowerCase().includes(pattern)) {
explanation += `- ${pattern.charAt(0).toUpperCase() + pattern.slice(1)} Pattern: ${desc}\n`;
return explanation;
}
}
return '';
}
/**
* Get explanation for algebraic rules used in a step.
* @param step The solution step
* @returns Explanation of the algebraic rules
*/
private getAlgebraicRuleExplanation(step: SolutionStep): string {
// Check if this is an algebraic manipulation step
if (!step.rule.includes('Algebraic') && !step.rule.includes('Simplification') && !step.rule.includes('Solving')) {
return '';
}
let explanation = '\nAlgebraic Rules Applied:\n';
let foundRules = false;
for (const [rule, desc] of Object.entries(this.algebraicRules)) {
if (step.justification.toLowerCase().includes(rule)) {
explanation += `- ${rule.charAt(0).toUpperCase() + rule.slice(1)} Property: ${desc}\n`;
foundRules = true;
}
}
return foundRules ? explanation : '';
}
/**
* Get a step-by-step calculation breakdown.
* @param step The solution step
* @param context The proof context
* @returns Calculation breakdown
*/
private getCalculationBreakdown(step: SolutionStep, context: ProofContext): string {
// This would be a detailed calculation breakdown based on the step type
// For now, this is a simplified implementation
if (step.rule.includes('Equation') || step.rule.includes('Solving')) {
return 'Calculation Breakdown:\nStarting with the equation, we isolate the variable by applying algebraic operations to both sides:\n1. Combine like terms on each side\n2. Move all variable terms to one side\n3. Move all constant terms to the other side\n4. Divide both sides by the coefficient of the variable';
}
if (step.rule.includes('Sequence') || step.rule.includes('Pattern')) {
return 'Pattern Analysis Breakdown:\n1. Examine the first few terms of the sequence\n2. Calculate differences between consecutive terms\n3. Check if these differences are constant (arithmetic) or form another pattern\n4. Identify the formula that generates each term\n5. Apply this formula to find the next term or any specified term';
}
return '';
}
/**
* Generate a visualization for a sequence.
* @param step The solution step
* @param context The proof context
* @returns ASCII visualization of the sequence
*/
private generateSequenceVisualization(step: SolutionStep, context: ProofContext): string {
// Extract the sequence from the statement if possible
const sequenceMatch = step.statement.match(/\[([\d\s,\.]+)\]/);
if (!sequenceMatch) {
return 'Sequence visualization not available.';
}
const sequence = sequenceMatch[1].split(/[,\s]+/).map(Number);
// Create a simple graph representation
let visualization = 'Sequence Visualization:\n\n';
// Calculate the scale
const maxValue = Math.max(...sequence);
const scale = Math.min(40, Math.floor(60 / maxValue));
// Draw the graph
for (let i = 0; i < sequence.length; i++) {
const bars = '*'.repeat(Math.max(1, Math.floor(sequence[i] * scale)));
visualization += `Term ${i+1} (${sequence[i]}): ${bars}\n`;
}
// Add pattern information
if (step.rule === 'Arithmetic Sequence') {
const difference = sequence[1] - sequence[0];
visualization += `\nArithmetic Sequence: Common difference = ${difference}`;
} else if (step.rule === 'Geometric Sequence') {
const ratio = sequence[1] / sequence[0];
visualization += `\nGeometric Sequence: Common ratio = ${ratio}`;
} else if (step.rule === 'Fibonacci Sequence') {
visualization += '\nFibonacci Sequence: Each term is the sum of the two previous terms';
}
return visualization;
}
/**
* Generate a visualization for an equation.
* @param step The solution step
* @param context The proof context
* @returns ASCII visualization of the equation
*/
private generateEquationVisualization(step: SolutionStep, context: ProofContext): string {
// Simple implementation - would be replaced with actual visualization
let visualization = 'Equation Solving Process:\n\n';
// Get all previous steps
const allSteps = [
...context.previousSteps.filter(s => s.rule.includes('Equation') || s.rule.includes('Solving')),
step
];
// Create a step-by-step visualization
for (let i = 0; i < allSteps.length; i++) {
visualization += `Step ${i+1}: ${allSteps[i].statement}\n`;
}
return visualization;
}
/**
* Generate a visualization for an expression.
* @param step The solution step
* @param context The proof context
* @returns ASCII visualization of the expression
*/
private generateExpressionVisualization(step: SolutionStep, context: ProofContext): string {
// Simple implementation - would be replaced with actual visualization
let visualization = 'Expression Transformation:\n\n';
// Get all previous steps
const allSteps = [
...context.previousSteps.filter(s => s.rule.includes('Simplification') || s.rule.includes('Manipulation')),
step
];
// Create a step-by-step visualization
for (let i = 0; i < allSteps.length; i++) {
visualization += `Step ${i+1}: ${allSteps[i].statement}\n`;
}
return visualization;
}
/**
* Generate a visualization for a formula.
* @param step The solution step
* @param context The proof context
* @returns ASCII visualization of the formula
*/
private generateFormulaVisualization(step: SolutionStep, context: ProofContext): string {
// Default formula visualization
return `Formula Representation:\n${step.statement}`;
}
}