From Heartbeats to Dynamical Systems

Ever wondered how your heart’s existential crisis during exercise could be a math problem? We turned beats into equations, panic into differential calculus, and recovery into logistic drama. Spoiler: Your Fitbit data is way less fun. Join us as we dissect cardiac chaos with sarcasm, code, and zero chill.

draft
dynamical systems
non-linear
simulation
educational
Author
Published

March 28, 2025

Introduction

Let’s talk about your heart. No, not the one that skips a beat when your crush texts back, that heart is a drama queen we’ll save for therapy. I’m talking about the actual meat-pump in your chest, the one that’s currently working overtime to process the existential dread of Monday mornings. For something so vital, it’s surprisingly bad at subtlety. When you exercise, it’s either “chill mode” (Netflix and nap) or “I’m about to audition for Speed 3: Cardiac Edition.” But here’s the kicker: scientists have spent decades trying to decode its mood swings, and let’s just say the results are… mixed. Enter my latest obsession: a math model so extra, it makes your gym’s heart rate monitor look like a Tamagotchi.

Picture this: you’re on a treadmill, sweating like a popsicle in July, and your heart rate zigzags like a caffeinated EKG. Traditional methods to track this chaos? They’re like using a ruler to measure a squiggle. Heart rate variability (HRV) metrics, those bland averages your Fitbit spits out, are the equivalent of summarizing War and Peace as “some guys had feelings.” Sure, they tell you something, but they miss the juicy plot twists. Your heart isn’t a metronome; it’s a freestyle jazz musician with a caffeine problem. And when you throw exercise into the mix? Cue the autotuned chaos.

Now, imagine if we could actually model this nonsense. Not with boring straight lines or sleepy exponentials, but with something that embraces the heart’s flair for melodrama. That’s where this new non-linear model struts in, wearing sunglasses indoors. It’s basically the Sherlock Holmes of heartbeats, solving the mystery of why your R-R intervals (the time between heartbeats, for the uninitiated) look like a toddler’s crayon drawing during a spin class. Using logistic functions, fancy curves that even your high school math teacher would side-eye, it maps out how your heart crashes during exercise and limps back to normal afterward. Think of it as a GPS for your cardiovascular system: “Recalculating… turn left at adrenaline alley.”

But why should you care? Well, unless you’re a cyborg, your autonomic nervous system (ANS) is the puppet master behind this circus. When you exercise, it’s a tug-of-war between “fight-or-flight” (sympathetic nervous system) and “nap time” (parasympathetic). Traditional models treat this like a polite debate. Spoiler: it’s not. It’s a WWE smackdown, complete with folding chairs. Linear models? They’re the guy at the party who insists the music isn’t that loud. This new model? It’s the one crowd-surfing while yelling, “I CAN EXPLAIN THE PLATEAU PHASE!”

Here’s the plot twist: the model wasn’t born in a lab coat. It started as a desperate attempt to make sense of data from 272 elderly folks marching in place like it’s 1999. (Side note: If you ever want to feel better about your fitness, watch a senior citizen out-step you in a “light” exercise test.) The real magic? The model doesn’t just fit the data, it throws a interpretive dance party. By smooshing together two logistic functions (one for the crash, one for the comeback), it captures the heart’s U-shaped rollercoaster: freefall during exercise, slow climb back to sanity. Bonus points: the parameters have names like \(\alpha\) and \(\beta\), which sounds like a sorority for math nerds.

Of course, no model is perfect. This one’s got quirks. For starters, it’s really into baseline RRI (\(\alpha\)), the “resting heart rate” of the equation. According to Sobol sensitivity analysis, \(\alpha\) is basically the Beyoncé of parameters, hogging 60% of the variance spotlight. Then there’s “c,” the recovery proportion, which is like the friend who says they’ll cover your Uber but only chips in 84%. The other parameters? They’re the background dancers. \(\lambda\) and \(\phi\) control the speed of crash and recovery, but apparently, nobody cares about speed when you’ve got drama queens like \(\alpha\) stealing the show.

Now, let’s address the elephant in the room: this model was tested on grandmas and grandpas. That’s right, your heart’s midlife crisis during Zumba? Not represented here. The elderly cohort is both a strength and a weakness. On one hand, they’re the ultimate stress test (imagine coding a model while your participants debate fiber intake). On the other, it’s like tuning a race car using data from a golf cart parade. But hey, if it works for them, it’ll probably work for you, unless you’re an Olympic sprinter, in which case, why are you reading a blog post? Go win a medal.

