Python ode first order, how to solve this using Sympy - ode

When I try to solve this first ode by using Sympy as it shows below:
import sympy
y = sympy.Function('y')
t = sympy.Symbol('t')
ode = sympy.Eq(y(t).diff(t),(1/y(t))*sympy.sin(t))
sol = sympy.dsolve(ode,y(t))
csol=sol.subs([(t,0),(y(0),-4)]) # the I.C. is y(0) = 1
ode_sol= sol.subs([(csol.rhs,csol.lhs)])
print(sympy.pprint(ode_sol))
It gives me this error:
Traceback (most recent call last):
File "C:/Users/Mohammed Alotaibi/AppData/Local/Programs/Python/Python35/ODE2.py", line 26, in <module>
csol=sol.subs([(t,0),(y(0),-4)]) # the I.C. is y(0) = 1
AttributeError: 'list' object has no attribute 'subs'

Your problem is that this ODE does not have a unique solution. Thus it returns a list of solution, which you can find out from the error message and by printing sol.
Do the evaluation in a loop,
for psol in sol:
csol = psol.subs([(t,0),(y(0),-4)]);
ode_sol = psol.subs([(csol.rhs,csol.lhs)]);
print(sympy.pprint(ode_sol))
to find the next error, that substituting does not solve for the constant. What works is to define C1=sympy.Symbol("C1") and using
ode_sol= psol.subs([(C1, sympy.solve(csol)[0])]);
but this still feels hacky. Or better to avoid error messages for the unsolvability of the second case:
C1=sympy.Symbol("C1");
for psol in sol:
csol = psol.subs([(t,0),(y(0),-4)]);
for cc1 in sympy.solve(csol):
ode_sol= psol.subs([(C1, cc1)]);
print(sympy.pprint(ode_sol))

Related

Multiclass confusion matrix problem ValueError: multilabel-indicator is not supported

I have successfully created a pytorch NN with 10 inputs and two output classes (B & S). So B is either 0 or 1, and S is either 0 or 1. So Y_test is B(0),B(1),S(0),S(1). Y_Pred will output B(0...1) and S(0...1). The net trains without error...
Now I want to create a confusion matrix and I am confused.
This is my code:
cm = confusion_matrix(y_test, y_pred)
print (cm)
It generates this error message:
"Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/3_indexes_NN/3_indexes_NN.py", line 386, in "
[line 386 is cm = confusion_matrix(y_test, y_pred)]
cm = confusion_matrix(y_test, y_pred)
File "C:\Users\user\anaconda3\envs\PIMA\lib\site-packages\sklearn\metrics_classification.py", line 309, in confusion_matrix
raise ValueError("%s is not supported" % y_type)
ValueError: multilabel-indicator is not supported
I am completely lost. Can anyone help me understand where I've gone wrong?
Thank you in advance for throwing me a life-line!!
Can both S and B be 1 simultaneously? In this case, this is indeed a multilabel task, making confusion matrix an unsuitable metric.
Otherwise, you may work it around using something like y_pred.argmax(axis=1) for both.

Repost: Discord.py & Sympy(mostly discord.py I think)

