Spaces:
Running
Running
Commit ·
8caaf20
1
Parent(s): b70a3e1
Add more symbol support in custom function expressions
Browse filesFiles changed (5)
1234577 unmodified lines83848586878889909192939495969798991001011021031041051067 unmodified lines11411511611711811912012129 unmodified lines151152153154155156157import numpy as npfrom sympy import sympify, lambdifyfrom optimization_logic import *77 unmodified lines# function expression checktry:expr = sympify(function)symbols = {s.name for s in expr.free_symbols}if mode == "univariate":return symbols in {frozenset({'x'}), frozenset(set())}elif mode == "bivariate":return symbols in {frozenset({'x', 'y'}),frozenset({'x'}),frozenset({'y'}),frozenset(set()),}else:return Falseexcept Exception as e:passreturn Falsedef _function_changed(self, function: str, mode: str) -> bool:function = function.strip()7 unmodified linesexcept Exception as e:self.trajectory_values = {"x": [], "y": []}def _compute_function_values(self, function: str, mode: str, xlim: list, ylim: list) -> None:expr = sympify(function)if mode == "univariate":x = np.linspace(xlim[0], xlim[1], 100)f = lambdify('x', expr, modules=['numpy'])29 unmodified linesdef _compute_trajectory_values(self, settings: dict, steps: int) -> None:mode = settings.get("mode", "").lower().strip()algorithm = settings.get("algorithm", "").lower().strip().replace(" ", "_")function = sympify(settings.get("functionExpr", "").strip())if mode == "univariate":if algorithm == "gradient_descent":123456789101112131415161718192021222324252677 unmodified lines1041051061071081091101111121131141151161177 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617729 unmodified lines207208209210211212213import numpy as npfrom sympy import (lambdify,symbols,sin,cos,tan,asin,acos,atan,exp,log,sqrt,pi,Abs,)from sympy.parsing.sympy_parser import (standard_transformations,implicit_multiplication_application,convert_xor,parse_expr,)from optimization_logic import *77 unmodified lines# function expression checktry:expr = self._parse_function(function)except Exception as e:return Falseif mode == "univariate" and symbols("y") in expr.free_symbols:return Falsereturn Truedef _function_changed(self, function: str, mode: str) -> bool:function = function.strip()7 unmodified linesexcept Exception as e:self.trajectory_values = {"x": [], "y": []}def _parse_function(self, function: str) -> Expr:if not function.strip():raise ValueError("Function expression cannot be empty")x, y = symbols("x y")allowed_locals = {'x': x,'y': y,'sin': sin,'cos': cos,'tan': tan,'asin': asin,'acos': acos,'atan': atan,'log': log,'ln': log,'sqrt': sqrt,'abs': Abs,'exp': exp,'e': exp(1),'pi': pi,'π': pi,}try:parsed_function = parse_expr(function,local_dict=allowed_locals,transformations=standard_transformations + (implicit_multiplication_application,convert_xor,),evaluate=True,)except Exception as e:raise ValueError(f"Invalid function expression: {e}")unknown_symbols = parsed_function.free_symbols - {x, y}if unknown_symbols:unknown_names = ", ".join(sorted(str(s) for s in unknown_symbols))raise ValueError(f"Unknown variable(s): {unknown_names}. Allowed: x, y")return parsed_functiondef _compute_function_values(self, function: str, mode: str, xlim: list, ylim: list) -> None:expr = self._parse_function(function)if mode == "univariate":x = np.linspace(xlim[0], xlim[1], 100)f = lambdify('x', expr, modules=['numpy'])29 unmodified linesdef _compute_trajectory_values(self, settings: dict, steps: int) -> None:mode = settings.get("mode", "").lower().strip()algorithm = settings.get("algorithm", "").lower().strip().replace(" ", "_")function = self._parse_function(settings.get("functionExpr", "").strip())if mode == "univariate":if algorithm == "gradient_descent":
1234577 unmodified lines83848586878889909192939495969798991001011021031041051067 unmodified lines11411511611711811912012129 unmodified lines151152153154155156157667 unmodified lines825826827828(function(){"use strict";var i=`import numpy as npfrom sympy import sympify, lambdifyfrom optimization_logic import *77 unmodified lines# function expression checktry:expr = sympify(function)symbols = {s.name for s in expr.free_symbols}if mode == "univariate":return symbols in {frozenset({'x'}), frozenset(set())}elif mode == "bivariate":return symbols in {frozenset({'x', 'y'}),frozenset({'x'}),frozenset({'y'}),frozenset(set()),}else:return Falseexcept Exception as e:passreturn Falsedef _function_changed(self, function: str, mode: str) -> bool:function = function.strip()7 unmodified linesexcept Exception as e:self.trajectory_values = {"x": [], "y": []}def _compute_function_values(self, function: str, mode: str, xlim: list, ylim: list) -> None:expr = sympify(function)if mode == "univariate":x = np.linspace(xlim[0], xlim[1], 100)f = lambdify('x', expr, modules=['numpy'])29 unmodified linesdef _compute_trajectory_values(self, settings: dict, steps: int) -> None:mode = settings.get("mode", "").lower().strip()algorithm = settings.get("algorithm", "").lower().strip().replace(" ", "_")function = sympify(settings.get("functionExpr", "").strip())if mode == "univariate":if algorithm == "gradient_descent":667 unmodified lines"x": x_values,"y": y_values,"z": z_values,}`;const o="https://cdn.jsdelivr.net/pyodide/v0.26.1/full/pyodide.mjs";let e=null,t=null;async function f(){const{loadPyodide:n}=await import(o);e=await n({indexURL:"https://cdn.jsdelivr.net/pyodide/v0.26.1/full/"}),await e.loadPackage(["numpy","sympy"]),e.FS.writeFile("optimization_logic.py",l),e.FS.writeFile("optimization_manager.py",i),e.runPython("from optimization_manager import OptimizationManager; manager = OptimizationManager();"),t=e.globals.get("manager"),t||console.error("Failed to initialize optimization manager"),self.postMessage({type:"READY"})}function s(n){if(!n)return null;try{const a=n.toJs({dict_converter:Object.fromEntries});n.destroy&&n.destroy(),self.postMessage({type:"RESULT",data:a})}catch(a){console.error("Error handling Python result:",a)}}self.onmessage=async n=>{const a=n.data;if(!t){console.warn("Pyodide is not ready yet");return}switch(a.type){case"INIT":const r=e.toPy(a.settings);s(t.handle_update_settings(r));break;case"NEXT_STEP":s(t.handle_next_step());break;case"PREV_STEP":s(t.handle_prev_step());break;case"RESET":s(t.handle_reset());break;default:console.error("Unknown message type:",a);break}},f()})();123456789101112131415161718192021222324252677 unmodified lines1041051061071081091101111121131141151161177 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617729 unmodified lines207208209210211212213667 unmodified lines881882883884(function(){"use strict";var i=`import numpy as npfrom sympy import (lambdify,symbols,sin,cos,tan,asin,acos,atan,exp,log,sqrt,pi,Abs,)from sympy.parsing.sympy_parser import (standard_transformations,implicit_multiplication_application,convert_xor,parse_expr,)from optimization_logic import *77 unmodified lines# function expression checktry:expr = self._parse_function(function)except Exception as e:return Falseif mode == "univariate" and symbols("y") in expr.free_symbols:return Falsereturn Truedef _function_changed(self, function: str, mode: str) -> bool:function = function.strip()7 unmodified linesexcept Exception as e:self.trajectory_values = {"x": [], "y": []}def _parse_function(self, function: str) -> Expr:if not function.strip():raise ValueError("Function expression cannot be empty")x, y = symbols("x y")allowed_locals = {'x': x,'y': y,'sin': sin,'cos': cos,'tan': tan,'asin': asin,'acos': acos,'atan': atan,'log': log,'ln': log,'sqrt': sqrt,'abs': Abs,'exp': exp,'e': exp(1),'pi': pi,'π': pi,}try:parsed_function = parse_expr(function,local_dict=allowed_locals,transformations=standard_transformations + (implicit_multiplication_application,convert_xor,),evaluate=True,)except Exception as e:raise ValueError(f"Invalid function expression: {e}")unknown_symbols = parsed_function.free_symbols - {x, y}if unknown_symbols:unknown_names = ", ".join(sorted(str(s) for s in unknown_symbols))raise ValueError(f"Unknown variable(s): {unknown_names}. Allowed: x, y")return parsed_functiondef _compute_function_values(self, function: str, mode: str, xlim: list, ylim: list) -> None:expr = self._parse_function(function)if mode == "univariate":x = np.linspace(xlim[0], xlim[1], 100)f = lambdify('x', expr, modules=['numpy'])29 unmodified linesdef _compute_trajectory_values(self, settings: dict, steps: int) -> None:mode = settings.get("mode", "").lower().strip()algorithm = settings.get("algorithm", "").lower().strip().replace(" ", "_")function = self._parse_function(settings.get("functionExpr", "").strip())if mode == "univariate":if algorithm == "gradient_descent":667 unmodified lines"x": x_values,"y": y_values,"z": z_values,}`;const o="https://cdn.jsdelivr.net/pyodide/v0.26.1/full/pyodide.mjs";let e=null,t=null;async function r(){const{loadPyodide:n}=await import(o);e=await n({indexURL:"https://cdn.jsdelivr.net/pyodide/v0.26.1/full/"}),await e.loadPackage(["numpy","sympy"]),e.FS.writeFile("optimization_logic.py",l),e.FS.writeFile("optimization_manager.py",i),e.runPython("from optimization_manager import OptimizationManager; manager = OptimizationManager();"),t=e.globals.get("manager"),t||console.error("Failed to initialize optimization manager"),self.postMessage({type:"READY"})}function s(n){if(!n)return null;try{const a=n.toJs({dict_converter:Object.fromEntries});n.destroy&&n.destroy(),self.postMessage({type:"RESULT",data:a})}catch(a){console.error("Error handling Python result:",a)}}self.onmessage=async n=>{const a=n.data;if(!t){console.warn("Pyodide is not ready yet");return}switch(a.type){case"INIT":const f=e.toPy(a.settings);s(t.handle_update_settings(f));break;case"NEXT_STEP":s(t.handle_next_step());break;case"PREV_STEP":s(t.handle_prev_step());break;case"RESET":s(t.handle_reset());break;default:console.error("Unknown message type:",a);break}},r()})();
4 unmodified lines5678910114 unmodified lines<link rel="icon" type="image/svg+xml" href="/vite.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Optimization</title><script type="module" crossorigin src="/assets/index-DyZyiv0F.js"></script><link rel="stylesheet" crossorigin href="/assets/index-CBOaLvz3.css"></head><body>4 unmodified lines5678910114 unmodified lines<link rel="icon" type="image/svg+xml" href="/vite.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Optimization</title><script type="module" crossorigin src="/assets/index-CZNS1f0O.js"></script><link rel="stylesheet" crossorigin href="/assets/index-CBOaLvz3.css"></head><body>
18 unmodified lines192021222324252627282930313233343536373829 unmodified lines686970717273743 unmodified lines7879808182838418 unmodified linesconst UNIVARIATE_FUNCTION_OPTIONS = {"--Custom--": "3 * x^2 + x","Quadratic": "x^2","Cubic": "x^3 - 3*x^2 + 2*x","Quartic": "x^4 - 4*x^3 + 6*x^2 - 4*x + 1","Sine": "sin(x)","Exponential": "exp(x) - 5",}const BIVARIATE_FUNCTION_OPTIONS = {"--Custom--": "x^2 + 3 * y^2","Quadratic": "x^2 + y^2","Ackley": "-20 * exp(-0.2 * sqrt(0.5 * (x^2 + y^2))) - exp(0.5 * (cos(2 * pi * x) + cos(2 * pi * y))) + e + 20","Rasteringin": "20 + (x^2 - 10 * cos(2 * pi * x)) + (y^2 - 10 * cos(2 * pi * y))","Rosenbrock": "(1 - x)^2 + 100 * (y - x^2)^2",}29 unmodified lines}}const [functionOption, setFunctionOption] = useState<string>("Quadratic");function handleFunctionOptionChange(option: string) {setFunctionOption(option);3 unmodified linesfunction handleModeChange(mode: SettingsUi["mode"]) {// When changing modes, reset function to Quadratic as some options are mode-specificconst newFunctionOption = "Quadratic";const expr = mode === "Bivariate"? BIVARIATE_FUNCTION_OPTIONS[newFunctionOption as keyof typeof BIVARIATE_FUNCTION_OPTIONS]18 unmodified lines192021222324252627282930313233343536373829 unmodified lines686970717273743 unmodified lines7879808182838418 unmodified linesconst UNIVARIATE_FUNCTION_OPTIONS = {"--Custom--": "x^2","Quadratic": "x^2","Cubic": "x^3 - 3x^2 + 2x","Quartic": "x^4 - 4x^3 + 6x^2 - 4x + 1","Sine": "sin(x)","Exponential": "exp(x)",}const BIVARIATE_FUNCTION_OPTIONS = {"--Custom--": "x^2 + 3y^2","Quadratic": "x^2 + y^2","Ackley": "-20exp(-0.2 sqrt(0.5 (x^2 + y^2))) - exp(0.5 (cos(2 pi x) + cos(2 pi y))) + e + 20","Rasteringin": "20 + (x^2 - 10 cos(2 * pi * x)) + (y^2 - 10 cos(2 pi y))","Rosenbrock": "(1 - x)^2 + 100 (y - x^2)^2",}29 unmodified lines}}const [functionOption, setFunctionOption] = useState<string>("--Custom--");function handleFunctionOptionChange(option: string) {setFunctionOption(option);3 unmodified linesfunction handleModeChange(mode: SettingsUi["mode"]) {// When changing modes, reset function to Quadratic as some options are mode-specificconst newFunctionOption = "--Custom--";const expr = mode === "Bivariate"? BIVARIATE_FUNCTION_OPTIONS[newFunctionOption as keyof typeof BIVARIATE_FUNCTION_OPTIONS]
backend/src/optimization_manager.py+75-19
dist/assets/index-DyZyiv0F.js → dist/assets/index-CZNS1f0O.jsRenamed
dist/assets/pyodide.worker-BeUH2O5o.js → dist/assets/pyodide.worker-Dr32d4MW.jsRenamed+76-20
dist/index.html+1-1
frontends/react/src/Sidebar.tsx+10-10