Python SymPy solving linear system - python

I have Python 3.3.3 and SymPy 0.7.4.1, both in x64 version and installed locally on my computer. I am using PSPad as a configured editor for Python scripting.
When using imports from library sympy in a module which should solve a set of three linear equations:
from sympy import Matrix, solve_linear_system
from sympy.abc import x, y, z
def main():
system = Matrix (((3,2,-1,1) ,(2,-2,4,-2),(-1,0.5,-1,0)))
print(solve_linear_system(system, x, y,z))
if __name__ == "__main__":
main()
The editor PSPad console output returns the following:
traceback (most recent call last): File "C:\Users\GOODLU~1\AppData\Local\Temp\PSpad\securesafety_DISK_5GB\Programmation\linear system solve SYMPY.py", line 1, in <module>
from sympy import Matrix,solve_linear_system File "C:\Users\GOODLU~1\AppData\Local\Temp\PSpad\securesafety_DISK_5GB\Programmation\sympy.py", line 2, in <module>
from sympy import var,Eq,solve ImportError: cannot import name var
Process completed, Exit Code 1.
Execution time: 00:00.134
Actually, I am wondering myself heavily about those issues:
Why, when typing the same thing, without an object def main(), and entered line by line in IDLE, everything is solved correctly, as: {x: 1.00000000000000, y: -2.00000000000000, z: -2.00000000000000}
Why, my PSPad file with object, having the same computation lines, doesn't work and returns errors?
In fact, I would like to use SymPy in normal python code and get computed results in a list or printed in console( .. as in IDLE). Just in order to avoid some annoying line-to-line IDLE manipulations, what should my code file look like?

The problem seems to be that you have created a file named sympy.py, which has the same name as the sympy module.
Hence, in the from sympy import ... statement, your sympy.py is acting as the sympy module.
Try renaming the file to something else, like sympy_programming_test.py and let know if it works.

Related

Python IDLE doesn't recognize numpy functions

A very simple thing - I downloaded python 3.8 and installed numpy. Upon making a very basic program that uses a numpy function, I get an error. I captured all the info that I think is relevant for now:
Traceback (most recent call last):
File "C:/Python/numpytest.py", line 6, in <module>
a=sigmoid(2)
File "C:/Python/numpytest.py", line 4, in sigmoid
return 1/(1+exp(-x))
NameError: name 'exp' is not defined
I'm guessing it isn't even importing numpy but no idea why.
Use np.exp(x) to access Numpy's exp() function.
Otherwise, import Numpy as:
from numpy import *
to use exp() without any prefix.
For example,
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
a=sigmoid(2)
print(a)
You need to call the np class then the exp function
Also, it is better to copy the text rather than take a picture of it.

What is wrong with my call to checkodesol in sympy?

I am learning sympy, and wanted to verify the solution to an ODE. I do not yet quite understand sympy naming conventions.
Instead of doing the standard methods of loading all packages at the top, I wanted to just import sympy and then use explicit long name to reference any other name inside sympy. On latest conda python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
When typing
import sympy
x = sympy.symbols('x')
y = sympy.Function('y')
ode = sympy.Eq(sympy.Derivative(y(x),x),1+2*x)
sol = sympy.dsolve(ode,y(x))
sympy.solvers.ode.checkodesol(ode,sol)
And the above gives error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'sympy.solvers.solvers' has no attribute 'ode'
But from the page https://docs.sympy.org/latest/modules/solvers/ode.html
It says
But if I do the following, it works
from sympy import checkodesol
checkodesol(ode,sol)
(True, 0)
But I do not want to import checkodesol explicitly. I want to just import sympy and then use the long name to call checkodesol or any other sympy sub packages, as this makes it more clear to me in the code where each function is coming from (at the cost of a little extra typing)
The question is, why using sympy.solvers.ode.checkodesol does not work?
At the very top of the documentation you linked to, it says
These are functions that are imported into the global namespace with
from sympy import *. These functions (unlike Hint Functions, below)
are intended for use by ordinary users of SymPy.
Then you can use checkodesol(ode, sol) directly.
If you do import sympy, then you need to call
sympy.checkodesol(ode, sol)

Access to mpmath module in sympy (python)

