# processors/process_add.py # -*- coding: utf-8 -*- import sympy import traceback import re # Importar re si se usa para formateo # Usar las nuevas utilidades from .processor_utils import get_sympy_representation, sympy_expr_to_scl, get_target_scl_name, format_variable_name from .symbol_manager import SymbolManager SCL_SUFFIX = "_sympy_processed" # Usar el nuevo sufijo def process_add(instruction, network_id, sympy_map, symbol_manager: SymbolManager, data): """Genera SCL para Add, simplificando la condición EN.""" instr_uid = instruction["instruction_uid"] instr_type_original = instruction.get("type", "Add") current_type = instruction.get("type","") if current_type.endswith(SCL_SUFFIX) or "_error" in current_type: return False # Obtener EN (SymPy), IN1, IN2 (SymPy o Constante/String) en_input = instruction["inputs"].get("en") in1_info = instruction["inputs"].get("in1") in2_info = instruction["inputs"].get("in2") sympy_en_expr = get_sympy_representation(en_input, network_id, sympy_map, symbol_manager) if en_input else sympy.true op1_sympy_or_const = get_sympy_representation(in1_info, network_id, sympy_map, symbol_manager) op2_sympy_or_const = get_sympy_representation(in2_info, network_id, sympy_map, symbol_manager) # Obtener destino SCL target_scl_name = get_target_scl_name(instruction, "out", network_id, default_to_temp=True) # Verificar dependencias if sympy_en_expr is None or op1_sympy_or_const is None or op2_sympy_or_const is None or target_scl_name is None: # print(f"DEBUG Add {instr_uid}: Dependency not ready") return False # Convertir operandos SymPy/Constante a SCL strings op1_scl = sympy_expr_to_scl(op1_sympy_or_const, symbol_manager) op2_scl = sympy_expr_to_scl(op2_sympy_or_const, symbol_manager) # Añadir paréntesis si contienen operadores (más seguro para SCL) op1_scl_formatted = f"({op1_scl})" if re.search(r'[+\-*/ ]', op1_scl) else op1_scl op2_scl_formatted = f"({op2_scl})" if re.search(r'[+\-*/ ]', op2_scl) else op2_scl # Generar SCL Core scl_core = f"{target_scl_name} := {op1_scl_formatted} + {op2_scl_formatted};" # Aplicar Condición EN (Simplificando EN) scl_final = "" if sympy_en_expr != sympy.true: try: #simplified_en_expr = sympy.simplify_logic(sympy_en_expr, force=True) simplified_en_expr = sympy.logic.boolalg.to_dnf(sympy_en_expr, simplify=True) except Exception as e: print(f"Error simplifying EN for {instr_type_original} {instr_uid}: {e}") simplified_en_expr = sympy_en_expr # Fallback en_condition_scl = sympy_expr_to_scl(simplified_en_expr, symbol_manager) # Evitar IF TRUE THEN... if en_condition_scl == "TRUE": scl_final = scl_core # Evitar IF FALSE THEN... elif en_condition_scl == "FALSE": scl_final = f"// {instr_type_original} {instr_uid} condition simplified to FALSE." else: indented_core = "\n".join([f" {line}" for line in scl_core.splitlines()]) scl_final = f"IF {en_condition_scl} THEN\n{indented_core}\nEND_IF;" else: scl_final = scl_core # Actualizar instrucción y mapa instruction["scl"] = scl_final # SCL final generado instruction["type"] = instr_type_original + SCL_SUFFIX # Propagar valor de salida (nombre SCL del destino) y ENO (expresión SymPy) map_key_out = (network_id, instr_uid, "out") sympy_map[map_key_out] = target_scl_name # Guardar nombre del destino (string) map_key_eno = (network_id, instr_uid, "eno") sympy_map[map_key_eno] = sympy_en_expr # Guardar la expresión SymPy para ENO return True # --- Processor Information Function --- def get_processor_info(): """Devuelve la información para el procesador Add.""" # Asegurar que la clave coincida con el tipo en JSON ('add') return {'type_name': 'add', 'processor_func': process_add, 'priority': 4}