The real kicker? This model could change how we monitor hearts in real time. Imagine wearables that don’t just count steps but scream, “HEY, YOUR PARASYMPATHETIC SYSTEM IS SLACKING!” during meetings. Or rehab programs tailored like Spotify playlists, “Autonomic Acoustic” for recovery, “Sympathetic Screamo” for HIIT. The future is weird, folks.

So buckle up. We’re diving into the mathy, sweaty, gloriously chaotic world of heart rate modeling. Whether you’re a fitness junkie, a data nerd, or just here for the sarcasm, this model’s got something for you. Spoiler: It involves differential equations, but I promise to keep the calculus to a minimum. After all, your heart’s already doing enough heavy lifting.

How We’ll Turn Heartbeats Into a Soap Opera (But With Math)

Alright, let’s talk about reverse-engineering your heart’s melodrama. The original model, a perfectly good equation that already does the job, is about to get a glow-up. Not because it’s bad, but because we’re bored and differential equations are the glitter glue of science. Here’s how we’ll reframe it as a dynamical system, no lab coat required.

Step 1: Split the Drama Into Seasons

First, we’ll take the original model, a sum of two moody sigmoids, and break it into two characters: Season 1: The Crash (Exercise Phase). This is where your heart goes full The Titanic. We’ll call this variable \(x(t)\), the mathematical embodiment of “why did I sign up for this spin class?”. Season 2: The Comeback (Recovery Phase). Here, \(y(t)\) is the slow-mo montage where your heart limps back to baseline like it’s recovering from a breakup.

Together, they’ll form a dynamic duo: \(RRi(t) = \alpha + x(t) + y(t)\). Think of α as the neutral narrator who just wants everyone to calm down.

Step 2: Write the Script (a.k.a. Differential Equations)

Next, we’ll turn these static characters into a live-action series. For \(x(t)\), we’ll ask: “How fast does panic set in?” The answer involves a logistic decay equation, basically, math’s way of saying “the faster you run, the faster you regret.” For \(y(t)\), we’ll ask: “How long until denial becomes acceptance?” That’s a logistic growth equation, or “the speed at which your ANS remembers it has a yoga class later.”

But here’s the twist: we’ll add activation functions, smooth on/off switches that tell the equations when to start. Imagine a director yelling “ACTION!” at \(\tau\) (exercise o’clock) and “CUT!” at \(\tau + \delta\) (nap o’clock). These switches ensure the drama stays in its lane. No crashing during warm-up, no recovering before the trauma even starts.

Step 3: Smoothie Recipe for Transitions

To avoid abrupt plot twists (because hearts hate jump scares), we’ll use sigmoidal activation functions. These are like blending a kale smoothie, harsh at first, but eventually smooth. They’ll gently ramp up the chaos during exercise and taper it off during recovery, so your heart rate doesn’t look like a toddler scribbling on a whiteboard.

Step 4: Let the Computer Do the Heavy Lifting

Once the equations are set, we’ll toss them into a Bayesian blender. Using Hamiltonian Monte Carlo (a fancy algorithm that’s basically a Roomba with a PhD), we’ll brute-force the parameters until the model fits the data like a conspiracy theory fits Twitter. No intuition required, just vibes and CPU power.

Step 5: Crowd-Source the Plot

Finally, we’ll run a sensitivity analysis to see which parameters steal the spotlight. Spoiler: Baseline RRi (\(\alpha\)) will probably monologue for 60% of the runtime, while recovery proportion (\(c\)) mutters emo poetry in the background. The rest? Cameos at best.

This isn’t about “fixing” our original model, it’s already a rockstar. It’s about giving it a new lens, like filming a rom-com in black-and-white. We’re translating a snapshot into a flipbook, asking: “What if heartbeats had director’s commentary?”

Now we are ready for the next scene, where we’ll actually show the math. Don’t worry, we’ll dilute the calculus with metaphors about Netflix binge-watching and interpretive dance. Your heart’s already doing calculus anyway.

How Your Heart’s Midlife Crisis Became a Math Problem

Let’s dissect this heart-rate saga like it’s a Netflix thriller. Buckle up, we’re diving into equations.