I'm trying to make a math discord bot.
I am pretty sure that my Sympy code is correct and it is just discord.py being funky.
Code:
#client.command()
async def solve(ctx, equation):
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
equation = equation.split("=")
eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
await ctx.send(f"```{solve(eqn)}```")
Please assume that I have all imports necessary.
I am getting this error:
Ignoring exception in command solve:
Traceback (most recent call last):
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "math.py", line 42, in solve
eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\sympy\parsing\sympy_parser.py", line 1008, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\sympy\parsing\sympy_parser.py", line 902, in eval_expr
expr = eval(
File "<string>", line 1
Integer (2 )+Integer (3 )Symbol ('x' )
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SyntaxError: invalid syntax (<string>, line 1)
Judging from the error you are getting, the problem is not from discord.py, it comes from sympy. And judging at the output of the code it has to do with the way you are introducing the parameter equation.
I did the following calls in SymPy Live and it outputted well:
>>> from sympy.parsing.sympy_parser import parse_expr
>>> equation = 'x+1 = 0'
>>> equation = equation.split('=')
>>> eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
>>> print(eqn)
Eq(x + 1, 0)
In your code, however, it is telling you that the parse_expr cannot evaluate the expression correctly due to the syntax being introduced. Make sure your input equation has a valid format.

Pyautogui and pyscreeze crash with windll.user32.ReleaseDC failed

I'm trying to compare certain pixel values in my pyautogui script, but it crashes with following error message after either multiple successful runs, or sometimes just straight on the first call:
Traceback (most recent call last):
File "F:\Koodit\Python\HeroWars NNet\Assets\autodataGet.py", line 219, in <module>
battle = observeBattle()
File "F:\Koodit\Python\HeroWars NNet\Assets\autodataGet.py", line 180, in observeBattle
statii = getHeroBattlePixels()
File "F:\Koodit\Python\HeroWars NNet\Assets\autodataGet.py", line 32, in getHeroBattlePixels
colormatch = pyautogui.pixelMatchesColor(location[0], location[1], alive, tolerance=5)
File "E:\Program Files\Python\lib\site-packages\pyscreeze\__init__.py", line 557, in pixelMatchesColor
pix = pixel(x, y)
File "E:\Program Files\Python\lib\site-packages\pyscreeze\__init__.py", line 582, in pixel
return (r, g, b)
File "E:\Program Files\Python\lib\contextlib.py", line 120, in __exit__
next(self.gen)
File "E:\Program Files\Python\lib\site-packages\pyscreeze\__init__.py", line 111, in __win32_openDC
raise WindowsError("windll.user32.ReleaseDC failed : return 0")
OSError: windll.user32.ReleaseDC failed : return 0
My code (this is called multiple times, sometimes it crashes on first run, sometimes it runs nicely for around 100 calls before failing, also, my screen is 4K, so the resolutions get big):
def getSomePixelStatuses():
someLocations= [
[1200, 990],
[1300, 990],
[1400, 990],
[1500, 990],
[1602, 990],
[1768, 990],
[1868, 990],
[1968, 990],
[2068, 990],
[2169, 990]
]
status = []
someValue= (92, 13, 12)
for location in someLocations:
colormatch = pyautogui.pixelMatchesColor(location[0], location[1], someValue, tolerance=5)
status.append(colormatch)
return status
I have no idea how to mitigate this problem. It would seem that pyautogui uses pyscreeze to read pixel values on screen, and most probable candidate for the place where error occurs is the pyscreeze pixel function:
def pixel(x, y):
"""
TODO
"""
if sys.platform == 'win32':
# On Windows, calling GetDC() and GetPixel() is twice as fast as using our screenshot() function.
with __win32_openDC(0) as hdc: # handle will be released automatically
color = windll.gdi32.GetPixel(hdc, x, y)
if color < 0:
raise WindowsError("windll.gdi32.GetPixel failed : return {}".format(color))
# color is in the format 0xbbggrr https://msdn.microsoft.com/en-us/library/windows/desktop/dd183449(v=vs.85).aspx
bbggrr = "{:0>6x}".format(color) # bbggrr => 'bbggrr' (hex)
b, g, r = (int(bbggrr[i:i+2], 16) for i in range(0, 6, 2))
return (r, g, b)
else:
# Need to select only the first three values of the color in
# case the returned pixel has an alpha channel
return RGB(*(screenshot().getpixel((x, y))[:3]))
I installed these libraries just yesterday, and I'm running python 3.8 on windows 10, and pyscreeze is version 0.1.25 so in theory everything should be up to date, but somehow something ends up crashing. Is there a way to mitigate this, either modifying my code, or even the library itself, or is my environment not suitable for this operation?
Well I know it's not particularly helpful; but for me, this error was fixed simply by running my code on 3.7 instead of 3.8. There shouldn't be any changes you have to make to your code, however (unless you were using walrus!)
On Windows, this can be done with the -3.7 command line flag, as long as 3.7 is installed
PyScreeze and PyAutoGUI maintainer here. This is an issue that has been fixed in PyScreeze 0.1.28, so you just need to update it by running pip install -U pyscreeze.
For more context, here's the GitHub issue where it was reported: https://github.com/asweigart/pyscreeze/pull/73
It's a bug. You were on the right track, as the problem is indeed in this line of the pixel() function:
with __win32_openDC(0) as hdc
That function uses cyptes.windll which doesn't seem to do well with the negative values sometimes returned from windll.user32.GetDC(), which subsequently creates an exception when windll.user32.ReleaseDC() is called.
The folks at pillow helped track this down and propose a fix.
issue filed at pyautogui
issue filed at pillow which led to the solution
pending PR at pyscreeze to address
I can use pixel function on Python 3.8 like this:
try:
a = pixel(100,100)
> except:
> a = pixel(100,100)
I don't have any clue why this works, but it works.
I had this error too and i fixed it. Just use try and except.
While true:
try:
x,y = pyautogui.position()
print(pyautogui.pixel(x,y))
except:
print("Cannot get pixel for the moment")
Given that you might be taking pixels multiple times, or you can do so, try and except works wonders to solve any pyscreeze for pyautogui issue. Honestly i dont know whats up with pyscreeze, but this works for me. Cheers

h2o set_params() takes exactly 1 argument (2 given), even though only 1 given?

Getting error
TypeError: set_params() takes exactly 1 argument (2 given)
even though I only appear to be providing a single argument...
HYPARAMS = {
unicode(HYPER_PARAM): best_random_forest.params[unicode(HYPER_PARAM)][u'actual']
for HYPER_PARAM in list_of_hyperparams_names
}
assert isinstance(HYPARAMS, dict)
print 'Setting optimal params for full-train model...'
pp.pprint(HYPARAMS)
model = model.set_params(HYPARAMS)
#output
{ u'col_sample_rate_per_tree': 1.0,
u'max_depth': 3,
u'min_rows': 1024.0,
u'min_split_improvement': 0.001,
u'mtries': 5,
u'nbins': 3,
u'nbins_cats': 8,
u'ntrees': 8,
u'sample_rate': 0.25}
model = model.set_params(OPTIM_HYPARAMS)
TypeError: set_params() takes exactly 1 argument (2 given)
Looking at the source code,
def set_params(self, **parms):
"""Used by sklearn for updating parameters during grid search.
Parameters
----------
parms : dict
A dictionary of parameters that will be set on this model.
Returns
-------
Returns self, the current estimator object with the parameters all set as desired.
"""
self._parms.update(parms)
return self
there does not appear to be much going on that I see could go wrong. Anyone know what I'm missing here or what is happening to cause this error?
TLDR: Need to unpack the keys/values as **kwargs keywords in order to get the expected behavior of updating the _parms dict. So do
model = model.set_params(**HYPARAMS) #see https://stackoverflow.com/a/22384521/8236733
Example:
# here's a basic standin for the set_params method
>>> def kfunc(**parms):
... print parms
...
# what I was doing
>>> kfunc({1:2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# and also tried
>>> kfunc(parms={1:2})
{'parms': {1: 2}}
>>> kfunc({u'1':2, u'2':3})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# what should have been done
>>> kfunc(**{'1':2})
{'1': 2}
>>> kfunc(**{u'1':2, u'2':3})
{u'1': 2, u'2': 3}
Can now see that this is not directly related to h2o, but keeping post up anyway so others with this problem may find, since did not immediately think to do this from just reading the popup docs for the method (and also since the other SE post commented in the example that I used to actually use variables as **kwarg keywords was not even on the first page of a Google search of "How to use python variable as keyword for kwargs parameter?" so would like to add more avenues to it).

fenics did not show figure . NameError: name interactive is not defined

I installed fenics on windows subsystem for linux to do my homework.I am trying to test fenics. So I use ft01_possion.py on the tutorial.
from fenics import *
# Create mesh and define function space
mesh = UnitSquareMesh(8, 8)
V = FunctionSpace(mesh, 'P', 1)
# Define boundary conditions
u_D = Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree = 2)
def boundary(x, on_boundary):
return on_boundary
bc = DirichletBC(V, u_D, boundary)
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(-6.0)
a = dot(grad(u), grad(v))*dx
L = f*v*dx
# Compute solution
u = Function(V)
solve(a == L, u, bc)
# Plot solution and mesh
plot(u)
plot(mesh)
interactive()
It did not show the figure.
the error i am getting is:
Solving linear variational problem.
Traceback (most recent call last):
File "ft01_poisson.py", line 29, in <module>
interactive()
NameError: name 'interactive' is not defined
I have tried to reinstall the newest version of fenics without success.
While the print out of the error values work, the NameError prevents the plots from being shown.
Some Fenics examples are unfortunately out of date. Please see the following GitHub post.
Change 'interactive()' to
import matplotlib.pyplot as plt
plt.show()
this will show your results.
Errors are shown as follows:
error_L2 = 0.008235098073354827
error_max = 1.3322676295501878e-15
But there is :NameError: name 'interactive' is not defined, probably this error is not affecting the results

Resources