I am new to sympy and still naive about python.... I wanted to solve a trigonometric equation, to find its zeroes. (Once I have syntax, then I will use a more complex function.)
I cannot find the right syntax yet. Here is what I tried at the iPython console in Spyder (Python 2.7):
from sympy.solvers import solve
from sympy import Symbol
x = Symbol('x')
solve(sin(x), x)
I got this error:
Traceback (most recent call last):
File "", line 1, in
solve(sin(x), x)
NameError: name 'sin' is not defined
OK, so I need to have the correct reference to the sine function.
According to the sympy documentation, I thought this was in mpath, but this did not work:
from mpmath import *
Traceback (most recent call last):
File "<ipython-input-7-8dcdd12d9679>", line 1, in <module>
from mpmath import *
ImportError: No module named mpmath
How do I load/access mpmath or some other way to get the sine function?
This fixed it:
from sympy import sin
To access mpmath do this
from sympy.mpmath import *

NameError: global name 'imshow' is not defined but Matplotlib is imported

I'm currently writing a python script which plots a numpy matrix containing some data (which I'm not having any difficulty computing). For complicated reasons having to do with how I'm creating that data, I have to go through terminal. I've done problems like this a million times in Spyder using imshow(). So, I thought I'd try to do the same in terminal. Here's my code:
from numpy import *
from matplotlib import *
def make_picture():
f = open("DATA2.txt")
arr = zeros((200, 200))
l = f.readlines()
for i in l:
j = i[:-1]
k = j.split(" ")
arr[int(k[0])][int(k[1])] = float(k[2])
f.close()
imshow(arr)
make_picture()
Suffice it to say, the array stuff works just fine. I've tested it, and it extracts the data perfectly well. So, I've got this 200 by 200 array of numbers floating around my RAM and I'd like to display it. When I run this code in Spyder, I get exactly what I expected. However, when I run this code in Terminal, I get an error message:
Traceback (most recent call last):
File "DATAmine.py", line 15, in <module>
make_picture()
File "DATAmine.py", line 13, in make_picture
imshow(arr)
NameError: global name 'imshow' is not defined
(My program's called DATAmine.py) What's the deal here? Is there something else I should be importing? I know I had to configure my Spyder paths, so I wonder if I don't have access to those paths or something. Any suggestions would be greatly appreciated. Thanks!
P.S. Perhaps I should mention I'm using Ubuntu. Don't know if that's relevant.
To make your life easier you can use
from pylab import *
This will import the full pylab package, which includes matplotlib and numpy.
Cheers

pymc.NormApprox unexpected behavior - unable to see mu and C and nuking of namespace

I am new to pymc and enjoying it but have run into some very strange behavior. I want to use it to track something moving; following the tutorials I set up some stochastics and attempted to use pymc.NormApprox() on it. fit() seems to run but when I try to get the output out it gives me KeyError. When I switch to using pymc.MCMC it runs `sample() OK but then nukes the namespace (Python even forgets how to exit()).
System: Ubuntu 12.04, scipy numpy etc installed, pymc installed via easy_install; also tried from git.
Code to reproduce:
test.py::
import pymc
import numpy as np
x = pymc.MvNormal('x',mu=np.zeros(4),tau=np.eye(4))
#pymc.deterministic()
def y(x=x):
out = np.zeros(2)
out[0] = x[0]+x[2]
out[1] = x[1]+x[3]
return out
ymeas = pymc.MvNormal('ymeas',mu=y,tau=np.eye(2)*100000,value=20*np.ones(2),observed=True)
Then, in a shell running python or ipython::
import test
import pymc
foo = pymc.NormApprox(test)
foo.fit()
foo.mu[foo.x] # Fails - gives KeyError
foo._mu # I can see it OK if I break privacy rules
foo = pymc.MCMC(test)
foo.sample(10000) # runs OK
foo # fails - namespace is nuked
What I expect to see:
foo.mu[foo.x] should give me the normal approx to the posterior; I shouldn't get a Key error and shouldn't have to break into foo._mu
instead I get:
>>> foo.mu[foo.x]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymc-2.2-py2.7-linux-x86_64.egg/pymc/NormalApproximation.py", line 56, in __getitem__
tot_len += self.owner.stochastic_len[p]
KeyError: 9.9999517411499177
>>> foo._mu
array([ 9.99995174, 9.99997163, 10.0000485 , 10.00002837])
>>>
Also I noticed that the docstring for foo.mu says N.mu(p1,p2) but the online documentation says N.mu[N.p1,N.p2].
As for the post- MCMC namespace meltdown, it even forgets how to exit()
Also I can confirm that I get the same problem on a different machine (MacBook Pro) running a different installation (Enthought Python).

Categories