The Original Model (a.k.a. “Before the Glow-Up”)

The original model, let’s call it The Heartbreak Equation, is a sum of two moody sigmoid curves. Think of it as your heart’s Instagram feed: one post bragging about its chill baseline (\(\alpha\)), another crying about exercise (\(\beta\)), and a third pretending to recover (\(c\beta\)). Mathematically, it’s:

\[ RRi(t) = \alpha + \frac{\beta}{1 + e^{\lambda(t - \tau)}} + \frac{-c\beta}{1 + e^{\phi(t - \tau - \delta)}} \]

Here’s the cast:

  • \(\alpha\): Baseline RRi. The heart’s “resting face” (read: pretending it didn’t just binge-watch Stranger Things).
  • \(\beta\): How hard RRi nosedives during exercise. Beta’s the drama queen.
  • \(c\): The recovery’s participation trophy. “I’ll undo some of the damage… maybe.”
  • \(\lambda\) & \(\phi\): Speed of crash and recovery. One’s a Tesla, the other’s a Prius.
  • \(\tau\) & \(\delta\): Timing of exercise and recovery. Because your heart needs a schedule to panic.

Split the Drama Into Spin-Offs

We’re giving the model a Hollywood reboot. Meet the two new leads:

  1. \(x(t)\): The Exercise Arc. Defined as:

\[ x(t) = \frac{\beta}{1 + e^{\lambda(t - \tau)}} \]

This is your heart’s “Why did I agree to this HIIT class?” phase.

  1. \(y(t)\): The Recovery Arc. Defined as:

\[ y(t) = \frac{-c\beta}{1 + e^{\phi(t - \tau - \delta)}} \]

This is the “I’ll never skip leg day again… (until next week)” phase.

Together, they form:

\[ RRi(t) = \alpha + x(t) + y(t) \]

Alpha’s just there to remind everyone what “normal” used to mean.

Derivative Drama

Time to make these variables earn their screen time. Let’s differentiate \(x(t)\) first.

Step 1: Quotient Rule, But Make It Fashion

The derivative of \(x(t)\) is like asking, “How fast does regret hit during burpees?” Using the quotient rule:

\[ \frac{dx}{dt} = -\beta \frac{\lambda e^{\lambda(t-\tau)}}{\left(1 + e^{\lambda(t-\tau)}\right)^2} \]

Translation: “The faster you exercise, the faster your soul leaves your body.”

Step 2: Rewrite the Script (In Terms of \(x(t)\))

We hate seeing “t” in our equations, it’s tacky. Let’s rewrite everything using \(x(t)\):

\[ 1 + e^{\lambda(t-\tau)} = \frac{\beta}{x(t)} \quad \Rightarrow \quad e^{\lambda(t-\tau)} = \frac{\beta - x(t)}{x(t)} \]

Substitute this back into the derivative and simplify:

\[ \frac{dx}{dt} = -\lambda x(t) \left(1 - \frac{x(t)}{\beta}\right) \]

Voilà! Now \(x(t)\) follows a logistic decay, math’s way of saying “panic accelerates until you accept your fate.”

\(y(t)\)’s Redemption Arc

Now for \(y(t)\). Differentiate:

\[ \frac{dy}{dt} = \phi c\beta \frac{e^{\phi(t-\tau-\delta)}}{\left(1 + e^{\phi(t-\tau-\delta)}\right)^2} \]

This is the “How fast does hope return post-exercise?” equation. Spoiler: Not fast enough.

Rewrite the Script (Again, Because We’re Extra)

Express everything in terms of \(y(t)\):

\[ 1 + e^{\phi(t-\tau-\delta)} = \frac{-c\beta}{y(t)} \quad \Rightarrow \quad e^{\phi(t-\tau-\delta)} = \frac{-c\beta - y(t)}{y(t)} \]

Plug it back in and simplify:

\[ \frac{dy}{dt} = -\phi y(t) \left(1 + \frac{y(t)}{c\beta}\right) \]

Boom! \(y(t)\) follows a logistic growth, math’s version of “recovery starts slow but eventually remembers it has a yoga class.”

Add Plot Armor (a.k.a. Activation Functions)

To prevent the drama from spilling into unrelated timelines (like recovering before exercising), we add sigmoidal activation functions, smooth on/off switches.

Exercise Switch:

\[ \psi_{\text{exercise}}(t) = \frac{1}{1 + e^{-\lambda(t-\tau)}} \]

It’s 0 before exercise (“I’m fine!”) and 1 after (“Code Red!”).

Recovery Switch:

\[ \psi_{\text{recovery}}(t) = \frac{1}{1 + e^{-\phi(t-\tau-\delta)}} \]

It’s 0 during exercise (“Still dying!”) and 1 after (“Maybe I’ll live?”).

Final Equations (With Boundaries, Because Chaos Needs Rules):

\[ \frac{dx}{dt} = -\lambda x(t)\left(1 - \frac{x(t)}{\beta}\right) \cdot \psi_{\text{exercise}}(t) \]

\[ \frac{dy}{dt} = -\phi y(t)\left(1 + \frac{y(t)}{c\beta}\right) \cdot \psi_{\text{recovery}}(t) \]

Now, \(x(t)\) only crashes when exercise starts, and \(y(t)\) only recovers after a respectful delay. Think of it as your heart’s way of saying, “I need 5… no, 10 minutes.”

Why This Matters (Besides Bragging Rights)

By framing the model as a dynamical system, we’ve turned a static equation into a real-time model. Want to see how fast your heart crashes if you skip warm-ups? Crank up \(\lambda\). Curious why recovery takes forever after 40? Blame \(\phi\).

It’s not better, just spicier. Like adding hot sauce to your Fitbit.
Next time: We’ll simulate this chaos.

Simplifying the Beast

The Diet Coke Version of Heart Math (Same Chaos, Fewer Calories)

Alright, let’s take a breath. We’ve just spent a small eternity dissecting how your heart’s existential crisis during exercise can be modeled with nonlinear differential equations, math’s version of a Shakespearean tragedy. It’s got drama, depth, and enough quadratic terms to make your laptop sweat. But here’s the thing: sometimes you don’t need a five-act play about cardiac dynamics. Sometimes you just want a TikTok skit.

Enter the simplified linear model. Think of it as the tutorial version of the original equation. It’s faster, lighter, and almost as accurate, like swapping a vintage wine for a LaCroix. But why bother simplifying something that’s already brilliant? Let’s talk about that.

Why Simplify?

The original dynamical system we built is a masterpiece. It’s got logistic decay, sigmoidal switches, and enough Greek letters to confuse a sorority. But here’s the problem: nonlinear equations are computational divas. They demand attention, processing power, and patience, three things you don’t have when you’re trying to simulate heartbeats in real time on a smartwatch powered by a potato battery.

Imagine you’re a fitness app developer. Your users want instant feedback on their heart rate recovery after a workout. The full model? It’s like asking them to wait while you solve a Rubik’s cube blindfolded. They’ll uninstall your app and go pet a dog instead.

Or say you’re a researcher teaching undergrads about autonomic regulation. Throwing nonlinear differential equations at them is like explaining quantum physics using interpretive dance. They’ll nod politely while mentally planning their dropout party.

That’s where the simplified model shines. It’s the IKEA furniture of cardiac math: easy to assemble, good enough for most purposes, and unlikely to collapse unless you’re doing something weird. Let’s break down how we hacked the drama out of the equations.

Step 1: Throw Out the Quadratic Drama (It’s Not You, It’s Math)

The original equations were nonlinear, a fancy way of saying they’re clingy and complicated. Take the exercise phase equation:

\[ \frac{dx}{dt} = -\lambda x \left(1 - \frac{x}{\beta}\right) \]

That \(x^2\) term? That’s the equation’s way of saying, “I’m not like other girls.” But if we assume your heart’s meltdown is controlled (i.e., \(x^2\) is close to its rock bottom \(\beta\)), we can Taylor-expand this like it’s a meme.

Here’s the math magic:

  1. Define \(\Delta x = \beta - x\) (how far \(x^2\) is from its emo phase).
  2. Pretend \(\Delta x\) is small (like your attention span during a Zoom meeting).
  3. Rewrite the equation in terms of \(\Delta x\):

\[ \frac{dx}{dt} \approx -\lambda (\beta - x) \]

Translation: The panic fades linearly, like your enthusiasm for kale smoothies.

Same trick for the recovery phase:

\[ \frac{dy}{dt} = -\phi y \left(1 + \frac{y}{c\beta}\right) \]

