Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

symbolics_to_sympy() and variable constrains #347

Open
owiecc opened this issue Aug 16, 2021 · 3 comments
Open

symbolics_to_sympy() and variable constrains #347

owiecc opened this issue Aug 16, 2021 · 3 comments

Comments

@owiecc
Copy link
Contributor

owiecc commented Aug 16, 2021

I'd like to solve a set on nonlinear equations. As this is not implemented yet (JuliaSymbolics/SymbolicUtils.jl#63) I am trying to use SymPy to do that. This is just a MWE, real problem is a bit more complex.

using Symbolics, SymPy

@variables x, y
eqns = [x^2 - y ~ 0, 4*x - 1 ~ 0]

Here I do a conversion to SymPy:

sx = symbols("x")
sy = symbols("y")
sol = nonlinsolve([symbolics_to_sympy(eq.lhs) for eq in eqns], sx, sy)

This solves correctly to {(1/4,1/16)}

However, if I add additional constrains on the variables I get bad results:

sx = symbols("x", positive = True)
sy = symbols("y")
sol = nonlinsolve([symbolics_to_sympy(eq.lhs) for eq in eqns], sx, sy)

This solves to an empty set:

I assume this is because symbolics_to_sympy() creates a variable x without constrains but I add these constrains later, in sx. Any ideas how to solve this problem?

┆Issue is synchronized with this Trello card by Unito

@ChrisRackauckas
Copy link
Member

We need to make a constraints system 😅

@owiecc
Copy link
Contributor Author

owiecc commented Aug 18, 2021

I made a small workaround if anyone stumbles on the same problem. I replaced the symbols created with symbolics_to_sympy() with constrained ones from SymPy. It is not pretty but is does work.

sx = symbols("x")
sy = symbols("y")

sa = symbols("a", positive = True)
sb = symbols("b")

subsymbols(ex) = subs(ex, sx=>sa, sy=> sb)

eqns_ab = [subsymbols(symbolics_to_sympy(eq.lhs)) for eq in eqns]

The solve function solves the nonlinear system correctly.

solve(eqns_ab, sa, sb) # (1/4, 1/16)

The nonlinsolve will also solve the system.

nonlinsolve(eqns_ab, sa, sb) # {(1/4, 1/16)}

However, nonlinsolve ignores the constraints. If I change the equations to [x^2 - y ~ 0, 4*x + 1 ~ 0] I get this:

solve(eqns_ab, sa, sb) # Any[]
nonlinsolve(eqns_ab, sa, sb) # {(-1/4, 1/16)}

I guess my original problem can be fixed by passing a list of known, constrained SymPy symbols symbolics_to_sympy(expr, symbols::Vector{Sym}=[]) and using them if necessary.

@ChrisRackauckas
Copy link
Member

It would probably be good for those values to be stored in the variable metadata.

@variables x [positive = true]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants