Fixed_quad Error With Functions - python

Keeping it simple:
----------------------------------
from mpmath import *
from scipy.integrate import *
mp.dps=30
def F(x):
return Q**(x)
Q=735
print fixed_quad(F,0,1,n=1)[0]
print fixed_quad(F,0,1,n=2)[0]
print fixed_quad(F,0,1,n=3)[0]
--------------------
returns
27.1108834235
93.1213589089
109.673420158
However, if I change F(x) from “Q**(x)” to even just a simple function—e.g., “cos(x)”—I get
--------------------
Traceback (most recent call last):
File "Test.py", line 7, in <module>
print fixed_quad(F,0,1,n=1)[0]
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadrature.py", line 67, in fixed_quad
return (b-a)/2.0*sum(w*func(y,*args),0), None
File "Test.py", line 5, in F
return cos(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 984, in f
x = ctx.convert(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 662, in convert
return ctx._convert_fallback(x, strings)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp.py", line 614, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from array([ 0.5])
Is this some known bug? Or is “fixed_quad” only meant for certain uses, not general integration (like “trapz”)?
All of the other regulars (“quad”, “dblquad”, “tplquad”, “nquad”) donʼt seem to have that problem/error.

Related

'NoneType' object has no attribute 'eglGetCurrentContext'

I am having a problem with python and pyopengl
I am just importing the modules, and getting errors, I checked and pip did install opengl and everything.
Here is my code
# ulWindow
import ulMath as ulm
import OpenGL.GL as gl
import OpenGL.GlE as gle
import glfw
def init() ->int|str:
if (not glfw.init()):
return "GLFW Failed to initialize"
return 0
And the error im getting:
Traceback (most recent call last):
File "src/ulWindow.py", line 3, in <module>
import OpenGL.GL as gl
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/GL/__init__.py", line 4, in <module>
from OpenGL.GL.VERSION.GL_1_1 import *
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/GL/VERSION/GL_1_1.py", line 14, in <module>
from OpenGL.raw.GL.VERSION.GL_1_1 import *
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/raw/GL/VERSION/GL_1_1.py", line 7, in <module>
from OpenGL.raw.GL import _errors
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/raw/GL/_errors.py", line 4, in <module>
_error_checker = _ErrorChecker( _p, _p.GL.glGetError )
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/error.py", line 183, in __init__
self._isValid = platform.CurrentContextIsValid
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 356, in CurrentContextIsValid
return self.GetCurrentContext
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/baseplatform.py", line 15, in __get__
value = self.fget( obj )
File "/home/jack3/.local/lib/python3.8/site-packages/OpenGL/platform/egl.py", line 106, in GetCurrentContext
return self.EGL.eglGetCurrentContext
AttributeError: 'NoneType' object has no attribute 'eglGetCurrentContext'
I have absolutely no clue what is going on, can someone help me out?

Sympy not able to calculate minimum of a cubic root with an interval set

So I was working on a project and I came across this error related to sympy:
Traceback (most recent call last):
File "c:\Users\Andres\OneDrive - Centre d'Estudis Monlau\z.ottro\final program try 1\testing area 2.py", line 4, in <module>
Ymin = minimum(root(x,3), x, domain=Interval(-7,7))
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\calculus\util.py", line 837, in minimum
return function_range(f, symbol, domain).inf
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\calculus\util.py", line 220, in function_range range_int += Interval(vals.inf, vals.sup, left_open, right_open)
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\sets\sets.py", line 274, in inf
return self._inf
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\sets\sets.py", line 1910, in _inf
return Min(*self)
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\functions\elementary\miscellaneous.py", line 391, in __new__
args = frozenset(cls._new_args_filter(args))
File "C:\Users\Andres\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\functions\elementary\miscellaneous.py", line 564, in _new_args_filter
raise ValueError("The argument '%s' is not comparable." % arg)
ValueError: The argument '(-7)**(1/3)' is not comparable.
I was able to isolate where happened and recreate the error with these lines:
from sympy import *
x = Symbol("x")
Ymin = minimum(root(x,3), x, domain=Interval(-7,7))
I'm not undrestanding why it's happening, as when is root(x,2) it doasn't have this problem. Does anyone have a clue?
Okey i found an answer online posted by user6655984(stackoverflow) and i wanted to share it online:
expression = root(Abs(x), 3)*sign(x)

Shorten large stack traces when using libraries

I work very often with large libraries like pandas, or matplotlib.
This means that exceptions often produce long stack traces.
Since the error is extremely rarely with the library, and extremely often with my own code, I don't need to see the library detail in the vast majority of cases.
A couple of common examples:
Pandas
>>> import pandas as pd
>>> df = pd.DataFrame(dict(a=[1,2,3]))
>>> df['b'] # Hint: there _is_ no 'b'
Here I've attempted to access an unknown key. This simple error produces a stacktrace containing 28 lines:
Traceback (most recent call last):
File "an_arbitrary_python\lib\site-packages\pandas\core\indexes\base.py", line 2393, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'b'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "an_arbitrary_python\lib\site-packages\pandas\core\frame.py", line 2062, in __getitem__
return self._getitem_column(key)
File "an_arbitrary_python\lib\site-packages\pandas\core\frame.py", line 2069, in _getitem_column
return self._get_item_cache(key)
File "an_arbitrary_python\lib\site-packages\pandas\core\generic.py", line 1534, in _get_item_cache
values = self._data.get(item)
File "an_arbitrary_python\lib\site-packages\pandas\core\internals.py", line 3590, in get
loc = self.items.get_loc(item)
File "an_arbitrary_python\lib\site-packages\pandas\core\indexes\base.py", line 2395, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'b'
Knowing that I ended up in hashtable_class_helper.pxi is almost never helpful for me. I need to know where in my code I've messed up.
Matplotlib
>>> import matplotlib.pyplot as plt
>>> import matplotlib.cm as cm
>>> def foo():
... plt.plot([1,2,3], cbap=cm.Blues) # cbap is a typo for cmap
...
>>> def bar():
... foo()
...
>>> bar()
This time, there's a typo in my keyword argument. But I still have to see 25 lines of stack trace:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in bar
File "<stdin>", line 2, in foo
File "an_arbitrary_python\lib\site-packages\matplotlib\pyplot.py", line 3317, in plot
ret = ax.plot(*args, **kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\__init__.py", line 1897, in inner
return func(ax, *args, **kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_axes.py", line 1406, in plot
for line in self._get_lines(*args, **kwargs):
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_base.py", line 407, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_base.py", line 395, in _plot_args
seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\axes\_base.py", line 302, in _makeline
seg = mlines.Line2D(x, y, **kw)
File "an_arbitrary_python\lib\site-packages\matplotlib\lines.py", line 431, in __init__
self.update(kwargs)
File "an_arbitrary_python\lib\site-packages\matplotlib\artist.py", line 885, in update
for k, v in props.items()]
File "an_arbitrary_python\lib\site-packages\matplotlib\artist.py", line 885, in <listcomp>
for k, v in props.items()]
File "an_arbitrary_python\lib\site-packages\matplotlib\artist.py", line 878, in _update_property
raise AttributeError('Unknown property %s' % k)
AttributeError: Unknown property cbap
Here I get to find out that I ended on a line in artist.py that raises an AttributeError, and then see directly underneath that the AttributeError was indeed raised. This is not much value add in information terms.
In these trivial, interactive examples, you might just say "Look at the top of the stack trace, not the bottom", but often my foolish typo has occurred within a function so the line I'm interested in is somewhere in the middle of these library-cluttered stack traces.
Is there any way I can make these stack traces less verbose, and help me find the source of the problem, which almost always lies with my own code and not in the libraries I happen to be employing?
You can use traceback to have better control over exception printing. For example:
import pandas as pd
import traceback
try:
df = pd.DataFrame(dict(a=[1,2,3]))
df['b']
except Exception, e:
traceback.print_exc(limit=1)
exit(1)
This triggers the standard exception printing mechanism, but only shows you the first frame of the stack trace (which is the one you care about in your example). For me this produces:
Traceback (most recent call last):
File "t.py", line 6, in <module>
df['b']
KeyError: 'b'
Obviously you lose the context, which will be important when debugging your own code. If we want to get fancy, we can try and devise a test and see how far the traceback should go. For example:
def find_depth(tb, continue_test):
depth = 0
while tb is not None:
filename = tb.tb_frame.f_code.co_filename
# Run the test we're given against the filename
if not continue_test(filename):
return depth
tb = tb.tb_next
depth += 1
I don't know how you're organising and running your code, but perhaps you can then do something like:
import pandas as pd
import traceback
import sys
def find_depth():
# ... code from above here ...
try:
df = pd.DataFrame(dict(a=[1, 2, 3]))
df['b']
except Exception, e:
traceback.print_exc(limit=get_depth(
sys.exc_info()[2],
# The test for which frames we should include
lambda filename: filename.startswith('my_module')
))
exit(1)

Python, PIL and libtiff issue

When I do general PIL commands in Python, I get such an error message:
>>> im.save('layer_86_.tiff')
TIFFSetField: layer_86_.tiff: Unknown tag 33922.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1685, in save
save_handler(self, fp, filename)
File "C:\Python34\lib\site-packages\PIL\TiffImagePlugin.py", line 1185, in _save
e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 430, in _getencoder
return encoder(mode, *args + extra)
RuntimeError: Error setting from dictionary
I've seen at Github and SO similar questions, that date back to many years ago. But in my case this problem still can be reproduced. I've even installed libtiff.dll and put it in the System32 and SysWOW64 folders, but to no avail. So, how can I fix it?
This is another error message, that I see, when I try to rotate an image:
>>> from PIL import Image
>>> Image.MAX_IMAGE_PIXELS = 100000000000
>>> img = Image.open('layer_71_.tiff')
>>> img.rotate(80,expand=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1603, in rotate
return self.transform((w, h), AFFINE, matrix, resample)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1862, in transform
im.__transformer((0, 0)+size, self, method, data, resample, fill)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1910, in __transformer
image.load()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 245, in load
if not self.map and (not LOAD_TRUNCATED_IMAGES or t == 0) and e < 0:
TypeError: unorderable types: tuple() < int()
So it seems like PIL does not work in many cases.

how to use the post_mortem method of pdb?

I am trying to understand how to use the pdb.post_mortem() method.
for this given file
# expdb.py
import pdb
import trace
def hello():
a = 6 * 9
b = 7 ** 2
c = a * b
d = 4 / 0
print(c)
tracer = trace.Trace()
Command prompt
'''
# first Try
λ python -i expdb.py
>>> pdb.post_mortem()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\pdb.py", line 1590, in post_mortem
raise ValueError("A valid traceback must be passed if no "
ValueError: A valid traceback must be passed if no exception is being handled
'''
'''
# Second Try
λ python -i expdb.py
>>> pdb.post_mortem(traceback=tracer.run('hello()') )
--- modulename: trace, funcname: _unsettrace
trace.py(77): sys.settrace(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Anaconda3\lib\trace.py", line 500, in run
self.runctx(cmd, dict, dict)
File "C:\Program Files\Anaconda3\lib\trace.py", line 508, in runctx
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "expdb.py", line 8, in hello
d = 4 / 0
ZeroDivisionError: division by zero
>>>
The post_mortem method wants a traceback object, not a Trace object. Traceback objects can be acquired from sys.exc_info()[2] inside of an except block, or you can simply call pdb.post_mortem() with no arguments directly (in the except block).
But either way, you must catch the exception before you can debug it.

Categories

Resources