Define \(\Delta y = -c \beta - y\) (how far \(y\) is from redemption), assume \(\Delta y\) is tiny, and boom:

\[ \frac{dy}{dt} \approx -\phi (-c\beta - y) \]

Now the redemption arc is linear, like your progress bar during a software update.

Step 2: Add Time-Out Switches (Because Even Hearts Need Boundaries)

Hearts don’t panic 24/7 (unless you’re a Wall Street trader). To control when the drama unfolds, we use sigmoidal activation functions, smooth on/off switches that say, “Not now, sweetie.”

  • Exercise switch:

\[ \psi_{\text{exercise}}(t) = \frac{1}{1 + e^{-\lambda(t - \tau)}} \]

  • Recovery switch:

\[ \psi_{\text{recovery}}(t) = \frac{1}{1 + e^{-\phi(t - (\tau + \delta))}} \]

These switches act like parental controls for your heart rate. Before τ (exercise o’clock), ψ_exercise ≈ 0: “No cardio before coffee.” After τ + δ (nap o’clock), ψ_recovery ≈ 1: “OK, you can stop dying now.”

Slap these into the linear equations:

\[ \frac{dx}{dt} = -\lambda (\beta - x) \cdot \psi_{\text{exercise}}(t) \]

\[ \frac{dy}{dt} = -\phi (-c\beta - y) \cdot \psi_{\text{recovery}}(t) \]

Now the meltdown and redemption only happen when scheduled. No surprises, like a Netflix show that actually respects your bedtime.

Step 3: Why Bother? (Trade-Offs for the Attention-Span Deprived)

Pros of the Diet Model:

  • Speed: Simulates faster than you can say “existential crisis.” Perfect for real-time apps where users tap their feet waiting for results.
  • Stability: No chaotic surprises. It’s like replacing a rollercoaster with a escalator.
  • Transparency: Parameters slap you in the face with meaning. λ? Panic speed. φ? Recovery laziness. No PhD required.

Cons:

  • Blandness: Loses the spicy logistic saturation. It’s the difference between a rom-com and a spreadsheet.
  • Accuracy: Only works near equilibrium. Stray too far, and it’s like using a ruler to measure a tornado.

When to Use Which Model (Choose Your Own Adventure)

Full Dynamical System:

  • For Researchers: If you’re publishing a paper titled “Nonlinear Autonomic Oscillations in Elderly Step-Test Cohorts: A Bayesian Perspective,” this is your jam.
  • Deep Analysis: Want to explore how λ and φ interact during a HIIT workout? Go nuts.
  • Flexibility: Captures the full cardiac soap opera, breakdowns, comebacks, and plot twists.

Simplified Linear Model:

  • For Developers: Building a fitness app? Use this. Your servers won’t cry.
  • Education: Teaching undergrads? They’ll thank you for not melting their brains.
  • Quick Simulations: Need to model 10,000 heartbeats before lunch? This’ll do.

The Big Picture: Why Simplification Isn’t Sacrilege

Let’s be real: the original model is a Ferrari. It’s sleek, powerful, and turns heads at academic conferences. But most of us don’t need a Ferrari to drive to Walmart. Sometimes a Toyota Corolla (read: linear model) gets the job done without the maintenance fees.

Simplification isn’t about dumbing things down, it’s about pragmatism. The world runs on approximations. Weather apps? They use simplified models. GPS? Simplified models. Your mom’s meatloaf recipe? Definitely simplified.

The key is knowing when to simplify. If you’re designing a pacemaker? Stick with the full model. If you’re coding a heart rate widget for a smartwatch? The linear version is your friend.

The Heart’s Many Faces

At the end of the day, your heart is a drama queen with range. Sometimes it’s method-acting through a spin class, other times it’s phoning it in during a Zoom meeting. The models we’ve built, both the full nonlinear saga and its streamlined sibling, are just tools to decode the performance.

So next time you’re on a treadmill, remember: your heart isn’t just beating. It’s starring in a math rock opera, complete with logistic plot twists and linear encores. And whether you’re team Ferrari or team Corolla, there’s a model for that.

Simulating Cardiac Meltdowns (With Less Math-Induced Trauma)

Alright, we’ve got the equations. Now let’s simulate this nonsense and watch your heart rate plot its escape from Zumba class. Think of it as The Sims for cardio nerds, except instead of drowning pixelated people, we’re drowning in differential equations. Let’s code this drama.

