5.4.18 · D3 · HinglishScientific Computing (Python)

Worked examplesAnimation — FuncAnimation

3,270 words15 min read↑ Read in English

5.4.18 · D3 · Coding › Scientific Computing (Python) › Animation — FuncAnimation

Pehle ek waada: har symbol earn kiya hua hai. interval ek number hai milliseconds mein — flip-book ke do flips ke beech ka waqt. frames hai "page numbers" (ya values) ki list jo robot walk karta hai. FPS hai ek second mein kitne pages flip hote hain. func (hum ise update bolenge) hai woh rubber stamp jo kehta hai "is page ke liye, picture AISE banao". Yeh chaar pictures apne dimaag mein rakkho.

Do aur chhoti cheezein hain jinhe hum baar baar use karenge, jo yahan, pehle use se pehle define ki gayi hain:


Scenario matrix

FuncAnimation ke baare mein har sawaal in cells mein se kisi ek mein aata hai. Neeche ke hamare examples mein se har ek un cells ke saath tagged hai jisme woh aata hai, aur saath milake sab ko cover karte hain.

Axis Cases jo cover karne hain
Frame source integer N · explicit list/array · generator (unknown length)
Timing direction diya interval → FPS/total time nikalo · diya FPS/time → interval nikalo
Blit blit=True (artists return karne zaroor hain) · blit=False (return value ignore hota hai)
Artist count ek artist · kai artists (line + dot)
Degenerate / limiting frames=0 (empty) · interval=0 (jitna fast ho sake) · one-frame animation · generator jo kabhi nahi rukta
Saving chosen fps par mp4 mein save karo · interval saving mein kyun ignore hota hai · generator + save_count
Word / exam twist "mujhe 8-second clip chahiye" real problem · "meri window blank kyun hai?" bug-hunt

Woh number jo timing ko ek saath jodhta hai, parent mein ek baar derive kiya gaya, yeh hai:


Example 1 — integer frames → FPS aur total time (cell: integer N · interval→FPS · one artist)

Forecast: padhne se pehle FPS guess karo. Kya 20 ms frames ke beech fast hai ya slow?

  1. Numbers padho. interval = 20 ms, N = 200 frames. Yeh step kyun? Har timing problem numbers ko name karne se shuru hoti hai — kaun sa number interval hai aur kaun sa N, taaki hum unhe mix na karein.
  2. Pehli equation se FPS. . Yeh step kyun? "1000 ms mein kitne 20 ms slots fit hote hain?" — woh count hi frames-per-second hai.
  3. Doosri equation se total time. ms; bridge se convert karo: s. Yeh step kyun? Ek pass har frame ka chhota sa wait hai, end-to-end stack kiya — ms mein — phir 1000 se divide karke seconds mein padhte hain.

Verify: doosre form se cross-check karo: s. ✓ Units: . ✓


Example 2 — inverse: "mujhe exact-length clip chahiye" (cell: given FPS/time→interval · word problem · saving)

Forecast: kya file save karte waqt interval matter bhi karta hai?

  1. Frames = FPS × seconds. frames. Yeh step kyun? ko rearrange karne par milta hai — right side ke dono values pata hain.
  2. FPS se Interval. ms. Yeh step kyun? Same pehli equation, interval ke liye solve ki: slot length hai "ek second (1000 ms) ko FPS pieces mein baantna."
  3. Saving fps pass karta hai, interval nahi. anim.save("clip.mp4", fps=60). Yeh step kyun? Parent note ka key rule: saving karte waqt, matplotlib frames ko seconds par space karta hai aur interval ignore karta hai (koi live GUI timer nahi obey karna). Dekho Saving figures and ffmpeg.

Verify: , ke saath: s exactly. ✓ Aur ms ms s live playback ke liye. ✓


Example 3 — frames ka array ek moving dot ko feed karta hai (cell: explicit array · many artists · blit=True)

Figure — Animation — FuncAnimation

Pehle data fix karo, taaki neeche har symbol concrete ho:

import numpy as np
x = np.linspace(0, 2*np.pi, 200)   # 200 evenly-spaced x-values from 0 to 2π
# y at any x is np.sin(x); see [[NumPy linspace and broadcasting]]

Toh ==x== ek NumPy array hai jisme se tak 200 evenly spaced numbers hain (`linspace` se bane), aur np.sin(x) matching heights ka array hai. x[:i] matlab "x ki pehli i entries" — ek slice.

