Ahmed Blogs

Ahmed Blogs

Share

Come to my Thought

10/04/2025

Python code for Alive and dead human heart ECG

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.patches as patches
import shutil

# -----------------------------
# Check ffmpeg availability
# -----------------------------
has_ffmpeg = shutil.which("ffmpeg") is not None

# -----------------------------
# ECG waveform generator
# -----------------------------
def ecg_waveform(t):
"""Simple synthetic ECG-like waveform."""
return np.piecewise(
t,
[t < 0.1, (t >= 0.1) & (t < 0.2), (t >= 0.2) & (t < 0.3), t >= 0.3],
[lambda t: 0.5 * np.sin(10 * np.pi * t), # small P wave
lambda t: -1.5 * np.exp(-50 * (t - 0.1)), # sharp Q dip
lambda t: 2 * np.exp(-200 * (t - 0.2)), # R spike
lambda t: -0.7 * np.exp(-20 * (t - 0.3))] # S dip / T wave
)

# -----------------------------
# Setup figure
# -----------------------------
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 8))

# Heart (as circle for simplicity)
heart = patches.Circle((0.5, 0.5), 0.1, color="red")
ax1.add_patch(heart)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax1.axis("off")
ax1.set_title("Human Heart (Alive → Death)")

# ECG line
t = np.linspace(0, 1, 200)
line, = ax2.plot([], [], lw=2, color="green")
ax2.set_xlim(0, 10)
ax2.set_ylim(-2, 3)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("ECG")
ax2.set_title("ECG Signal")

# -----------------------------
# Animation function
# -----------------------------
frames = 300 # total frames (~10 sec at 30 fps)

def init():
line.set_data([], [])
return heart, line

def animate(i):
phase = i / frames

# Heart beating until ~70%, then stops
if phase < 0.7:
scale = 0.1 + 0.01 * np.sin(20 * np.pi * phase)
heart.set_radius(scale)
heart.set_color("red")
else:
heart.set_radius(0.1)
heart.set_color("gray")

# ECG alive → flatline
if phase < 0.7:
t_vals = np.linspace(0, 1, 200)
y = ecg_waveform(t_vals)
x = np.linspace(0, 10, len(y))
line.set_data(x, np.tile(y, 10)[:len(x)])
line.set_color("green")
else:
x = np.linspace(0, 10, 200)
y = np.zeros_like(x)
line.set_data(x, y)
line.set_color("black")

return heart, line

anim = FuncAnimation(fig, animate, init_func=init,
frames=frames, interval=30, blit=True)

# -----------------------------
# Save outputs
# -----------------------------
if has_ffmpeg:
anim.save("heart_ecg_life_to_death.mp4", writer="ffmpeg", fps=30)
print("✅ Saved MP4: heart_ecg_life_to_death.mp4")
else:
print("⚠️ ffmpeg not found, skipping MP4 export")

# Always save GIF as fallback
anim.save("heart_ecg_life_to_death.gif", writer="pillow", fps=30)
print("✅ Saved GIF: heart_ecg_life_to_death.gif")

plt.show()

Run above code
Result is as

10/04/2025

This code is for young students who learning Geometry

Want your public figure to be the top-listed Public Figure in Allen?
Click here to claim your Sponsored Listing.

Category

Telephone

Website

Address


Sleepy Hollow Drive
Allen, TX
75002