Euler’s Method

Differential equations are like IKEA instructions: “Here’s the slope, good luck!” To solve them, we’ll use Euler’s method, the duct tape of numerical analysis. It guesses the future by taking tiny steps forward, like a drunk person navigating a dark room.

For any equation:

\[ \frac{dx}{dt} = f(x, t) \]

Euler says:

\[ x(t + \Delta t) \approx x(t) + \Delta t \cdot f(x(t), t) \]

where \(\Delta t\) is the step size. Smaller steps = more accuracy, but slower than your Wi-Fi during a storm.

Simplify the Equations (Because We’re Lazy)

Our simplified model ditches the quadratic tantrums of the original equations. Instead, we’ve got:

  1. Exercise Phase (\(x(t)\)):

\[ \frac{dx}{dt} = -\lambda (\beta - x) \cdot \psi_{\text{exercise}}(t) \]

  1. Recovery Phase (\(y(t)\)):

\[ \frac{dy}{dt} = -\phi (-c\beta - y) \cdot \psi_{\text{recovery}}(t) \]

Translation:
- \(\lambda\) (lambda): How fast your heart yeets itself into panic mode.
- \(\phi\) (phi): How lazily it crawls back to Netflix.
- \(\psi_{exercise}\) and \(\psi_{recovery}\): Sigmoidal switches that say “Panic now!” and “Ok, nap time.”

Code This in R (Because Excel Was Too Mainstream)

Let’s translate this into R code. We’ll need:
1. Parameters (plucked from elderly step-test data).
2. Time grid (because time is an illusion, but simulations aren’t).
3. A loop that updates \(x\) and \(y\) like a clingy ex.

Here’s the code, annotated with sarcasm and questionable life choices:

# --------------------------
# Set Parameters (Grandma's Fitness Diary)
# --------------------------
params <- c(
  alpha = 861.78,   # Baseline RRi (ms). Basically your heart's zen mode.
  beta = -345.49,   # How hard RRi crashes. Negative = midlife crisis.
  lambda = -3.05,   # Speed of crash. Negative? Blame the math.
  phi = -2.60,      # Speed of recovery. Also negative. Blame the patriarchy.
  tau = 6.71,       # Exercise starts at 6.71 min. Plot twist!
  delta = 3.24,     # Recovery starts after 3.24 min of regret.
  c = 0.84          # Recovery proportion. "I'll do 84% better next time."
)

# --------------------------
# Define Activation Functions (The Drama Switches)
# --------------------------
# Sigmoidal switches to gatekeep the chaos

psi_exercise <- function(t) {
  1 / (1 + exp(params["lambda"] * (t - params["tau"])))  # lambda is negative, so this flips
}

psi_recovery <- function(t) {
  1 / (1 + exp(params["phi"] * (t - params["tau"] - params["delta"])))  # same logic
}

# --------------------------
# Euler's Method Loop (The Heart of the Simulation)
# --------------------------
# Time grid: 0 to 20 min, steps of 0.1 min (because we're extra)

time_steps <- seq(0, 20, by = 0.01)
n_steps <- length(time_steps)

# Initialize arrays to store x, y, and RRi

x <- numeric(n_steps)
y <- numeric(n_steps)
RRi <- numeric(n_steps)

# Initial conditions: x=0 (no panic), y=0 (no recovery)

x[1] <- 0
y[1] <- 0
RRi[1] <- params["alpha"] + x[1] + y[1]

# Loop through time like it's 1999

for (k in 1:(n_steps - 1)) {
  current_time <- time_steps[k]
  
  # --- Exercise Phase ---
  # Calculate dx/dt: -λ*(β - x) * ψ_exercise
  dxdt <- -params["lambda"] * (params["beta"] - x[k]) * psi_exercise(current_time)
  
  # --- Recovery Phase ---
  # Calculate dy/dt: -φ*(-cβ - y) * ψ_recovery
  dydt <- -params["phi"] * (-params["c"] * params["beta"] - y[k]) * psi_recovery(current_time)
  
  # Update x and y using Euler's method
  x[k + 1] <- x[k] + 0.01 * dxdt  # Δt = 0.1 min
  y[k + 1] <- y[k] + 0.01 * dydt
  
  # Total RRi = baseline + panic + redemption
  RRi[k + 1] <- params["alpha"] + x[k + 1] + y[k + 1]
}

