From f0bdf1e419dd8ebc16e230e1daf7ec082b937011 Mon Sep 17 00:00:00 2001 From: Miguel Date: Fri, 6 Jun 2025 15:26:00 +0200 Subject: [PATCH] =?UTF-8?q?Actualizaci=C3=B3n=20de=20la=20historia=20de=20?= =?UTF-8?q?c=C3=A1lculos=20con=20nuevas=20ecuaciones=20y=20valores.=20Mejo?= =?UTF-8?q?ra=20en=20la=20l=C3=B3gica=20de=20resoluci=C3=B3n=20iterativa?= =?UTF-8?q?=20y=20auto-aplicaci=C3=B3n=20de=20soluciones=20en=20el=20motor?= =?UTF-8?q?=20algebraico.=20Ajuste=20en=20la=20configuraci=C3=B3n=20de=20l?= =?UTF-8?q?a=20interfaz=20y=20eliminaci=C3=B3n=20de=20pruebas=20obsoletas.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hybrid_calc_history.txt | 10 +++-- hybrid_calc_settings.json | 2 +- main_evaluation_puro.py | 94 +++++++++++++++++++++++++++++++++++++-- test_final.py | 25 ----------- 4 files changed, 97 insertions(+), 34 deletions(-) delete mode 100644 test_final.py diff --git a/hybrid_calc_history.txt b/hybrid_calc_history.txt index bead65a..5f6c993 100644 --- a/hybrid_calc_history.txt +++ b/hybrid_calc_history.txt @@ -1,9 +1,11 @@ -y = x + 3 -z = y + x -solve(x) -solve(z) +y = 2*x + 3 +x = z * 4 +z = 8 +y=? +z=? + x=? # Instanciación via sympify diff --git a/hybrid_calc_settings.json b/hybrid_calc_settings.json index b85153f..8b1e1ad 100644 --- a/hybrid_calc_settings.json +++ b/hybrid_calc_settings.json @@ -1,6 +1,6 @@ { "window_geometry": "1020x700+356+1216", - "sash_pos_x": 343, + "sash_pos_x": 347, "symbolic_mode": true, "show_numeric_approximation": true, "keep_symbolic_fractions": true, diff --git a/main_evaluation_puro.py b/main_evaluation_puro.py index af33895..8ea1076 100644 --- a/main_evaluation_puro.py +++ b/main_evaluation_puro.py @@ -370,18 +370,30 @@ class PureAlgebraicEngine: except Exception as e: return f"Error resolviendo sistema: {e}" elif len(args) == 1 and hasattr(args[0], 'is_Symbol') and args[0].is_Symbol: - # solve(variable) - resolver para una variable específica y devolver ecuación + # solve(variable) - resolver para una variable específica y auto-aplicar var_symbol = args[0] solution_value = self._solve_for_variable(var_symbol) - # Si encontramos una solución, devolver como ecuación + # Si encontramos una solución, auto-aplicar al sistema if solution_value != var_symbol: - return Eq(var_symbol, solution_value) + # Resolver iterativamente para obtener el valor más simplificado + final_value = self._resolve_iteratively(solution_value) + + # Auto-aplicar la solución al sistema + self._auto_apply_solution(var_symbol, final_value) + + # Verificar que el resultado no sea problemático + if final_value == var_symbol or str(final_value) in ['True', 'False']: + return var_symbol + + return Eq(var_symbol, final_value) else: # Si no hay solución en las ecuaciones, verificar en symbol_table var_name = str(var_symbol) if var_name in self.symbol_table: - return Eq(var_symbol, self.symbol_table[var_name]) + value = self.symbol_table[var_name] + final_value = self._resolve_iteratively(value) + return Eq(var_symbol, final_value) else: return var_symbol else: @@ -475,6 +487,80 @@ class PureAlgebraicEngine: self.logger.debug(f"Error resolviendo {var_symbol}: {e}") return var_symbol + def _resolve_iteratively(self, expression, max_iterations=10): + """Resuelve una expresión iterativamente sustituyendo valores conocidos""" + try: + current_expr = expression + + for iteration in range(max_iterations): + # Sustituir valores del symbol_table + substituted = current_expr + + # Sustituir cada variable conocida por su valor + for var_name, value in self.symbol_table.items(): + var_symbol = sp.Symbol(var_name) + if var_symbol in substituted.free_symbols: + # Resolver recursivamente el valor antes de sustituir + resolved_value = self._resolve_iteratively(value, max_iterations - iteration - 1) if iteration < max_iterations - 1 else value + substituted = substituted.subs(var_symbol, resolved_value) + + # Si no hay cambio, hemos terminado + if substituted == current_expr: + break + + current_expr = substituted + + # Simplificar el resultado + if hasattr(current_expr, 'simplify'): + current_expr = simplify(current_expr) + + # Si llegamos a un valor numérico, terminar + if current_expr.is_number: + break + + return current_expr + + except Exception as e: + self.logger.debug(f"Error en resolución iterativa: {e}") + return expression + + def _auto_apply_solution(self, var_symbol, solution_value): + """Auto-aplica una solución al sistema como si fuera una nueva asignación""" + try: + var_name = str(var_symbol) + + # 1. Actualizar symbol_table + self.symbol_table[var_name] = solution_value + + # 2. Buscar y actualizar/reemplazar ecuaciones existentes + updated_equations = [] + equation_found = False + + for eq in self.equations: + if eq.lhs == var_symbol or eq.rhs == var_symbol: + # Reemplazar la ecuación existente + new_eq = Eq(var_symbol, solution_value) + updated_equations.append(new_eq) + equation_found = True + else: + updated_equations.append(eq) + + # 3. Si no había ecuación para esta variable, agregar una nueva + if not equation_found: + new_eq = Eq(var_symbol, solution_value) + updated_equations.append(new_eq) + + # 4. Actualizar la lista de ecuaciones + self.equations = updated_equations + + # 5. Asegurar que la variable esté en el conjunto de variables + self.variables.add(var_symbol) + + self.logger.debug(f"Auto-aplicada solución: {var_symbol} = {solution_value}") + + except Exception as e: + self.logger.debug(f"Error auto-aplicando solución: {e}") + def _get_numeric_approximation(self, expr) -> Optional[str]: """Obtiene aproximación numérica si es posible""" try: diff --git a/test_final.py b/test_final.py deleted file mode 100644 index 5ceae6f..0000000 --- a/test_final.py +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env python3 -""" -Test final con el ejemplo exacto del usuario -""" - -import main_evaluation_puro - -def test_ejemplo_usuario(): - print("=== EJEMPLO ORIGINAL DEL USUARIO ===") - - engine = main_evaluation_puro.PureAlgebraicEngine() - - casos = [ - "y = x + 3", - "z = y + x", - "solve(x)", - "solve(z)" - ] - - for caso in casos: - result = engine.evaluate_line(caso) - print(f"{caso} → {result.output}") - -if __name__ == "__main__": - test_ejemplo_usuario() \ No newline at end of file