Seite 1 von 1

Ball Animation

Verfasst: Montag 16. November 2020, 15:25
von bremen_hs_1992
Guten Tag an alle Programmierer :)
Ich bin erst seit sehr kurzer Zeit in der Python Geschichte drinne und habe jetzt ein Modul in meinem Studium(Modelbuldung und Systeme) wo wir python mit JupyterLab programmieren sollen.
Die Aufgabe ist einen Ball in einem x/Y Koordinatensystem fallen zu lassen und dieser soll wieder vom Boden abprallen( in gleichmäßiger geschwindigkeit also ohne Gravitation)
Nun habe ich mit meinem Gruppenpartner große probleme bei der Realisierung. Ich schicke meinen Code mal hier rein vielleicht sieht ja jemand direkt einen Fehler.




import numpy as np
from numpy import pi, sin, cos
import matplotlib.pyplot as plt
from IPython.display import HTML

from matplotlib import animation
# %matplotlib qt
%matplotlib inline
[19:09, 14.11.2020] agah: t_max = 10
v = pi*t_max # Geschwindigkeit in LE/s
frame_rate = 30 # Anzahl der Bilder pro sec
dt = 1. / frame_rate # Zeitdelay zwischen 2 Frames in sec
t = np.arange(0,t_max,dt) # Zeit-Stuetzstellenarray
f = 1/t_max # Frequenz (1 Umlauf in 5s)
omega = 2*pi*f # Kreisfrequenz
#time = np.linspace(0, -10, 10)
y = 0
i = np.zeros(10)
print(i)
[19:09, 14.11.2020] agah: # Erzeuge ein figure-Objekt (so etwas wie eine canvas)
fig = plt.figure(figsize=(5,5))

# Erzeuge ein axes-Objekt (artist) innerhalb der Figure
ax = fig.add_subplot()

#fig, ax = plt.subplots(figsize=(5, 5))

# Definiere die Achsenabschnitte
ax.set_xlim((-1, 1))
ax.set_ylim((-1, 1))

# Definiere die Objekte `point` und `time_text`, die animiert werden sollen
point, = ax.plot([], [],"o", lw=5)
plt.grid()


#y = -0.9 * t
y = np.linspace(0, -1, 10)

# Initialisierungsfunktion für die Animation
def init():
point.set_data([], [])
#time_text.set_text("")
return (point, time_text)

# Animationsfunktion, die sequentiel aufgerufen wird
def animate(t):
y = -0.9 * t
#y = 0.5*sin(omega*t)
x = 0
point.set_data(x, y)
#time_text.set_text(time_template %(t))
return (point, time_text)

anim = animation.FuncAnimation(fig, animate,init_func=init,
frames=t, interval=1./frame_rate*1000.,
blit=True, repeat=False)

# HTML(anim.to_html5_video())
HTML(anim.to_jshtml())





Wird der Code ausgeführt kommt folgende Fehlermeldung: (Fehlermeldung : File "<ipython-input-11-1c5b674931f2>", line 32
point.set_data(x, y)
^
IndentationError: unexpected indent)


Ich bedanke mich schonmal für jede Hilfe
Mfg

Re: Ball Animation

Verfasst: Montag 16. November 2020, 16:25
von einfachTobi
Die Zeile ist nicht richtig eingerückt. In Python ist die Einrückung von entscheidender Bedeutung, da sie die Zusammengehörigkeit von Codeteilen anzeigt. Was z. B. in Java mit geschweiften Klammern erledigt wird, erfolgt in Python durch Einrückung. Die Einrückung beträgt gemäß Konvention immer 4 Leerzeichen pro Ebene.

PS: Wenn du hier Code zeigst, dann verwende bitte die Code-Tags des Forums (</>-Knopf im vollständigen Editor). Dann bleibt die Einrückung nämlich auch in der Darstellung erhalten.

Re: Ball Animation

Verfasst: Montag 16. November 2020, 16:30
von Sirius3
Einrückungen sind in Python wichtig für die Syntax und die angemerkte Zeile ist eindeutig falsch eingerückt, wobei ich mich wundere, warum nicht die nachfolgende `return`-Zeile den Fehler erzeugt.

Re: Ball Animation

Verfasst: Mittwoch 18. November 2020, 16:11
von bremen_hs_1992
Also wir haben es nicht hinbekommen und haben den kompletten code von unserem Prof bekommen. Wenn ich denn jetzt bei mir ausführe , funktioniert die Ballanimation immernoch nicht, habe dann aus dem Internet eine ganz simple Wave Animation zum Testen rausgesucht und muss feststellen das geht auch nicht^^
Evt habe ich irgendwelche voreinstellungen nicht getätigt ?