# --------------------------
# Plot the Trauma (For Clout)
# --------------------------

# Bundle results into a dataframe

df <- data.frame(
  Time = time_steps,
  RRi = RRi,
  Phase = ifelse(time_steps < params["tau"], "Rest",
              ifelse(time_steps < params["tau"] + params["delta"], "Exercise", "Recovery"))
)

# Plot with ✨aesthetic✨
fig <- ggplot(df, aes(x = Time, y = RRi, color = Phase)) +
  geom_line(linewidth = 1.5) +
  scale_color_manual(values = c("Rest" = "#00BFC4", "Exercise" = "#F8766D", "Recovery" = "#7CAE00")) +
  labs(
    title = "Your Heart's Zumba Class, Simulated",
    subtitle = "Simplified linear model: Because drama sells",
    x = "Time (min)",
    y = "RR Interval (ms)"
  ) +
  theme(legend.position = "bottom")

Run It and Pray to the Code Gods

Execute this code, and voilà, your plot will look like this:

plot(fig)

Key Features we can see here:

  • Resting Phase (t < \(\tau\)): Flatline. Boring. Perfect. Your heart’s version of “I’m just here for the snacks.”
  • Exercise Phase (\(\tau\) ≤ t < \(\tau + \delta\)): RRi nosedives like your will to live during burpees.
  • Recovery Phase (t ≥ \(\tau + \delta\)): RRi crawls back up, slower than your post-workout laundry motivation.

Why This Works (and Why It’s Flawed)

Pros:

  • Speed: Simulates faster than you can say “existential crisis.”
  • Transparency: Parameters slap you with meaning. \(\lambda\)? Panic speed. \(\phi\)? Recovery laziness.
  • Stability: No chaotic surprises. It’s like replacing a rollercoaster with a rocking chair.

Cons:

  • Linear ≠ Real Life: Hearts aren’t straight lines. This model misses the spicy saturation of the original equations.
  • Euler’s Jank: Tiny errors accumulate like dirty laundry. Use Runge-Kutta if you’re fancy.
  • Grandma Bias: Parameters fit for seniors. Not tested on CrossFit junkies or couch potatoes.

Real-World Uses (Because Science Pays the Bills)

  1. Wearable Tech: Power fitness apps that nag you with “YOUR HEART IS 84% RECOVERED. GO RUN.”
  2. Personalized Training: Adjust τ and δ to find your optimal workout-recovery ratio.
  3. Rehab Monitoring: Track if patients are doing their exercises or just Googling “is napping cardio?”

Simulating hearts is like writing fanfiction: fun, slightly unhinged, and nobody knows if it’s accurate. But hey, at least we’re not using Fortran.

Your Heart’s Dramatic Arc, Now with More Math

Let’s take a breath. We’ve just spent an ungodly amount of time simulating your heart’s existential crisis using differential equations, which is either a flex or a cry for help, jury’s still out. But before we pat ourselves on the back (or check into therapy), let’s unpack what we’ve actually done, why it’s both cool and slightly unhinged, and where we go from here.

In short, we took Castillo-Aguilar et al.’s original model, a sleek, elegant equation that already captured the U-shaped rollercoaster of RR intervals during exercise and recovery, and gave it a glow-up. Think of it like adapting a bestselling novel into a limited series. The original formula was the literary masterpiece: concise, powerful, and publishable in Nature. It used two logistic functions to summarize the entire cardiac saga, the nosedive during exercise, the slow crawl back to baseline, into a single snapshot. But we’re greedy. We wanted to see the action unfold frame by frame, like binge-watching your heart’s midlife crisis on Netflix. So we decomposed the model into two dynamic variables, \(x(t)\) and \(y(t)\), and wrote differential equations to describe their tantrums. The result? A flipbook version of the original, where every panic attack and recovery sigh is animated in calculus.

Now, let’s address the elephant in the room: Why bother? The original model already worked beautifully. It was the Marie Kondo of exercise physiology, simple, effective, and sparking joy in reviewers’ hearts. But here’s the thing: static equations are like long-exposure photos. They capture the whole trajectory in one shot, perfect for summarizing data or calculating parameters over a coffee break. Our dynamical system, on the other hand, is the shaky cam footage of a documentary crew chasing your heart through a spin class. It shows how the crash happens, when the recovery kicks in, and why your ANS oscillates between “fight-or-flight” and “nap time” like a toddler on a sugar crash. This isn’t about replacing the original, it’s about giving it a director’s commentary.

