diff --git a/.data/history.txt b/.data/history.txt index 0938bf3..135b662 100644 --- a/.data/history.txt +++ b/.data/history.txt @@ -1 +1,5 @@ -plot(sin(x), (x, 0, 1)) \ No newline at end of file +valor = 500 +k = valor * symbols('Hz') / symbols('mmS') + +valor_mmS = 100 * symbols('mmS') +speed = k * valor_mmS \ No newline at end of file diff --git a/custom_types/symbol_type.py b/custom_types/symbol_type.py new file mode 100644 index 0000000..f06263f --- /dev/null +++ b/custom_types/symbol_type.py @@ -0,0 +1,153 @@ +""" +Clase para símbolos SymPy - Tokenización automática de corchetes +Convierte [texto] automáticamente a symbols('texto') + +EJEMPLOS DE USO: + k = 100 * [Hz] → k = 100 * symbols('Hz') + E = [m] * [c]**2 → E = symbols('m') * symbols('c')**2 + f = [omega] / (2*[pi]) → f = symbols('omega') / (2*symbols('pi')) + +CARACTERÍSTICAS: + - Tokenización automática de [nombre] a symbols('nombre') + - Integración completa con SymPy para álgebra simbólica + - Soporte para operaciones matemáticas completas + - Prioridad alta en el sistema de tokenización +""" +from app.sympy_Base import SympyClassBase +import re + + +class SymPySymbol(SympyClassBase): + """ + Wrapper para símbolos de SymPy con tokenización automática de corchetes + + Esta clase permite usar la sintaxis [nombre] como shortcut para symbols('nombre'), + mejorando significativamente la experiencia de usuario para trabajo algebraico. + + Uso: [Hz] se convierte automáticamente a symbols('Hz') + """ + + def __init__(self, symbol_name): + """Inicialización del símbolo SymPy""" + from sympy import symbols + + if isinstance(symbol_name, str): + self.symbol_name = symbol_name + self.symbol = symbols(symbol_name) + else: + raise TypeError(f"SymPySymbol requiere un string, recibido: {type(symbol_name)}") + + # Llamar al constructor base + super().__init__(self.symbol, str(self.symbol)) + + def __str__(self): + """Representación string""" + return str(self.symbol) + + def _sympystr(self, printer): + """Representación SymPy string""" + return str(self.symbol) + + def __repr__(self): + return f"Symbol({self.symbol_name})" + + # ========== DELEGACIÓN DE OPERADORES A SYMPY ========== + + def __add__(self, other): + """Suma delegada al símbolo SymPy""" + return self.symbol + other + + def __radd__(self, other): + return other + self.symbol + + def __sub__(self, other): + """Resta delegada al símbolo SymPy""" + return self.symbol - other + + def __rsub__(self, other): + return other - self.symbol + + def __mul__(self, other): + """Multiplicación delegada al símbolo SymPy""" + return self.symbol * other + + def __rmul__(self, other): + return other * self.symbol + + def __truediv__(self, other): + """División delegada al símbolo SymPy""" + return self.symbol / other + + def __rtruediv__(self, other): + return other / self.symbol + + def __pow__(self, other): + """Potencia delegada al símbolo SymPy""" + return self.symbol ** other + + def __rpow__(self, other): + return other ** self.symbol + + # ========== MÉTODOS ESTÁTICOS ========== + + @staticmethod + def Helper(input_str): + """Ayuda contextual para símbolos""" + if re.search(r'\[.*\]', input_str): + return ('Uso: [Hz] se convierte automáticamente a symbols("Hz")\n' + 'Para unidades físicas, frecuencias, variables simbólicas, etc.\n' + 'Ejemplos: [x], [omega], [pi], [Hz], [m], [c]') + return None + + @staticmethod + def PopupFunctionList(): + """Lista de métodos sugeridos para símbolos""" + return [ + ("subs", "Sustituir valores: symbol.subs(x, valor)"), + ("expand", "Expandir expresión"), + ("simplify", "Simplificar expresión"), + ("factor", "Factorizar expresión"), + ("solve", "Resolver ecuaciones"), + ] + + @staticmethod + def get_tokenization_patterns(): + """ + Define la regla de tokenización principal: [texto] → symbols('texto') + + PATRÓN: \[([a-zA-Z_][a-zA-Z0-9_]*)\] + - Captura texto entre corchetes que empiece con letra o _ + - Permite números después del primer carácter + - Convierte a llamada symbols() automáticamente + + Returns: + List[Dict]: Lista de reglas de tokenización + """ + return [ + { + 'pattern': r'\[([a-zA-Z_][a-zA-Z0-9_]*)\]', + 'replacement': lambda match: f'symbols("{match.group(1)}")', + 'priority': 10, # ALTA prioridad - muy específico y común + 'description': 'Símbolos con corchetes: [Hz], [x], [omega] → symbols("Hz"), etc.' + } + ] + + +# ========== FUNCIÓN DE REGISTRO ========== + +def register_classes_in_module(): + """ + Registra la clase SymPySymbol en el sistema de tipos + + Configuración: + - add_lowercase: True (permite sympysymbol() además de SymPySymbol()) + - supports_brackets: False (los corchetes se manejan vía tokenización) + - Integración automática con el sistema de tokenización distribuida + """ + return [ + ("SymPySymbol", SymPySymbol, "SympyClassBase", { + "add_lowercase": True, + "supports_brackets": False, # Los corchetes se manejan vía tokenización + "description": "Símbolos SymPy con tokenización automática de corchetes [nombre]" + }), + ] \ No newline at end of file