how to solve 'Expect x to not have duplicates' with scipy? - python

i was trying to make curve as follows:
x = all_dat['rcs']
y = all_dat['Mean_Range']
xnew = np.linspace(x.min(), x.max(), 200)
cubic_interploation_model = interp1d(x, y, kind = "cubic")
y_=cubic_interploation_model(xnew)
pl.plot(xnew , y_)
but i was not getting a plot and end with an error:
Traceback (most recent call last):
File "C:\Users\xxx\PycharmProjects\pythonProject1\seq_2_final.py", line 268, in <module>
plot_alldata(df_all,p2)
File "C:\Users\xxx\PycharmProjects\pythonProject1\seq_2_final.py", line 201, in plot_alldata
cubic_interploation_model = interp1d(x, y, kind = "cubic")
File "C:\Users\xxx\PycharmProjects\pythonProject1\venv\lib\site-packages\scipy\interpolate\_interpolate.py", line 564, in __init__
self._spline = make_interp_spline(xx, yy, k=order,
File "C:\Users\xxx\PycharmProjects\pythonProject1\venv\lib\site-packages\scipy\interpolate\_bsplines.py", line 1295, in make_interp_spline
raise ValueError("Expect x to not have duplicates")
ValueError: Expect x to not have duplicates
Process finished with exit code 1
How to solve this issue?

Related

matplotlib's contourf producing error in tikzplotlib

could someone point out to what is wrong with the following code?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm,colors
import tikzplotlib
max_r = 20
N_vorfs = 500
scalings = np.linspace(0.1, 5.*np.pi, N_vorfs)
X, Y = np.meshgrid(scalings, 2.*np.arange(1, max_r+1)-1.)
Z = np.arange(max_r*N_vorfs).reshape(X.shape)
fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]})
axs[0].contour(X, Y, Z)
print(tikzplotlib.get_tikz_code())
plt.show()
I get errors from tikzplotlib, namely
Traceback (most recent call last):
File ".../to_pgfplot.py", line 19, in <module>
print(tikzplotlib.get_tikz_code())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 209, in get_tikz_code
data, content = _recurse(data, figure)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 353, in _recurse
data, children_content = _recurse(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 378, in _recurse
data, cont = _draw_collection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 319, in _draw_collection
return _path.draw_pathcollection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_path.py", line 214, in draw_pathcollection
p = obj.get_paths()[0]
IndexError: list index out of range

Plot a function with telegram bot (python, matplotlib)

I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this.
My code
import telebot
import matplotlib.pyplot as plt
import numpy as np
...
def plot_func(message):
x = np.linspace(-5,5,100)
y = message.text # <-- here is something wrong I supppose
plt.plot(x, y, 'r')
plt.savefig('plot_name.png', dpi = 300)
bot.send_photo(message.chat.id, photo=open('plot_name.png', 'rb'))
#plt.show()
Main idea
User send function, bot plot it and send image back:
ERROR
/home/anmnv/Desktop/news_scrapper_bot/bot.py:148: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
plt.plot(x, y, 'r')
Traceback (most recent call last):
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 424, in <module>
bot.polling(none_stop=True)
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1047, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1122, in __threaded_polling
raise e
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1078, in __threaded_polling
self.worker_pool.raise_exceptions()
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 154, in raise_exceptions
raise self.exception_info
File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 98, in run
task(*args, **kwargs)
File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 148, in plot_func
plt.plot(x, y, 'r')
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2730, in plot
return gca().plot(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1662, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 311, in __call__
yield from self._plot_args(
File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 504, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (100,) and (1,)
Thank you in advance
Assuming message.text contains the string 'x**2', you can use numexpr.evaluate to convert to numpy array:
import numexpr
import matplotlib.pyplot as plt
x = np.linspace(-5, 5, 100)
y = numexpr.evaluate(message.text) # message.text = 'x**2'
plt.plot(x, y, 'r')
Output:

How to symbolize / compile the following sympy code that throws ValueError: Can't determine orientation

I have this bit of code for calculating the internal angles of a polygon using sympy -
pt1 = sympy.Point((0, 0))
pt2 = sympy.Point((1, 1))
pt3 = sympy.Point((0, 1))
pt4 = sympy.Point((1, 0))
poly = sympy.Polygon(pt1, pt2, pt3, pt4)
print(poly.angles[pt2])
5.49778714378214
How do I lambdify this code?
I get the following error when I replace the numeric values with symbols -
pt1 = sympy.Point(*sympy.symbols("x0 y0"))
pt2 = sympy.Point(*sympy.symbols("x1 y1"))
pt3 = sympy.Point(*sympy.symbols("x2 y2"))
pt4 = sympy.Point(*sympy.symbols("x3 y3"))
poly = sympy.Polygon(pt1, pt2, pt3, pt4)
angles = poly.angles[pt2]
sympy.lambdify(
sympy.symbols("x0 y0")
+ sympy.symbols("x1 y1")
+ sympy.symbols("x2 y2")
+ sympy.symbols("x3 y3"),
angles,
)
Traceback (most recent call last):
File "/Users/dev/.virtualenvs/ddgai-b0692ca2/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 564, in _run_script
exec(code, module.__dict__)
File "/Users/dev/Projects/dara/ddgai/pages/Pad.py", line 111, in <module>
angles = poly.angles[pt2]
File "/Users/dev/.virtualenvs/ddgai-b0692ca2/lib/python3.10/site-packages/sympy/geometry/polygon.py", line 266, in angles
cw = self._isright(args[-1], args[0], args[1])
File "/Users/dev/.virtualenvs/ddgai-b0692ca2/lib/python3.10/site-packages/sympy/geometry/polygon.py", line 231, in _isright
raise ValueError("Can't determine orientation")
ValueError: Can't determine orientation

basemap.maskoceans: 'float' object cannot be interpreted as an integer

I'm getting the error:
TypeError: 'float' object cannot be interpreted as an integer
when I call maskoceans. Why is this? I'm running python3.
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.basemap import maskoceans
from mpl_toolkits.basemap import interp
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
import numpy as np
places = {
(-8.91508040128176, 52.23826465): 0,
(-6.45854802816101, 52.64127685): 21,
(-9.03867527891856, 52.78809005): 0,
(-8.70926037608263, 53.717247): 0,
(-6.8217677, 54.3303964): 0,
(-6.1658125, 53.5255827): 4
}
m = Basemap(llcrnrlon=-10.56, llcrnrlat=51.39, urcrnrlon=-5.34, urcrnrlat=55.43,
lat_1=30., lat_2=60., lat_0=53.41, lon_0=-7.95,
resolution="i")
x, y, values = np.array([(x, y, v) for (x, y), v in places.items()]).T
coords = np.stack((x, y)).T
x, y = np.mgrid[-11:-4:10j, 51:56:10j]
z = griddata(coords, values, (x, y), method='nearest')
mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True)
plt.contour(x[:,0], x[0,:], mdata.T,linewidths=0.5,colors='k',z=99)
plt.contourf(x[:,0], y[0,:], mdata.T,cmap=plt.cm.Purples, z=100)
Here's the full stacktrack:
Traceback (most recent call last):
File "plot.py", line 28, in <module>
mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5107, in maskoceans
_readlsmask(lakes=inlands,resolution=resolution,grid=grid)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5132, in _readlsmask
np.reshape(np.fromstring(lsmaskf.read(),dtype=np.uint8),(nlats,nlons))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 257, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 62, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 42, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: 'float' object cannot be interpreted as an integer
If you use Python3, you need to do a simple change to this file:
"your_python3_install_directory/lib/python3.x/site-packages/mpl_toolkits/basemap/init.py"
Between line 5125 and 5130, find "nlats = nlons/2" and change it to "nlats = nlons//2".
This should solve the problem.

i have error in code when i use basin hopping scipy

I don't know why this probelm , all the time the varaiable of parameters out of range , and now also the problem is for code and give me this eroor object of type 'Bounds' has no len():
(I hope i can find the error in my code or find other good code for using bounds of variabels)
Traceback (most recent call last):
File "./trigger_SLQ.py", line 160, in <module>
main()
File "./trigger_SLQ.py", line 156, in main
opt(x0)
File "./trigger_SLQ.py", line 148, in opt
res = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs, T=10000.0,
stepsize=1.0, niter=100, niter_success=200, accept_test=bounds)
File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line
611, in basinhopping
accept_tests, disp=disp)
File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line
72, in __init__
minres = minimizer(self.x)
File "/usr/lib/python3/dist-packages/scipy/optimize/_basinhopping.py", line
280, in __call__
return self.minimizer(self.func, x0, **self.kwargs)
File "/usr/lib/python3/dist-packages/scipy/optimize/_minimize.py", line 455,
in minimize
constraints, callback=callback, **options)
File "/usr/lib/python3/dist-packages/scipy/optimize/slsqp.py", line 329, in
_minimize_slsqp
if bounds is None or len(bounds) == 0:
TypeError: object of type 'Bounds' has no len()
I use this code
b0 = (5, 95)
b1 = (0.10, 0.95)
b2= (2, 8)
bounds=((5, 95), (0.10, 0.95), (2, 8))
class Bounds(object):
def __init__(self, xmax=[0,0,2], xmin=[100,0.100,8], stepsize=0.01):
self.xmax = np.array(xmax)
self.xmin = np.array(xmin)
self.stepsize = stepsize
def __call__(self, x):
min_step = np.maximum(self.xmin - x, -self.stepsize)
max_step = np.minimum(self.xmax - x, self.stepsize)
random_step = np.random.uniform(low=min_step, high=max_step, size=x.shape)
xnew = x + random_step
return xnew
bounded_step = Bounds(np.array([b[0] for b in bounds]), np.array([b[1]
for b in bounds]), np.array([b[2] for b in bounds]))
def opt(x0):
bounds = Bounds()
minimizer_kwargs = {'method':'SLSQP', 'bounds':bounds,'options':{'maxiter':1000, 'ftol':1e-2, 'eps':1e-2},}
res = basinhopping(rmse, x0, minimizer_kwargs=minimizer_kwargs, T=10000.0, stepsize=1.0, niter=100, niter_success=200, accept_test=mybounds)
print(res.x)
return res.x
def main():
x0 = np.array((50.0, 0.50, 5.0)) # initial guess
opt(x0)
if __name__ == "__main__":
main()

Categories

Resources