The technical nitty-gritty? The original model’s logistic curves implicitly handled timing through parameters like \(\tau\) (exercise onset) and \(\delta\) (recovery delay). We made this explicit by adding sigmoidal activation functions, smooth on/off switches that act like stage managers cueing the chaos. It’s not revolutionary; it’s just turning the volume knob instead of slamming it. And while the original Sobol analysis crowned \(\alpha\) (baseline RRi) as the protagonist, our dynamical framing lets us spotlight supporting characters like \(\lambda\) (crash speed) and \(\phi\) (recovery speed) in specific acts. It’s like realizing the quiet sidekick actually has a killer monologue.

But let’s not kid ourselves, this isn’t a flawless victory. The original model’s simplicity is its superpower. It’s the Swiss Army knife of cardiac analysis: robust, interpretable, and ready for clinical prime time. Our dynamical system? It’s the overengineered gadget from a spy movie. Cool to simulate, but good luck explaining it to a cardiologist without a whiteboard and a stiff drink. Still, the exercise is valuable. By reframing the model as a system of equations, we can now ask new questions: Does the heart panic faster if you sprint versus jog? Is recovery slower if you skip leg day? These aren’t just academic quirks, they’re potential hooks for personalized medicine, rehab protocols, or even biofeedback apps that scream, “YOUR PARASYMPATHETIC SYSTEM IS ON VACATION!” during Zoom meetings.

So, what’s next? First, validation. Our model was trained on grandma’s step test data, which is like testing a race car in a school zone. We need to see if it holds up for younger, fitter, or more chaotic hearts. Athletes, for example, might have Jedi-level parasympathetic recovery that breaks our equations. Then there’s the noise problem. Real-world data has more artifacts than a Marvel movie, sneezes, caffeine spikes, existential dread, and our pristine simulations don’t account for that. Future work could add stochasticity (math speak for “life happens”) or time-varying parameters to model stress-induced meltdowns.

And let’s not forget the holy grail: real-time monitoring. Imagine wearables that don’t just count steps but predict cardiac drama before it happens. This would require ditching Euler’s method, the “hold my beer” of numerical integration, for faster algorithms like Runge-Kutta or neural networks. Bonus points if we integrate this with AI to guess your workout intensity from your Spotify playlist (“User played ‘Eye of the Tiger’, simulate \(\lambda\) = 10”).

But perhaps the most exciting frontier is cross-disciplinary chaos. Linking RRi dynamics to mental health? Imagine flagging anxiety disorders via permanent \(\psi_{exercise}\) mode. Or simulating how beta-blockers or espresso shots tweak the equations. Heck, we could even sell RRi simulations as NFTs, CryptoCardio, anyone?

In the end, none of this would exist without Castillo-Aguilar et al.’s original work. They did the heavy lifting, crafting a simple, interpretable model that captured non-linear RRi dynamics when everyone else was stuck in linear la-la land. It’s the Citizen Kane of exercise physiology: groundbreaking, elegant, and still relevant years later. Our dynamical system is just a fan sequel, Citizen Kane II: Rosebud’s Revenge. Louder, flashier, and with more explosions (read: differential equations). But without the original’s genius, we’d be stuck modeling heartbeats with stick figures.

So here’s to the future: more research, more chaos, and hopefully fewer existential crises, both cardiac and academic. Until then, keep calm and differentiate on. Your heart sure is.

Appendix

Check the original paper where the model is presented here.

Citation

BibTeX citation:
@misc{castillo-aguilar2025,
  author = {Castillo-Aguilar, Matías},
  title = {From {Heartbeats} to {Dynamical} {Systems}},
  date = {2025-03-28},
  url = {https://bayesically-speaking.com/posts/2025-XX-XX from-heartbeats-to-dynamical-systems/},
  langid = {en}
}
For attribution, please cite this work as:
Castillo-Aguilar, Matías. 2025. “From Heartbeats to Dynamical Systems.” March 28, 2025. https://bayesically-speaking.com/posts/2025-XX-XX from-heartbeats-to-dynamical-systems/.