---
title: "Introduction to Derivatives — A Car on the Road"
subtitle: "Preparatory Lesson: What Does «Rate of Change» Mean?"
output:
  html_document:
    toc: true
    toc_float: true
    theme: flatly
    highlight: tango
    code_folding: show
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo    = TRUE,      # Show the R code
  message = FALSE,
  warning = FALSE,
  fig.width  = 8,
  fig.height = 4.5
)
```

---

## 🎯 Goal of the Lesson

Before we study how populations grow, we need a basic idea from
mathematics: the **derivative**.

> **The derivative of a function tells us how fast it changes.**

Instead of abstract formulas, we will start with something very familiar:
**a car moving along a road.**

---

## 🚗 The Story of the Car

Imagine a car that:

- **Phase A (0–30 seconds):** Moves at a **constant speed** of 20 m/s.
  It does not accelerate, it does not brake — steady motion.

- **Phase B (30–60 seconds):** Steps on the gas and **accelerates** smoothly.
  Its speed increases from 20 m/s to 50 m/s.

The question: How are **distance**, **speed** and **acceleration** connected?

---

## ⚙️ Step 1 — Defining Time and Parameters

```{r parameters}
# -------------------------------------------------------
# We define the time scale of the motion
# seq() creates a sequence of values
# from 0 to 60 seconds, with a step of 0.1 sec
# -------------------------------------------------------
t <- seq(0, 60, by = 0.1)   # time in seconds

# Phase A parameters — constant motion
v0 <- 20        # initial speed (m/s)
t_switch <- 30  # moment when acceleration begins (sec)

# Phase B parameter — acceleration
# We want the speed to go from 20 → 50 m/s between t=30 and t=60
# So: a = Δv / Δt = (50 - 20) / (60 - 30) = 1 m/s²
a <- 1          # acceleration (m/s²)
```

---

## ⚙️ Step 2 — Computing the Speed

The speed changes depending on the phase:

$$
v(t) = \begin{cases}
20 & \text{if } t \leq 30 \\
20 + 1 \cdot (t - 30) & \text{if } t > 30
\end{cases}
$$

```{r velocity}
# -------------------------------------------------------
# ifelse() works like a choice:
#   if the condition is TRUE  → first value
#   if the condition is FALSE → second value
#
# Here: if t <= 30, speed = v0 (constant)
#        if t >  30, speed increases linearly
# -------------------------------------------------------
v <- ifelse(
  t <= t_switch,
  v0,                          # Phase A: constant speed
  v0 + a * (t - t_switch)      # Phase B: v = v₀ + a·(t - 30)
)
```

---

## ⚙️ Step 3 — Computing the Distance

The distance is the **integral** of the speed (or equivalently:
the speed is the **derivative** of the distance).

$$
x(t) = \begin{cases}
v_0 \cdot t & \text{if } t \leq 30 \\
v_0 \cdot 30 + v_0(t-30) + \frac{1}{2}a(t-30)^2 & \text{if } t > 30
\end{cases}
$$

```{r distance}
# -------------------------------------------------------
# Phase A: x = v₀ · t  (uniform straight-line motion)
# Phase B: x = distance of Phase A at t=30
#           + v₀·(t-30) + ½·a·(t-30)²
#
# First we compute the distance covered
# up to the moment t=30 (end of Phase A)
# -------------------------------------------------------
x_at_switch <- v0 * t_switch   # = 20 × 30 = 600 meters

x <- ifelse(
  t <= t_switch,
  v0 * t,                                              # Phase A
  x_at_switch + v0 * (t - t_switch) + 0.5 * a * (t - t_switch)^2  # Phase B
)
```

---

## ⚙️ Step 4 — Computing the Acceleration

The acceleration is the **derivative** of the speed.

```{r acceleration}
# -------------------------------------------------------
# Phase A: speed constant → does not change → acceleration = 0
# Phase B: speed increases by 1 m/s every second
#          → acceleration = 1 m/s²
# -------------------------------------------------------
acc <- ifelse(t <= t_switch, 0, a)
```

---

## 📊 Step 5 — The Plots

Now we will see the three quantities visually.
Notice how the **shape** of each plot changes at 30 seconds.

```{r plots, fig.height=11, fig.width=8}
# -------------------------------------------------------
# par(mfrow = c(3, 1)) → splits the graphics window
# into 3 rows and 1 column (the 3 plots one below
# the other)
# mar = c(bottom, left, top, right) → margins in lines
# -------------------------------------------------------
par(mfrow = c(3, 1), mar = c(4.5, 5, 3, 2))

# --- Plot 1: Distance vs Time ---
plot(t, x,
     type = "l",           # "l" = line
     lwd  = 2.5,           # line width
     col  = "#2C7BB6",     # color (blue)
     xlab = "Time (sec)",
     ylab = "Distance x (m)",
     main = "Distance versus Time  —  x(t)",
     cex.main = 1.3, cex.lab = 1.1)

# Vertical dashed line at t=30 (phase change)
abline(v = t_switch, lty = 2, col = "gray50")
text(31, max(x) * 0.15, "Start of\nacceleration",
     adj = 0, col = "gray40", cex = 0.9)