schicke nun den Code mit der anschließenden Fehlermeldung:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

def init():
line.set_data([], []) #Plot the background of each Frame
return line,

def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i)) #Animation funktion
line.set_data(x, y)
return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True)

anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()








ist relativ simpel jedoch funktionierts nicht ^^
hier der fehlercode:


MovieWriter stderr:
Unknown encoder 'libx264'

---------------------------------------------------------------------------
OSError Traceback (most recent call last)
~\anaconda3\lib\site-packages\matplotlib\animation.py in saving(self, fig, outfile, dpi, *args, **kwargs)
229 try:
--> 230 yield self
231 finally:

~\anaconda3\lib\site-packages\matplotlib\animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs, progress_callback)
1151 frame_number += 1
-> 1152 writer.grab_frame(**savefig_kwargs)
1153

~\anaconda3\lib\site-packages\matplotlib\animation.py in grab_frame(self, **savefig_kwargs)
383 # frame format and dpi.
--> 384 self.fig.savefig(self._frame_sink(), format=self.frame_format,
385 dpi=self.dpi, **savefig_kwargs)

~\anaconda3\lib\site-packages\matplotlib\figure.py in savefig(self, fname, transparent, **kwargs)
2202
-> 2203 self.canvas.print_figure(fname, **kwargs)
2204

~\anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
2118 try:
-> 2119 result = print_method(
2120 filename,

~\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_raw(self, filename_or_obj, *args, **kwargs)
449 with cbook.open_file_cm(filename_or_obj, "wb") as fh:
--> 450 fh.write(renderer.buffer_rgba())
451

OSError: [Errno 22] Invalid argument

During handling of the above exception, another exception occurred:

CalledProcessError Traceback (most recent call last)
<ipython-input-20-daa1cc3be8bb> in <module>
----> 1 anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
2
3 plt.show()

~\anaconda3\lib\site-packages\matplotlib\animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs, progress_callback)
1150 progress_callback(frame_number, total_frames)
1151 frame_number += 1
-> 1152 writer.grab_frame(**savefig_kwargs)
1153
1154 # Reconnect signal for first draw if necessary

~\anaconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
129 value = type()
130 try:
--> 131 self.gen.throw(type, value, traceback)
132 except StopIteration as exc:
133 # Suppress StopIteration *unless* it's the same exception that

~\anaconda3\lib\site-packages\matplotlib\animation.py in saving(self, fig, outfile, dpi, *args, **kwargs)
230 yield self
231 finally:
--> 232 self.finish()
233
234

~\anaconda3\lib\site-packages\matplotlib\animation.py in finish(self)
366 def finish(self):
367 '''Finish any processing for writing the movie.'''
--> 368 self.cleanup()
369
370 def grab_frame(self, **savefig_kwargs):

~\anaconda3\lib\site-packages\matplotlib\animation.py in cleanup(self)
409 "MovieWriter stderr:\n%s", err)
410 if self._proc.returncode:
--> 411 raise subprocess.CalledProcessError(
412 self._proc.returncode, self._proc.args, out, err)
413

CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '432x288', '-pix_fmt', 'rgba', '-r', '30', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-vcodec', 'libx264', '-y', 'basic_animation.mp4']' returned non-zero exit status 1.




Ich hoffe jemand weis woran das liegen könnte...schonmal vielen dank :)

Re: Ball Animation

Verfasst: Mittwoch 18. November 2020, 16:59
von narpfel
@bremen_hs_1992: Hast du mal nach der Fehlermeldung gegooglet?

Wovon im Code könnte der Fehler denn ausgelöst werden? Was kann man machen, um den Fehler a) zu beheben; oder b) zu umgehen?

Re: Ball Animation

Verfasst: Mittwoch 18. November 2020, 17:28
von bremen_hs_1992
Ja habe es eingegeben, verstehe es aber nicht zu 100 %
Kann das sein dass ich diesen encoder x264 noch downloaden muss und ihn in jupyterlab in das korrekte verzeichnis zu setzen?

Re: Ball Animation

Verfasst: Mittwoch 18. November 2020, 18:04
von narpfel
@bremen_hs_1992: Ja, entweder du installierst `x264`, oder du lässt die `extra_args` einfach weg, dann sollte ein anderer Encoder benutzt werden.

Re: Ball Animation

Verfasst: Donnerstag 19. November 2020, 12:31
von bremen_hs_1992
Ich habe nun dieses x264 runtergeladen und die Datei in das Verzeichnis gezogen...es funktioniert immernoch nicht.
ffmpeg ist auch schon installiert..
hätte jemand noch eine idee