Forecast: agar tum sirf dot return karo aur trail line bhool jao — screen par kya hoga?

  1. Dono artists ek baar, empty banaao. line, = ax.plot([], [], 'b-') aur dot, = ax.plot([], [], 'ro'). Yeh step kyun? Parent ke rule ke mutabiq, artists update ke bahar bante hain aur andar sirf mutate hote hain — dekho Artists in Matplotlib.
  2. Frame i data slice karta hai. trail = points x[:i]; dot = single point (x[i], sin(x[i])). Yeh step kyun? x[:i] slice ko i ke saath grow karna hi trail ko lengthen karta hai — figure dekho: mint trail left-se-right grow karti hai jabke coral dot uski tip par ride karta hai.
  3. DONO artists return karo. return line, dot. Yeh step kyun? blit=True ke saath, matplotlib exactly wohi redraw karta hai jo tum return karte ho. Line chhod do aur trail freeze ho jaayegi.

Verify (sanity, no arithmetic): par, trail empty hai (x[:0]), dot par — ek single starting point, "motion se pehle frame" se match karta hai. Last par, x[:i] poora curve hai. ✓ Figure ke frames-side captions slice lengths confirm karte hain.


Example 4 — frames ke taur par ek generator, save_count ke saath (cell: generator · saving · unknown length)

Forecast: kya matplotlib ek generator ki length khud jaanta hai?

  1. Yields count karo. Values hain pehle tak par nahi including. Count . Yeh step kyun? while t < 6.28 with step indices se tak yield karta hai (kyunki lekin ). Yeh 126 values hain.
  2. Live playback theek hai — timer bas generator se naye t values pull karta rehta hai jab tak woh exhaust na ho jaaye. Dekho Generators in Python.
  3. Saving ko count chahiye. Ek generator ka koi len nahi hota. save_count=200 .save ko batata hai ki kitne frames pull karne hain uska upper bound. Yeh step kyun? Saver ko pehle se pata hona chahiye (ya cap hona chahiye) kitni images likhni hain; woh generator se puch nahi sakta "tum kitne lambe ho?"

Verify: ✓ aur ✓, toh exactly 126 frames. Kyunki , save_count=200 unhe saare capture kar leta hai gunjaaish ke saath. ✓


Example 5 — blit=False: return value matter karna band ho jaata hai (cell: blit off · one artist)

Forecast: kya return bhoolna blit=False animation ko tod dega?

  1. blit=False ke saath, poora axes har frame mein redraw hota hai. Return value ignore hoti hai. Yeh step kyun? Blitting woh single feature hai jo tumhare returned artists padhta hai (use pata hona chahiye ki cached background ke upar kya copy karna hai). No blit → kuch nahi return padhta.
  2. Toh return line, yahan harmless lekin optional hai. Ise rakhne ka matlab hai wahi code baad mein blit=True flip karne par bhi kaam karta hai. Yeh step kyun? Future-proofing: ek aadat (hamesha artists return karo) dono modes mein kaam karti hai.
  3. Cost: slower, kyunki ticks/grid/labels har frame mein re-render hote hain — exactly woh kharcha jo blitting skip karne ke liye banaaya gaya tha.

Verify (behavioural): ek blit=False animation bina return statement ke phir bhi sahi animate karti hai (proves return ignore hoti hai); ek blit=True wali bina return ke raise/freeze karti hai (proves blit ise padhta hai). Yeh ek logic check hai, arithmetic nahi — asymmetry hi poora point hai.


Example 6 — degenerate: zero frames, one frame, interval 0 (cell: empty / single / limiting)

Figure — Animation — FuncAnimation