# Label for each phase
text(13, max(x) * 0.85, "Phase A\n(straight line)", col = "#2C7BB6", cex = 0.95)
text(47, max(x) * 0.20, "Phase B\n(parabola)", col = "#2C7BB6", cex = 0.95)

# -------------------------------------------------------
# Tangent line in the acceleration phase
# We pick the moment t₀ = 45 sec
# At this point:
#   - the distance is x(45)
#   - the slope of the tangent = derivative = v(45)
# -------------------------------------------------------
t0   <- 45                                                # moment
x_t0 <- x_at_switch + v0*(t0 - t_switch) + 0.5*a*(t0 - t_switch)^2
v_t0 <- v0 + a*(t0 - t_switch)        # instantaneous speed = slope of tangent

# Equation of the tangent line: y = x(t₀) + v(t₀) · (t - t₀)
t_tan <- seq(t0 - 10, t0 + 10, length.out = 50)
y_tan <- x_t0 + v_t0 * (t_tan - t0)

# We draw the tangent
lines(t_tan, y_tan, col = "#E66101", lwd = 2.5)

# Point of contact (dot)
points(t0, x_t0, pch = 19, col = "#E66101", cex = 1.6)

# Annotation with arrow
arrows(x0 = 53, y0 = x_t0 + 280,
       x1 = t0 + 0.5, y1 = x_t0 + 30,
       length = 0.1, col = "#E66101", lwd = 1.5)
text(53.5, x_t0 + 320,
     paste0("slope of tangent\n= v(", t0, ") = ", v_t0, " m/s"),
     col = "#E66101", cex = 0.9, adj = 0)

# --- Plot 2: Speed vs Time ---
plot(t, v,
     type = "l",
     lwd  = 2.5,
     col  = "#1A9641",    # green
     xlab = "Time (sec)",
     ylab = "Speed v (m/s)",
     main = "Speed versus Time  —  v(t) = dx/dt",
     cex.main = 1.3, cex.lab = 1.1)

abline(v = t_switch, lty = 2, col = "gray50")
text(31, max(v) * 0.25, "Start of\nacceleration",
     adj = 0, col = "gray40", cex = 0.9)

# Arrow showing that the slope of the line = acceleration
text(40, 32, "slope = a = 1 m/s²", col = "#1A9641", cex = 0.9)

# --- Plot 3: Acceleration vs Time ---
plot(t, acc,
     type = "l",
     lwd  = 2.5,
     col  = "#D7191C",    # red
     xlab = "Time (sec)",
     ylab = "Acceleration a (m/s²)",
     main = "Acceleration versus Time  —  a(t) = dv/dt",
     ylim = c(-0.3, 1.5),
     cex.main = 1.3, cex.lab = 1.1)

abline(v = t_switch, lty = 2, col = "gray50")
abline(h = 0, lty = 3, col = "gray70")
text(31, 1.3, "Start of\nacceleration",
     adj = 0, col = "gray40", cex = 0.9)
```

---

## 🔎 The Tangent and the Instantaneous Speed

In the first plot we just added a **tangent line** to the distance
curve, at the point t = 45 sec.

> 💡 **The central geometric idea:**
> The **slope** of the tangent line at any point of the distance
> curve gives us the **instantaneous speed** at exactly that moment
> in time.

The **steeper** (larger angle with the horizontal axis) the tangent is,
the **greater** the instantaneous speed.

Let us see it by drawing **multiple tangents** at different moments
in time:

```{r multiple_tangents, fig.height=6}
# -------------------------------------------------------
# We choose four moments in time to show
# how the slope of the tangent changes along the curve
# -------------------------------------------------------
t_points <- c(15, 35, 45, 55)   # moments for the tangents
colors_t <- c("#1A9641", "#FDAE61", "#E66101", "#D7191C")

par(mar = c(4.5, 5, 3, 2))

# Distance curve
plot(t, x,
     type = "l", lwd = 2.5, col = "#2C7BB6",
     xlab = "Time (sec)", ylab = "Distance x (m)",
     main = "The slope of the tangent = instantaneous speed",
     cex.main = 1.2)

abline(v = t_switch, lty = 2, col = "gray60")

# -------------------------------------------------------
# Loop: for each moment in time we compute
#   - the position x(ti)
#   - the instantaneous speed v(ti) (= slope of tangent)
#   - and we draw the tangent
# -------------------------------------------------------
for (i in seq_along(t_points)) {

  ti <- t_points[i]

  # Position at the point of contact
  if (ti <= t_switch) {
    xi <- v0 * ti                                           # Phase A
    vi <- v0                                                # constant speed
  } else {
    xi <- x_at_switch + v0*(ti - t_switch) + 0.5*a*(ti - t_switch)^2
    vi <- v0 + a*(ti - t_switch)                            # accelerating
  }

  # Tangent: y = xi + vi · (t - ti)
  tt <- seq(ti - 6, ti + 6, length.out = 30)
  yy <- xi + vi * (tt - ti)

  lines(tt, yy, col = colors_t[i], lwd = 2)
  points(ti, xi, pch = 19, col = colors_t[i], cex = 1.4)

  # Label with the instantaneous speed
  text(ti, xi - 130,
       paste0("t=", ti, "s\nv=", vi, " m/s"),
       col = colors_t[i], cex = 0.85, font = 2)
}

