import json from pathlib import Path def read_config(file_path): with open(file_path, 'r', encoding='utf-8') as file: config = json.load(file) return config def calculate_hydraulic_fault_weights(faults, config): # 初始化总权值 total_weight = 0 if '液压故障' in faults: total_weight += config['液压故障']['weight'] else: # 检查左液压子系统 left_hydraulic_subsystem = config['左液压子系统'] if any(fault in faults for fault in left_hydraulic_subsystem['faults']): total_weight += left_hydraulic_subsystem['weight'] else: subsystem_total_weight = 0 for subsystem_name, subsystem_data in left_hydraulic_subsystem['subsystems'].items(): relevant_fault_indices = [i for i, fault in enumerate(subsystem_data['faults']) if fault in faults] if relevant_fault_indices: if subsystem_data.get('max_weight', False): max_weight = max(subsystem_data['weights'][i] for i in relevant_fault_indices) subsystem_total_weight = max(subsystem_total_weight, max_weight) elif subsystem_data.get('special_rules'): applied_special_rule = False for rule in subsystem_data['special_rules']: if all(condition in faults for condition in rule['condition']): subsystem_total_weight += rule['weight'] applied_special_rule = True break if not applied_special_rule: subsystem_total_weight += sum(subsystem_data['weights'][i] for i in relevant_fault_indices) else: subsystem_total_weight += sum(subsystem_data['weights'][i] for i in relevant_fault_indices) total_weight += subsystem_total_weight # 检查右液压子系统 right_hydraulic_subsystem = config['右液压子系统'] if any(fault in faults for fault in right_hydraulic_subsystem['faults']): total_weight += right_hydraulic_subsystem['weight'] else: subsystem_total_weight = 0 for subsystem_name, subsystem_data in right_hydraulic_subsystem['subsystems'].items(): relevant_fault_indices = [i for i, fault in enumerate(subsystem_data['faults']) if fault in faults] if relevant_fault_indices: if subsystem_data.get('max_weight', False): max_weight = max(subsystem_data['weights'][i] for i in relevant_fault_indices) subsystem_total_weight = max(subsystem_total_weight, max_weight) elif subsystem_data.get('special_rules'): applied_special_rule = False for rule in subsystem_data['special_rules']: if all(condition in faults for condition in rule['condition']): subsystem_total_weight += rule['weight'] applied_special_rule = True break if not applied_special_rule: subsystem_total_weight += sum(subsystem_data['weights'][i] for i in relevant_fault_indices) else: subsystem_total_weight += sum(subsystem_data['weights'][i] for i in relevant_fault_indices) total_weight += subsystem_total_weight return total_weight # 示例用法 if __name__ == "__main__": current_dir = Path(__file__).parent json_path = current_dir.parent / "config" / "score_" \ "config.json" config = read_config(json_path) faults_occurred = ['液压泵1低压', '液压泵3传感器故障'] total_weight = calculate_hydraulic_fault_weights(faults_occurred, config) print(f"Total Weight: {total_weight}")