Forecast: kya frames=0 crash karta hai, freeze karta hai, ya static picture dikhata hai?

  1. frames=0 → ek pass mein kuch move nahi karta. update kabhi kisi frame value ke saath call nahi hota; tum sirf wohi dekhte ho jo init_func ne draw kiya tha (clean background jo humne upar define ki). s of motion. Yeh step kyun? ke saath doosri equation deti hai: koi frames nahi matlab koi animation time nahi guzra. Figure ka left panel sirf clean init_func background dikhata hai.
  2. frames=1 → ek single flip. update ek baar run karta hai (frame 0), phir (kyunki repeat=True default hai — woh loop-when-frames-run-out switch jo humne upar define kiya) woh ek frame hamesha ke liye loop karta hai, toh yeh still image jaisa lagta hai. . Yeh step kyun? Yeh sabse chhota non-empty case hai; useful hai test karne ke liye ki tumhare artists bilkul dikhte hain ya nahi.
  3. interval=0 → "backend jitna fast allow kare utna". mathematically undefined hai; practically GUI timer event loop jitni jaldi kar sake utni jaldi fire karta hai, toh real FPS formula se nahi, tumhare machine se cap hoti hai. Yeh step kyun? Yeh pehli equation ka limiting behaviour hai: jaise , FPS , lekin hardware ise clamp karta hai. Literal zero se kabhi apne dimaag mein divide mat karo — ise ek limit ki tarah padho.

Verify: (a) s ✓. (b) s ms single frame ke liye ✓. (c) limit check: jaise interval ms shrink hota hai, FPS rise karta hai, confirm karta hai FPS as interval . ✓


Example 7 — never-ending generator (cell: generator that never stops · limiting)

Forecast: kya live playback kabhi rukegi? Kya saving hamesha hang karegi?

  1. Live playback indefinitely chalta hai. Generator kabhi StopIteration raise nahi karta, toh timer har interval ms mein naye t values pull karta rehta hai jab tak tum window band nahi karte. Yeh step kyun? FuncAnimation ek pass tab rokta hai jab frame source exhaust ho jaaye; infinite source kabhi exhaust nahi hota. repeat irrelevant hai (koi "end" nahi hai loop karne ke liye), yeh bas ek endless stream hai.
  2. Saving zaroor cap honi chahiye. .save images likhne ke liye generator walk karta hai. Bina length aur bina save_count ke, matplotlib nahi jaanta kab rokna hai — woh frames forever pull karne ki koshish karta rahega. Yeh step kyun? Yahi reason hai save_count exist karta hai (Example 4): yeh ek infinite generator ke liye mandatory hai. anim.save("out.mp4", fps=30, save_count=300) pehle 300 frames likhta hai aur rok deta hai.
  3. Fix pattern. Ya toh generator finite banao (stop condition add karo) ya saving karte waqt hamesha save_count pass karo. Yeh step kyun? Dono saver ko ek definite endpoint dete hain; finite generator live playback ko bhi naturally end karne deta hai.

Verify: save_count=300 aur fps=30 ke saath, saved clip length s hai — ek definite, finite file chahe generator infinite ho. ✓


Example 8 — classic "window blank hai" bug (cell: exam twist · degenerate reference-loss)

Forecast: bug update mein hai, interval mein hai, ya kahin aur?

  1. Missing assignment pakdo. Call result store nahi hua: koi anim = ... nahi. Yeh step kyun? FuncAnimation ek object return karta hai jo timer ka owner hai. Aur kuch ise alive nahi rakhta.
  2. Python ise garbage-collect karta hai. Jaise hi unreferenced object collect hota hai, uska timer mar jaata hai — aur koi frames nahi. Yeh step kyun? Yeh event loop se jodta hai: timer ek live object hai; reference drop karo, heartbeat drop karo.
  3. Fix: anim = FuncAnimation(...) aur anim ko scope mein rakkho (module-level ya apne function se return karo).

Verify (behavioural): identical code jo sirf anim = add karta hai woh animate karta hai; ise hatao toh blank window har baar reproduce hoti hai — reference ko sole cause ke roop mein isolate karta hai. ✓


Active recall

Connections

  • Animation — FuncAnimation — parent: woh machine jinhe yeh scenarios exercise karti hain.
  • Matplotlib Figure and Axes — woh canvas jo har frame mein update hota hai.
  • Artists in MatplotlibLine2D, set_data, blit-return.
  • Generators in Python — Examples 4 & 7 ka frame source.
  • Event Loops / GUI backends — Examples 6 & 8 ke peeche ka timer.
  • NumPy linspace and broadcasting — per-frame arrays banana (Example 3 ka x).
  • Saving figures and ffmpeg — Examples 2, 4 & 7 ka .save.

Concept Map

integer N

generator

live

saving

frame source

known length

needs save_count

timing eqns FPS and T

uses interval

uses fps only

blit true returns artists

store anim reference