import {
LogicalSystem,
Operation,
InputFormat,
LogicResult,
MathematicalArgument
} from '../types.js';
import {
createSyntaxError,
createMathematicalError,
createUnsupportedOperationError,
errorTemplates,
errorSuggestions,
exampleTemplates
} from '../errorHandler.js';
// Import parsers
import { MathematicalParser } from '../parsers/mathematicalParser.js';
import { EnhancedMathematicalParser } from '../parsers/enhancedMathematicalParser.js';
// Import NLP preprocessor
import { NaturalLanguageProcessor } from '../preprocessors/naturalLanguageProcessor.js';
// Import specialized modules
import {
MathematicalEvaluator,
MathematicalValidator,
MathematicalFormatter,
MathematicalSolver,
MathematicalVisualizer
} from './mathematical/index.js';
// Import logger
import { Loggers } from '../utils/logger.js';
const logger = Loggers.mathematical;
/**
* Mathematical Logic System
* Orchestrates mathematical operations by delegating to specialized modules
*/
export class MathematicalLogic {
private parser: MathematicalParser;
private enhancedParser: EnhancedMathematicalParser;
private nlpProcessor: NaturalLanguageProcessor;
// Specialized modules
private evaluator: MathematicalEvaluator;
private validator: MathematicalValidator;
private formatter: MathematicalFormatter;
private solver: MathematicalSolver;
private visualizer: MathematicalVisualizer;
// State
private variableMap: Map<string, string> = new Map();
private sequenceMap: Map<string, number[]> = new Map();
constructor() {
// Initialize parsers
this.parser = new MathematicalParser();
this.enhancedParser = new EnhancedMathematicalParser();
this.nlpProcessor = new NaturalLanguageProcessor();
// Initialize specialized modules
this.evaluator = new MathematicalEvaluator();
this.validator = new MathematicalValidator();
this.formatter = new MathematicalFormatter();
this.solver = new MathematicalSolver();
this.visualizer = new MathematicalVisualizer();
}
/**
* Main entry point for mathematical logic operations
* @param operation The operation to perform
* @param input Input text or structured data
* @param format Input format
* @returns Operation result
*/
process(
operation: Operation,
input: string | MathematicalArgument,
format: InputFormat = 'natural'
): LogicResult {
try {
// Reset state
this.variableMap = new Map<string, string>();
this.sequenceMap = new Map<string, number[]>();
// Parse the input if it's a string
const parsedInput = typeof input === 'string'
? this.parseInput(input, format)
: input;
// Perform the requested operation by delegating to specialized modules
switch (operation) {
case 'validate':
return this.validator.validateMathematical(parsedInput, this.variableMap, this.sequenceMap);
case 'formalize':
return this.formatter.formatMathematical(parsedInput, format, this.variableMap, this.sequenceMap);
case 'visualize':
return this.visualizer.generateVisualization(parsedInput, this.variableMap, this.sequenceMap);
case 'solve':
return this.solver.generateSolution(parsedInput, this.variableMap, this.sequenceMap);
default:
return createUnsupportedOperationError(
'mathematical',
operation,
`Try using 'validate', 'formalize', 'visualize', or 'solve'.`,
`${operation} --system=mathematical --input="1, 2, 3, 4, 5"`
);
}
} catch (error) {
return this.handleError(error, input);
}
}
/**
* Parse input text into mathematical argument
* @param input Input text
* @param format Input format
* @returns Parsed mathematical argument
*/
private parseInput(
input: string,
format: InputFormat
): MathematicalArgument {
// Preprocess natural language if needed
let processedInput = input;
if (format === 'natural') {
// Use the NLP processor to preprocess the input
const nlpResult = this.nlpProcessor.preprocess(input);
processedInput = nlpResult.processedInput;
try {
// Use the enhanced parser for natural language input
const parsedResult = this.enhancedParser.parse(processedInput);
// Get variable mapping from enhanced parser
this.variableMap = (this.enhancedParser as any).variableMap || new Map();
this.sequenceMap = (this.enhancedParser as any).sequenceMap || new Map();
return parsedResult;
} catch (error) {
// Attempt to use standard parser if enhanced parser fails
logger.warn("Enhanced parser failed, attempting to use standard parser", {
error: error instanceof Error ? error.message : String(error),
input: processedInput
});
try {
return this.parser.parse(processedInput);
} catch (standardError) {
// Detailed error handling for parsing failures
if (processedInput.includes(',')) {
// Likely a sequence with formatting issues
throw new Error(errorTemplates.syntax.mathematical.invalidSequence);
} else if (processedInput.includes('=')) {
// Likely an equation with issues
throw new Error(errorTemplates.syntax.mathematical.unbalancedEquation);
} else {
// Generic parsing error with enhanced details
throw new Error(`Invalid mathematical expression: ${processedInput}. ${errorSuggestions.syntax.mathematical.invalidExpression}`);
}
}
}
} else {
// Use the standard parser for symbolic/formal input
return this.parser.parse(processedInput);
}
}
/**
* Handle errors with enhanced error messages
* @param error The error that occurred
* @param input The original input
* @returns Error result
*/
private handleError(error: unknown, input: string | MathematicalArgument): LogicResult {
// Return an enhanced error result
if (error instanceof Error) {
// Parse error message to determine type
if (error.message.includes('parse') || error.message.includes('syntax')) {
return createSyntaxError(
'mathematical',
error.message,
'input',
errorSuggestions.syntax.mathematical.invalidExpression,
exampleTemplates.syntax.mathematical.invalidExpression,
typeof input === 'string' ? input : JSON.stringify(input)
);
} else if (error.message.includes('division by zero')) {
return createMathematicalError(
errorTemplates.validation.mathematical.divisionByZero,
'operation',
errorSuggestions.validation.mathematical.divisionByZero,
exampleTemplates.validation.mathematical.divisionByZero,
typeof input === 'string' ? input : JSON.stringify(input)
);
} else if (error.message.includes('not defined')) {
return createMathematicalError(
error.message,
'variables',
'Make sure all variables are properly defined in the equation.',
'x + 5 = 10',
typeof input === 'string' ? input : JSON.stringify(input)
);
}
}
// Generic error
return createMathematicalError(
error instanceof Error ? error.message : 'Unknown error',
'unknown',
'Check your input for any errors in mathematical notation.',
'1, 2, 3, 4, 5',
typeof input === 'string' ? input : JSON.stringify(input)
);
}
}