Matplotlib Animation Not Saving - python

I have a Finite Difference Simulation that is plotted with the following command:
anim = ani.FuncAnimation(fig, update, init_func = init, frames = np.linspace(0, t_max, int(t_max / dt + 1)), repeat = False) # repeat = False
plt.show()
This gives a constantly updating figure as expected. However, I would like to try and save this as literally any type of video format, i.e. .gif, .mp4, .mov, and none work.
anim.save("FDA Simulation.gif", writer = 'imagemagick', fps = 30)
The following error is generated:
jacobivanov#Jacob-Ivanovs-MacBook-Air 1D Heat Transfer % /opt/homebr
ew/bin/python3 "/Users/jacobivanov/Desktop/University of Connecticut
/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.
py"
MovieWriter stderr:
convert: unexpected end-of-file '-': No such file or directory # error/rgb.c/ReadRGBImage/249.
convert: no images defined `FDA Simulation.gif' # error/convert.c/ConvertImageCommand/3342.
Traceback (most recent call last):
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 231, in saving
yield self
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 1081, in save
anim._draw_next_frame(d, blit=False)
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 1116, in _draw_next_frame
self._draw_frame(framedata)
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 1743, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
File "/Users/jacobivanov/Desktop/University of Connecticut/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.py", line 96, in update
fig.show()
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/figure.py", line 2632, in show
raise AttributeError(
AttributeError: Figure.show works only for figures managed by pyplot, normally created by pyplot.figure()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/jacobivanov/Desktop/University of Connecticut/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.py", line 112, in <module>
anim.save("FDA Simulation.gif", writer = 'imagemagick', fps = 30)
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 1063, in save
with mpl.rc_context({'savefig.bbox': None}), \
File "/opt/homebrew/Cellar/python#3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 233, in saving
self.finish()
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py", line 347, in finish
raise subprocess.CalledProcessError(
subprocess.CalledProcessError: Command '['convert', '-size', '1280x960', '-depth', '8', '-delay', '3.3333333333333335', '-loop', '0', 'rgba:-', '-layers', 'OptimizePlus', 'FDA Simulation.gif']' returned non-zero exit status 1.
Changing the last line to:
plt.save("FDA Simulation.mov", writer = 'imagemagick', fps = 30)
Outputs this new error:
jacobivanov#Jacob-Ivanovs-MacBook-Air 1D Heat Transfer % /opt/homebr
ew/bin/python3 "/Users/jacobivanov/Desktop/University of Connecticut
/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.
py"
Traceback (most recent call last):
File "/Users/jacobivanov/Desktop/University of Connecticut/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.py", line 112, in <module>
plt.save("FDA Simulation.mov", writer = 'imagemagick', fps = 30)
AttributeError: module 'matplotlib.pyplot' has no attribute 'save'. Did you mean: 'imsave'?
/opt/homebrew/lib/python3.10/site-packages/matplotlib/animation.py:879: UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you output the Animation using `plt.show()` or `anim.save()`.
Changing the last line to:
plt.imsave("/Users/jacobivanov/Desktop/University of Connecticut/Computational Fluid Dynamics Group/1D Heat Transfer/FDA Simulation.gif", anim)
Returns this new error:
jacobivanov#Jacob-Ivanovs-MacBook-Air 1D Heat Transfer % /opt/homebr
ew/bin/python3 "/Users/jacobivanov/Desktop/University of Connecticut
/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.
py"
Traceback (most recent call last):
File "/Users/jacobivanov/Desktop/University of Connecticut/Computational Fluid Dynamics Group/1D Heat Transfer/FDA_Simulation.py", line 109, in <module>
plt.imsave("/Users/jacobivanov/Desktop/University of Connecticut/Computational Fluid Dynamics Group/1D Heat Transfer/FDA Simulation.gif", anim)
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2128, in imsave
return matplotlib.image.imsave(fname, arr, **kwargs)
File "/opt/homebrew/lib/python3.10/site-packages/matplotlib/image.py", line 1633, in imsave
pil_shape = (rgba.shape[1], rgba.shape[0])
AttributeError: 'tuple' object has no attribute 'shape'
I'm not sure how to resolve this, and I've been looking through various Matplotlib animation tutorials without any actual solutions.

Related

pandas causing NoneType error in matplotlib plt.savefig() and plt.show()?

I want to read a csv file using the read_csv method, and then plot the data using matplotlib. However, I cannot seem to create a simple matplotlib plot (even without using the data from the file), after I use pandas to read in some csv data. It gives the error: 'NoneType' object is not callable.
Any idea what's going on here?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("data.csv")
time = [0,10,20]
vel = [0,1,2]
fig,axes = plt.subplots()
axes.plot(time,vel)
plt.show()
plt.savefig(fname = "pic.png" )
I have tried using plot.savefig instead of plot.show() and this produces the same error.
If I move the plotting block of code before the pd.read_csv line, it plots just fine. The error only seems to occur after pandas is used.
This is occuring in Visual Studio. Not occuring in IDLE.
Traceback:
Traceback (most recent call last):
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\numpy\core\getlimits.py", line 384, in __new__
dtype = numeric.dtype(dtype)
TypeError: 'NoneType' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\backends\backend_qt.py", line 455, in _draw_idle
self.draw()
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\backends\backend_agg.py", line 436, in draw
self.figure.draw(self.renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\artist.py", line 73, in draw_wrapper
result = draw(artist, renderer, *args, **kwargs)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\figure.py", line 2803, in draw
mimage._draw_list_compositing_images(
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\image.py", line 132, in _draw_list_compositing_images
a.draw(renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\artist.py", line 50, in draw_wrapper
return draw(artist, renderer)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 3020, in draw
self._unstale_viewLim()
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 776, in _unstale_viewLim
self.autoscale_view(**{f"scale{name}": scale
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 2932, in autoscale_view
handle_single_axis(
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\axes\_base.py", line 2895, in handle_single_axis
x0, x1 = locator.nonsingular(x0, x1)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\ticker.py", line 1654, in nonsingular
return mtransforms.nonsingular(v0, v1, expander=.05)
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\matplotlib\transforms.py", line 2880, in nonsingular
if maxabsvalue < (1e6 / tiny) * np.finfo(float).tiny:
File "C:\Users\user1\AppData\Roaming\Python\Python310\site-packages\numpy\core\getlimits.py", line 387, in __new__
dtype = numeric.dtype(type(dtype))
TypeError: 'NoneType' object is not callable

Why am I receiving this error when using pylab to make a bar graph

I am using data from a file to make a bar graph using pylab. When I run it I get a very long error code.
This is my code.
bar_width=0.5
x_values=[1,2,3,4,5,6,7,8,9,10]
y_values=[3,2,5,7,4,10,12]
tlabel=["0-10", "11-20", "21-30", "31-40", "41-50", "51-60", "61-70", "71-80", "81-90", "Above 90"]
#pylab.xticks(range(6),rotation=30)
pylab.title("Homicide Occurance by Age")
pylab.bar(x_values,y_values,width=bar_width,tick_label=tlabel, align='center',color='b')
pylab.show()
And here is the error message I am receiving.
Traceback (most recent call last):
File "C:\Users\mads\OneDrive\Desktop\CSC 130\prog5.py", line 39, in <module>
pylab.bar(x_values,y_values,width=bar_width,tick_label=tlabel, align='center',color='b')
File "C:\Users\mads\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2487, in bar
return gca().bar(
File "C:\Users\mads\anaconda3\lib\site-packages\matplotlib\__init__.py", line 1447, in inner
return func(ax, *map(sanitize_sequence, args), **kwargs)
File "C:\Users\mads\anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 2430, in bar
x, height, width, y, linewidth = np.broadcast_arrays(
File "<__array_function__ internals>", line 5, in broadcast_arrays
File "C:\Users\mads\anaconda3\lib\site-packages\numpy\lib\stride_tricks.py", line 538, in broadcast_arrays
shape = _broadcast_shape(*args)
File "C:\Users\mads\anaconda3\lib\site-packages\numpy\lib\stride_tricks.py", line 420, in _broadcast_shape
b = np.broadcast(*args[:32])
ValueError: shape mismatch: objects cannot be broadcast to a single shape
you have 10 x_values but only 7 y_values. Try to run the same code with balanced data.

Python "EPSG code is unknown" when plotting a base map?

I am trying to add a base map to my plot through Contextily, but am getting this error when trying to see the plot.
Traceback (most recent call last):
File "rasterio/_crs.pyx", line 322, in rasterio._crs._CRS.from_epsg
File "rasterio/_err.pyx", line 192, in rasterio._err.exc_wrap_int
rasterio._err.CPLE_AppDefinedError: PROJ: proj_create_from_database: /opt/anaconda3/share/proj/proj.db lacks DATABASE.LAYOUT.VERSION.MAJOR / DATABASE.LAYOUT.VERSION.MINOR metadata. It comes from another PROJ installation.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.8/site-packages/matplotlib/cbook/__init__.py", line 196, in process
func(*args, **kwargs)
File "/opt/anaconda3/lib/python3.8/site-packages/matplotlib/widgets.py", line 1051, in _clicked
self.set_active(closest)
File "/opt/anaconda3/lib/python3.8/site-packages/matplotlib/widgets.py", line 1077, in set_active
func(self.labels[index].get_text())
File "vis.py", line 1109, in draw_basemap
ctx.add_basemap(ax, crs=properties_geo.crs.to_string())
File "/opt/anaconda3/lib/python3.8/site-packages/contextily/plotting.py", line 139, in add_basemap
left, right, bottom, top = _reproj_bb(
File "/opt/anaconda3/lib/python3.8/site-packages/contextily/plotting.py", line 229, in _reproj_bb
n_l, n_b, n_r, n_t = transform_bounds(s_crs, t_crs, left, bottom, right, top)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/warp.py", line 180, in transform_bounds
xs, ys = transform(src_crs, dst_crs, in_xs, in_ys)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/env.py", line 387, in wrapper
return f(*args, **kwds)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/warp.py", line 65, in transform
return _transform(src_crs, dst_crs, xs, ys, zs)
File "rasterio/_base.pyx", line 1398, in rasterio._base._transform
File "rasterio/_base.pyx", line 1444, in rasterio._base._osr_from_crs
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/crs.py", line 496, in from_user_input
return cls.from_string(value, morph_from_esri_dialect=morph_from_esri_dialect)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/crs.py", line 384, in from_string
return cls.from_epsg(val)
File "/opt/anaconda3/lib/python3.8/site-packages/rasterio/crs.py", line 333, in from_epsg
obj._crs = _CRS.from_epsg(code)
File "rasterio/_crs.pyx", line 324, in rasterio._crs._CRS.from_epsg
rasterio.errors.CRSError: The EPSG code is unknown. PROJ: proj_create_from_database: /opt/anaconda3/share/proj/proj.db lacks DATABASE.LAYOUT.VERSION.MAJOR / DATABASE.LAYOUT.VERSION.MINOR metadata. It comes from another PROJ installation.
Here is what I am doing in my code:
route = pd.read_excel("0002_D1_0_fixed_out_points_15ft.xls")
geometry = [Point(xy) for xy in zip(route.x_dd, route.y_dd)]
gdf = GeoDataFrame(route, geometry=geometry, crs='EPSG:3857')
fig,ax = plt.subplots()
ax.plot(route['x_dd'], route['y_dd'], 'o', markersize=1)
ctx.add_basemap(ax, crs=gdf.crs.to_string())
plt.show()
I'm assuming this is an issue with how my installations are set up and not the code itself. I've tried doing conda activate base which is the environment I'm in but am still getting the same error. I am on macOS as well

Workspace allocation error when using PyPortfolioOptimisation

Thanks in advance!
I am working on portfolio optimisation with PyPortfolioOptimisation.
I have the prices of my underlying assets starting from 2015-01-01 up till 2021-05-19
The dataframe shape is [1666 rows x 20 columns]
I ran the following codes
mu = expected_returns.mean_historical_return(df)
cov = risk_models.sample_cov(df)
print('Mean' '\n'+str(mu))
print('Covariance: ' '\n' +str(cov))
ef = EfficientFrontier(mu,cov)
weights = ef.max_sharpe()
cleaned_w = ef.cleaned_weights()
print(cleaned_w)
ef.portfolio_performance(verbose=True)
But it gives an error stating workspace allocation error pointing to line weights = ef.max_sharpe()
Traceback (most recent call last):
File "F:\Python projects\KS\Investment\Efficient frontier.py", line 34, in <module>
weights = ef.max_sharpe()
File "F:\Python projects\KS\lib\site-packages\pypfopt\efficient_frontier\efficient_frontier.py", line 278, in max_sharpe
self._solve_cvxpy_opt_problem()
File "F:\Python projects\KS\lib\site-packages\pypfopt\base_optimizer.py", line 239, in _solve_cvxpy_opt_problem
self._opt.solve(verbose=self._verbose, **self._solver_options)
File "F:\Python projects\KS\lib\site-packages\cvxpy\problems\problem.py", line 459, in solve
return solve_func(self, *args, **kwargs)
File "F:\Python projects\KS\lib\site-packages\cvxpy\problems\problem.py", line 947, in _solve
solution = solving_chain.solve_via_data(
File "F:\Python projects\KS\lib\site-packages\cvxpy\reductions\solvers\solving_chain.py", line 343, in solve_via_data
return self.solver.solve_via_data(data, warm_start, verbose,
File "F:\Python projects\KS\lib\site-packages\cvxpy\reductions\solvers\qp_solvers\osqp_qpif.py", line 103, in solve_via_data
solver.setup(P, q, A, lA, uA, verbose=verbose, **solver_opts)
File "F:\Python projects\KS\lib\site-packages\osqp\interface.py", line 37, in setup
self._model.setup(*unpacked_data, **settings)
ValueError: Workspace allocation error!
I tried changing the memory setting in Pycharm but to no avail. Is memory the same as workspace allocation? Sorry for these fundamental questions...
Cheers mate

MDP FANode issues

I'm trying to perform factorial analysis on a distance matrix (made of distances between about 1700 points, all ranging between 0.0 and 1.0, inclusively). I'm a total FA newbie.
Anyways, this code:
fan=mdp.nodes.FANode()
far=fan.execute(a)
# a is a numpy.array, size 1780x1780
Gives me:
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
far=fan.execute(a)
File "/usr/lib/pymodules/python2.7/mdp/signal_node.py", line 575, in execute
self._pre_execution_checks(x)
File "/usr/lib/pymodules/python2.7/mdp/signal_node.py", line 451, in _pre_execution_checks
self._if_training_stop_training()
File "/usr/lib/pymodules/python2.7/mdp/signal_node.py", line 431, in _if_training_stop_training
self.stop_training()
File "/usr/lib/pymodules/python2.7/mdp/signal_node.py", line 556, in stop_training
self._train_seq[self._train_phase][1](*args, **kwargs)
File "/usr/lib/pymodules/python2.7/mdp/nodes/em_nodes.py", line 93, in _stop_training
A = normal(0., sqrt(scale/k), size=(d, k)).astype(typ)
File "mtrand.pyx", line 1279, in mtrand.RandomState.normal (numpy/random/mtrand/mtrand.c:6943)
ValueError: scale <= 0
I tried replacing 0 values with 0.00001, to no avail. Any idea what this might mean?

Categories

Resources