@flexabrain/mcp-server
Version:
Advanced electrical schematic analysis MCP server with rail engineering expertise
494 lines • 23.5 kB
JavaScript
/**
* FlexaBrain MCP Server - Core Electrical Schematic Analysis Service
*
* The main analysis engine that orchestrates OCR, component classification,
* connection analysis, and expert recommendations to provide comprehensive
* electrical schematic analysis with rail engineering expertise.
*/
import { RecommendationType, RecommendationPriority } from '../types/schematic';
import { SchematicType, SafetyLevel } from '../types/electrical';
import { ocrService } from './ocr-service';
import { electricalComponentClassifier } from './component-classifier';
export class ElectricalSchematicAnalyzer {
ocrService;
componentClassifier;
constructor() {
this.ocrService = ocrService;
this.componentClassifier = electricalComponentClassifier;
}
/**
* Perform comprehensive electrical schematic analysis
*/
async analyzeSchematic(imagePath, options = {
analysis_depth: 'standard',
focus_areas: ['safety', 'compliance']
}) {
const startTime = Date.now();
const errors = [];
const warnings = [];
try {
console.error(`FlexaBrain Analyzer: Starting analysis of ${imagePath}`);
// Phase 1: Image preprocessing (placeholder for now)
const imagePreprocessing = await this.preprocessImage(imagePath);
// Phase 2: OCR text extraction
console.error('FlexaBrain Analyzer: Extracting text via OCR...');
const ocrResults = await this.ocrService.extractComponentLabels(imagePath);
// Phase 3: Component recognition and classification
console.error('FlexaBrain Analyzer: Classifying electrical components...');
const classificationContext = this.buildClassificationContext(options);
const components = await this.componentClassifier.classifyComponents(ocrResults, classificationContext);
const componentRecognition = {
components,
total_components: components.length,
recognized_components: components.filter(c => c.confidence > 0.6).length,
overall_confidence: components.reduce((sum, c) => sum + c.confidence, 0) / Math.max(components.length, 1),
processing_time: Date.now() - startTime,
unrecognized_text: ocrResults.words
.filter(w => !components.some(c => c.id === w.text.trim().toUpperCase()))
.map(w => w.text)
};
// Phase 4: Connection and topology analysis
console.error('FlexaBrain Analyzer: Analyzing circuit topology...');
const connectionAnalysis = await this.analyzeConnections(components, imagePath);
const circuitTopology = await this.analyzeCircuitTopology(components, connectionAnalysis);
// Phase 5: Expert domain analysis
console.error('FlexaBrain Analyzer: Applying rail electrical expertise...');
const safetyAnalysis = await this.performSafetyAnalysis(components, circuitTopology, options);
const complianceReport = await this.generateComplianceReport(components, options);
const maintenanceGuidance = await this.generateMaintenanceGuidance(components, options);
const performanceAnalysis = await this.analyzePerformance(components, circuitTopology, options);
const expertRecommendations = await this.generateExpertRecommendations(components, circuitTopology, safetyAnalysis, complianceReport, options);
// Build comprehensive analysis result
const analysis = {
image_path: imagePath,
schematic_type: this.inferSchematicType(components),
analysis_timestamp: new Date(),
processing_time: Date.now() - startTime,
image_preprocessing: imagePreprocessing,
ocr_results: ocrResults,
component_recognition: componentRecognition,
components,
connection_analysis: connectionAnalysis,
circuit_topology: circuitTopology,
safety_analysis: safetyAnalysis,
compliance_report: complianceReport,
maintenance_guidance: maintenanceGuidance,
performance_analysis: performanceAnalysis,
expert_recommendations: expertRecommendations,
overall_confidence: this.calculateOverallConfidence(componentRecognition, safetyAnalysis, complianceReport),
analysis_quality: this.assessAnalysisQuality(componentRecognition, components.length),
limitations: this.identifyLimitations(components, ocrResults, options),
assumptions: this.documentAssumptions(options),
analyzer_version: '1.0.0',
rail_expertise_applied: true,
standards_version: '2025.1'
};
console.error(`FlexaBrain Analyzer: Analysis complete in ${analysis.processing_time}ms`);
console.error(`FlexaBrain Analyzer: Found ${components.length} components with ${(analysis.overall_confidence * 100).toFixed(1)}% confidence`);
const result = {
success: true,
analysis,
processing_stats: {
total_time: analysis.processing_time,
ocr_time: ocrResults.processing_time,
analysis_time: analysis.processing_time - ocrResults.processing_time,
validation_time: 0 // Will be calculated when validation is implemented
}
};
if (errors.length > 0) {
result.errors = errors;
}
if (warnings.length > 0) {
result.warnings = warnings;
}
return result;
}
catch (error) {
console.error('FlexaBrain Analyzer: Analysis failed:', error);
return {
success: false,
errors: [{
code: 'ANALYSIS_FAILED',
message: `Electrical schematic analysis failed: ${error instanceof Error ? error.message : String(error)}`,
recovery_suggestions: [
'Verify image file exists and is readable',
'Check image quality and clarity',
'Try preprocessing the image to improve OCR results',
'Ensure the image contains electrical schematic content'
]
}],
processing_stats: {
total_time: Date.now() - startTime,
ocr_time: 0,
analysis_time: 0,
validation_time: 0
}
};
}
}
/**
* Build classification context from analysis options
*/
buildClassificationContext(options) {
const context = {};
if (options.rail_system_context) {
context.rail_system_type = options.rail_system_context.system_type;
const parsedVoltage = this.parseVoltageFromSystem(options.rail_system_context.voltage_system);
if (parsedVoltage !== undefined) {
context.voltage_level = parsedVoltage;
}
}
return context;
}
/**
* Parse voltage level from system description
*/
parseVoltageFromSystem(voltageSystem) {
const voltageMatch = voltageSystem.match(/(\d+)(?:\.?\d*)?(?:k?V)/i);
if (voltageMatch && voltageMatch[1]) {
const value = parseFloat(voltageMatch[1]);
return voltageSystem.toLowerCase().includes('kv') ? value * 1000 : value;
}
return undefined;
}
/**
* Placeholder for image preprocessing
*/
async preprocessImage(imagePath) {
// TODO: Implement actual image preprocessing with Sharp/Jimp
return {
processed_image_path: imagePath,
original_dimensions: { width: 1920, height: 1080 },
processed_dimensions: { width: 1920, height: 1080 },
applied_filters: ['none'],
enhancement_quality: 1.0
};
}
/**
* Analyze electrical connections between components
*/
async analyzeConnections(components, imagePath) {
// Placeholder implementation - would use computer vision for line detection
const startTime = Date.now();
return {
connections: [], // TODO: Implement connection detection
circuit_paths: [], // TODO: Implement path tracing
total_connections: 0,
processing_time: Date.now() - startTime,
topology_complexity: components.length > 20 ? 'VERY_COMPLEX' :
components.length > 10 ? 'COMPLEX' :
components.length > 5 ? 'MODERATE' : 'SIMPLE'
};
}
/**
* Analyze circuit topology and power flow
*/
async analyzeCircuitTopology(components, connectionAnalysis) {
const powerSources = components.filter(c => ['converter', 'transformer', 'rectifier'].includes(c.type));
const loads = components.filter(c => ['converter', 'motor', 'heater'].includes(c.type));
const protectionDevices = components.filter(c => ['circuit_breaker', 'fuse', 'surge_protector'].includes(c.type));
return {
power_sources: powerSources,
loads,
protection_devices: protectionDevices,
control_circuits: connectionAnalysis.circuit_paths.filter(p => p.path_type === 'CONTROL'),
signal_circuits: connectionAnalysis.circuit_paths.filter(p => p.path_type === 'SIGNAL'),
grounding_system: {
is_adequate: protectionDevices.length > 0,
has_ground_fault_protection: protectionDevices.some(d => d.type === 'circuit_breaker'),
ground_electrodes: [],
bonding_connections: []
},
power_flows: [],
validation_results: {
is_valid: true,
overall_status: 'ACCEPTABLE',
violations: [],
safety_level: SafetyLevel.MEDIUM,
compliance_level: 0.8
}
};
}
/**
* Perform comprehensive safety analysis with rail electrical expertise
*/
async performSafetyAnalysis(components, topology, options) {
const highVoltageComponents = components.filter(c => c.specifications?.voltage_rating && c.specifications.voltage_rating.max > 1000);
const criticalComponents = components.filter(c => c.safety_level === SafetyLevel.CRITICAL);
return {
overall_safety_level: criticalComponents.length > 0 ? SafetyLevel.CRITICAL :
highVoltageComponents.length > 0 ? SafetyLevel.HIGH : SafetyLevel.MEDIUM,
arc_flash_hazards: {
present: highVoltageComponents.length > 0,
components: highVoltageComponents.map(c => c.id),
estimated_energy: highVoltageComponents.length * 5, // Simplified calculation
ppe_category: highVoltageComponents.length > 0 ? 2 : 0
},
electrical_shock_hazards: {
present: components.some(c => c.specifications?.voltage_rating && c.specifications.voltage_rating.max > 50),
voltage_levels: [...new Set(components
.filter(c => c.specifications?.voltage_rating)
.map(c => c.specifications.voltage_rating.max))],
components: components.filter(c => c.specifications?.voltage_rating && c.specifications.voltage_rating.max > 50).map(c => c.id)
},
ground_fault_risks: {
present: !topology.grounding_system.has_ground_fault_protection,
unprotected_circuits: topology.grounding_system.has_ground_fault_protection ? [] : ['main_circuit'],
recommendations: topology.grounding_system.has_ground_fault_protection ? [] : [
'Install ground fault circuit interrupters (GFCI)',
'Verify grounding system integrity',
'Implement ground fault monitoring'
]
},
fire_hazards: {
present: components.some(c => c.type === 'converter' || c.type === 'transformer'),
overloaded_circuits: [],
inadequate_protection: topology.protection_devices.length === 0 ? ['main_circuit'] : []
},
safety_recommendations: this.generateSafetyRecommendations(components, topology)
};
}
/**
* Generate safety recommendations based on rail electrical expertise
*/
generateSafetyRecommendations(components, topology) {
const recommendations = [];
// High voltage safety
const hvComponents = components.filter(c => c.specifications?.voltage_rating && c.specifications.voltage_rating.max > 1000);
if (hvComponents.length > 0) {
recommendations.push({
id: 'hv_safety_001',
type: RecommendationType.SAFETY,
priority: RecommendationPriority.CRITICAL,
category: 'high_voltage',
title: 'High Voltage Safety Protocols Required',
description: `${hvComponents.length} high voltage components require specialized safety procedures`,
action: 'Implement lockout/tagout procedures and provide appropriate PPE',
component_ids: hvComponents.map(c => c.id)
});
}
// Arc flash protection
const arcFlashComponents = components.filter(c => ['converter', 'transformer', 'circuit_breaker'].includes(c.type));
if (arcFlashComponents.length > 0) {
recommendations.push({
id: 'arc_flash_001',
type: RecommendationType.SAFETY,
priority: RecommendationPriority.HIGH,
category: 'arc_flash',
title: 'Arc Flash Hazard Assessment Required',
description: 'Components present arc flash hazards requiring analysis per IEEE 1584',
action: 'Perform arc flash study and install appropriate warning labels',
component_ids: arcFlashComponents.map(c => c.id)
});
}
return recommendations;
}
/**
* Generate standards compliance report
*/
async generateComplianceReport(components, options) {
const standards = ['EN 50155', 'IEC 61375', 'IEEE 519', ...(options.custom_standards || [])];
const compliantItems = [];
const nonCompliantItems = [];
const requiresReview = [];
// Check each component against standards
for (const component of components) {
const componentStandards = component.specifications?.standards_compliance || [];
for (const standard of standards) {
if (componentStandards.includes(standard)) {
compliantItems.push({
standard,
item: component.id,
status: 'COMPLIANT',
notes: `Component meets ${standard} requirements`
});
}
else {
requiresReview.push({
standard,
item: component.id,
status: 'REQUIRES_REVIEW',
reason: `No explicit compliance information available for ${standard}`,
expert_needed: true
});
}
}
}
return {
overall_compliance: compliantItems.length / Math.max(compliantItems.length + nonCompliantItems.length + requiresReview.length, 1),
standards_checked: standards,
compliant_items: compliantItems,
non_compliant_items: nonCompliantItems,
requires_review: requiresReview
};
}
/**
* Generate maintenance guidance based on component types and rail expertise
*/
async generateMaintenanceGuidance(components, options) {
const componentSchedules = components.map(component => {
const maintenance = component.specifications?.maintenance_intervals;
const now = new Date();
const schedule = {
component_id: component.id,
component_type: component.type,
next_inspection: new Date(now.getTime() + (maintenance?.inspection.frequency || 12) * 30 * 24 * 60 * 60 * 1000)
};
if (maintenance?.testing) {
schedule.next_testing = new Date(now.getTime() + maintenance.testing.frequency * 30 * 24 * 60 * 60 * 1000);
}
if (maintenance?.calibration) {
schedule.next_calibration = new Date(now.getTime() + maintenance.calibration.frequency * 30 * 24 * 60 * 60 * 1000);
}
if (maintenance?.overhaul) {
schedule.next_overhaul = new Date(now.getTime() + maintenance.overhaul.frequency * 30 * 24 * 60 * 60 * 1000);
}
return schedule;
});
const priorityActions = [
{
action: 'Visual inspection of all high-voltage components',
component_ids: components.filter(c => c.safety_level === SafetyLevel.CRITICAL).map(c => c.id),
urgency: 'SCHEDULED',
estimated_duration: '2-4 hours',
estimated_cost: 'Low'
}
];
return {
component_schedules: componentSchedules,
priority_actions: priorityActions,
maintenance_recommendations: []
};
}
/**
* Analyze performance characteristics
*/
async analyzePerformance(components, topology, options) {
return {
efficiency_metrics: {
overall_efficiency: 0.92, // Placeholder
power_factor: 0.85,
load_balance: 0.95,
harmonic_distortion: 0.05
},
optimization_opportunities: {
energy_savings_potential: 5,
cost_reduction_potential: 10,
reliability_improvement: ['Redundant protection systems', 'Preventive maintenance scheduling']
},
performance_recommendations: []
};
}
/**
* Generate expert recommendations combining all analysis results
*/
async generateExpertRecommendations(components, topology, safetyAnalysis, complianceReport, options) {
const recommendations = [];
// Add safety recommendations
recommendations.push(...safetyAnalysis.safety_recommendations);
// Add performance recommendations based on component analysis
const converters = components.filter(c => c.type === 'converter');
if (converters.length > 0) {
recommendations.push({
id: 'maintenance_001',
type: RecommendationType.MAINTENANCE,
priority: RecommendationPriority.MEDIUM,
category: 'preventive',
title: 'Traction Converter Maintenance',
description: 'Regular maintenance prevents costly failures',
action: 'Schedule quarterly inspections of cooling systems and power electronics',
component_ids: converters.map(c => c.id)
});
}
const criticalCount = recommendations.filter(r => r.priority === RecommendationPriority.CRITICAL).length;
const highCount = recommendations.filter(r => r.priority === RecommendationPriority.HIGH).length;
return {
recommendations,
summary: {
total_recommendations: recommendations.length,
critical_count: criticalCount,
high_priority_count: highCount,
estimated_total_cost: 'Medium',
estimated_total_savings: 'High'
},
next_actions: {
immediate: recommendations.filter(r => r.priority === RecommendationPriority.CRITICAL),
short_term: recommendations.filter(r => r.priority === RecommendationPriority.HIGH),
long_term: recommendations.filter(r => r.priority === RecommendationPriority.MEDIUM)
}
};
}
/**
* Infer schematic type from component analysis
*/
inferSchematicType(components) {
const hasSignalComponents = components.some(c => c.category === 'signaling');
const hasPowerComponents = components.some(c => c.category === 'traction_power');
const hasControlComponents = components.some(c => c.category === 'control');
if (hasSignalComponents)
return SchematicType.SIGNALING;
if (hasPowerComponents)
return SchematicType.TRACTION_POWER;
if (hasControlComponents)
return SchematicType.CONTROL;
return SchematicType.GENERAL;
}
/**
* Calculate overall confidence score
*/
calculateOverallConfidence(componentRecognition, safetyAnalysis, complianceReport) {
const weights = {
component: 0.5,
safety: 0.3,
compliance: 0.2
};
return (componentRecognition.overall_confidence * weights.component +
0.8 * weights.safety + // Placeholder for safety confidence
complianceReport.overall_compliance * weights.compliance);
}
/**
* Assess analysis quality
*/
assessAnalysisQuality(recognition, totalComponents) {
if (recognition.overall_confidence > 0.9 && totalComponents > 5)
return 'EXCELLENT';
if (recognition.overall_confidence > 0.8 && totalComponents > 3)
return 'GOOD';
if (recognition.overall_confidence > 0.6)
return 'ACCEPTABLE';
return 'POOR';
}
/**
* Identify analysis limitations
*/
identifyLimitations(components, ocrResult, options) {
const limitations = [];
if (components.length === 0) {
limitations.push('No electrical components were identified in the schematic');
}
if (ocrResult.confidence < 0.7) {
limitations.push('OCR confidence is low - image quality may affect accuracy');
}
if (options.analysis_depth === 'basic') {
limitations.push('Basic analysis level - some advanced features not included');
}
return limitations;
}
/**
* Document analysis assumptions
*/
documentAssumptions(options) {
const assumptions = [
'Schematic follows standard electrical drawing conventions',
'Component labels are clearly visible and readable',
'Drawing scale and orientation are consistent'
];
if (options.rail_system_context) {
assumptions.push(`Analysis assumes ${options.rail_system_context.system_type} rail system context`);
}
return assumptions;
}
}
// Export singleton instance
export const electricalSchematicAnalyzer = new ElectricalSchematicAnalyzer();
//# sourceMappingURL=electrical-analyzer.js.map