legend("topleft",
       legend = "Distance curve x(t)",
       col    = "#2C7BB6", lty = 1, lwd = 2.5,
       bty    = "n", cex = 0.95)
```

### What we observe

| Moment | Slope of tangent | Instantaneous speed |
|--------|---------------------|---------------------|
| t = 15 s (Phase A) | Moderate — constant | 20 m/s |
| t = 35 s (Phase B, early) | A bit steeper | 25 m/s |
| t = 45 s (Phase B, middle) | Steeper | 35 m/s |
| t = 55 s (Phase B, end) | Very steep | 45 m/s |

**In Phase A** all the tangents have the **same slope** — because the curve
is a straight line, the line is its own tangent. So the speed is
constant (20 m/s).

**In Phase B** each tangent is **steeper** than the previous one.
This means: the speed **increases** — that is, we have acceleration.

### Conclusion

$$
v(t_0) = \frac{dx}{dt}\bigg|_{t=t_0} = \text{slope of the tangent of } x(t) \text{ at } t_0
$$

> **This is exactly the geometric meaning of the derivative:**
> the derivative at a point = slope of the tangent line at that point.

---

## 💡 Step 6 — What Do We See? The Central Idea

Look at the three plots together and observe:

| Plot | Phase A (0–30 sec) | Phase B (30–60 sec) |
|---------|-------------------|---------------------|
| **Distance** x(t) | Straight line | Curve (parabola) |
| **Speed** v(t) | Horizontal line | Rising line |
| **Acceleration** a(t) | = 0 | = 1 m/s² (constant) |

### The connection:

$$\boxed{v(t) = \frac{dx}{dt}} \qquad \text{and} \qquad \boxed{a(t) = \frac{dv}{dt} = \frac{d^2x}{dt^2}}$$

> **In simple terms:**
> - The **speed** tells us how fast the **position** changes.
> - The **acceleration** tells us how fast the **speed** changes.
> - This is exactly the relationship that the **derivative** expresses.

---

## 🔍 Step 7 — The Derivative Numerically (Optional)

We don't need formulas to compute (approximately) the derivative.
It is enough to see **how much the function changes over a very small step in time**.

```{r numerical_derivative}
# -------------------------------------------------------
# diff() computes the differences between consecutive values
# E.g. diff(c(1, 3, 6)) → c(2, 3)
#
# The numerical derivative: dx/dt ≈ Δx / Δt
# Δt = 0.1 sec (the step of t we defined at the start)
# -------------------------------------------------------
dt <- 0.1

# Numerical derivative of distance → should resemble v
v_numerical <- diff(x) / dt

# Numerical derivative of speed → should resemble acc
a_numerical <- diff(v) / dt

# The time for the derivatives has one element less
t_deriv <- t[-1]   # we remove the first element

# Comparison: numerical vs analytical speed
cat("Maximum deviation v_numerical vs v_analytical:",
    round(max(abs(v_numerical - v[-1])), 4), "m/s\n")
```

```{r comparison_plot, fig.height=5}
# -------------------------------------------------------
# Visual comparison: analytical speed (line)
# vs numerical derivative (dashed)
# -------------------------------------------------------
par(mar = c(4.5, 5, 3, 2))

plot(t, v,
     type = "l", lwd = 2.5, col = "#1A9641",
     xlab = "Time (sec)", ylab = "Speed (m/s)",
     main = "Speed: Analytical vs Numerical Derivative",
     cex.main = 1.2)

lines(t_deriv, v_numerical,
      lty = 2, lwd = 2, col = "#D7191C")

legend("topleft",
       legend = c("Analytical v(t)", "Numerical  dx/dt"),
       col    = c("#1A9641", "#D7191C"),
       lty    = c(1, 2), lwd = 2,
       bty    = "n", cex = 1.0)
```

> The two curves **coincide almost perfectly** — this confirms that
> the derivative of the distance is indeed the speed!

---

## 🌿 Connection to Biology

Why do we learn these things in a biology course?

In biology we are often interested in **the rate** at which something changes:

| Biological Quantity | «Distance» | «Speed» (derivative) |
|---------------------|------------|--------------------------|
| Population size N(t) | N | dN/dt = growth rate |
| Drug concentration C(t) | C | dC/dt = excretion rate |
| Biomass B(t) | B | dB/dt = production rate |

> In the next lessons we will see exactly this: how the **rate of change of
> the population** (i.e. the derivative dN/dt) determines whether a population grows,
> shrinks or stabilizes.

---

## ✏️ Comprehension Questions

1. In Phase A, the distance-time graph is a **straight line**.
   What does this mean for its derivative (= speed)?

2. In Phase B, the distance follows a **parabola**. What shape does the speed have?
   And the acceleration?

3. If a population of bacteria grows exponentially, how do you expect
   the graph of the **growth rate** dN/dt versus time to look?

---

*In the next lesson: Exponential Population Growth — N(t) = N₀ · e^(r·t)*
