CogSci 132 Assignment1 HH Model

Soliana Yohannes and Jiyun Woo · Spring 2025

In [19]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.core.debugger import set_trace
In [20]:
def check_type(y,t): # Ensure Input is Correct
    return y.dtype == np.floating and t.dtype == np.floating

class _Integrator():
    
    def integrate(self,func,y0,t):
        time_delta_grid = t[1:] - t[:-1]
        
        y = np.zeros((y0.shape[0],t.shape[0]))
        y[:,0] = y0
        
        # Euler Step or Runge-Kutta Second Order Integration Step
        for i in range(time_delta_grid.shape[0]):
            y[:,i+1] = time_delta_grid[i]*func(y[:,i],t[i])+y[:,i] # Euler Integration Step
            
            #Un-Comment the next three lines to use the Runge-Kutta Second Order Integration
            #k1=(1/2)*time_delta_grid[i]*func(y[:,i],t[i])
            #breakpoint()
            #y[:,i+1] = y[:,i]+time_delta_grid[i]*func(y[:,i]+k1,t[i]+time_delta_grid[i]/2)
            
            
        return y
       
        #Runge-Kutta Fourth Order Integration Step
        #for i in range(time_delta_grid.shape[0]):
            #k1 = func(y[:,i], t[i])# RK4 Integration Steps replace Euler's Updation Steps
            #half_step = t[i] + time_delta_grid[i] / 2
            #k2 = func(y[:,i] + time_delta_grid[i] * k1 / 2, half_step)
            #k3 = func(y[:,i] + time_delta_grid[i] * k2 / 2, half_step)
            #k4 = func(y[:,i] + time_delta_grid[i] * k3, t[i] + time_delta_grid[i])
            #y[:,i+1]= (k1 + 2 * k2 + 2 * k3 + k4) * (time_delta_grid[i] / 6) + y[:,i]
        #return y
        

def odeint_rk4(func,y0,t):
    y0 = np.array(y0)
    t = np.array(t)
    if check_type(y0,t):
        return _Integrator().integrate(func,y0,t)
    else:
        print("error encountered")
In [21]:
C_m = 1      # Membrane Capacitance

g_K = 10
E_K = -95

g_Na = 100
E_Na = 50 

g_L = 0.15
E_L = -55
In [22]:
def f(x):
    
    if abs(x)<1e-12: 
        x=1
    elif x < -20:
        ex = np.exp(x)
        x = -x*ex/(1-ex)
    else: 
        x = x/(1-np.exp(-x))
    return x

def g(x):
    if abs(x)<1e-12: 
        x=1
    else:
        x = x/(np.exp(x)-1)
    return x

def h(x):
    if x < -20:
        x = np.exp(x)/(np.exp(x)+1)
    else: x = 1/(1+np.exp(-x))
    return x

def K_prop(v):

#αn(V ) = 0.032(V + 52)/(1 − exp(−(V + 52)/5))
    def alpha_n(v):
        u= (v+52)/5
        return 0.032*5*f(u)
    beta_n=0.5*np.exp(-(v+65)/80)

    def n_inf(v):
        return (alpha_n(v)/(alpha_n(v)+ beta_n))
        #set_trace()
    def tau_n(v):
        return (1/(alpha_n(v)+beta_n))
    #set_trace()
    return n_inf(v), tau_n(v)


def Na_prop(v):
    
#αm(V) = 0.32(V + 54)/(1 − exp(−(V + 54)/4))
#βm (V ) = 0.28(V + 27)/(exp((V + 27)/5) − 1)

    def alpha_m(v):
        u = (v+54)/4
        return 4*0.32*f(u)
    
    def beta_m(v):
        u =(v+27)/5
        return 5*0.28*g(u)

    def m_inf(v):
        return (alpha_m(v)/(alpha_m(v)+beta_m(v)))
    
    def tau_m(v):
        return (1 / (alpha_m(v) + beta_m(v)))

#αh(V) = 0.128 exp(−(V + 50)/18)
#βh(V) = 4/(1 + exp(−(V + 27)/5)

    alpha_h = 0.128*np.exp(-(v+50)/18)
                                 
    def beta_h(v):
        u = (v+27)/5
        return 4*h(u)
    
    def h_inf(v):
        return (alpha_h/(alpha_h+beta_h(v)))
    
    def tau_h(v):
        return 1/(alpha_h+beta_h(v))
    #set_trace()
    
    return m_inf(v), tau_m(v), h_inf(v), tau_h(v)


def alpha_n(V): return 0.032 * (V + 52) / (1 - np.exp(-(V + 52) / 5))
def beta_n(V): return 0.5 * np.exp(-(V + 65) / 80)
def alpha_m(V): return 0.32 * (V + 54) / (1 - np.exp(-(V + 54) / 4))
def beta_m(V): return 0.28 * (V + 27) / (np.exp((V + 27) / 5) - 1)
def alpha_h(V): return 0.128 * np.exp(-(V + 50) / 18)
def beta_h(V): return 4 / (1 + np.exp(-(V + 27) / 5))

def n_inf(V): return alpha_n(V) / (alpha_n(V) + beta_n(V))
def tau_n(V): return 1 / (alpha_n(V) + beta_n(V))
def m_inf(V): return alpha_m(V) / (alpha_m(V) + beta_m(V))
def tau_m(V): return 1 / (alpha_m(V) + beta_m(V))
def h_inf(V): return alpha_h(V) / (alpha_h(V) + beta_h(V))
def tau_h(V): return 1 / (alpha_h(V) + beta_h(V))

def I_Na(V, m, h): return g_Na * (m**3) * h * (V - E_Na)
def I_K(V, n): return g_K * (n**4) * (V - E_K)
def I_L(V): return g_L * (V - E_L)
In [23]:
def I_K(V, n):
    return g_K  * n**4 * (V - E_K)

def I_Na(V, m, h):
    return g_Na * m**3 * h * (V - E_Na)

def I_L(V):
    return g_L * (V - E_L)
In [24]:
def gPot(n):
    return g_K * n**4

def gSod():
    return g_Na * m**3 * h
In [25]:
def run_HH(v_clamp):
    
    def dXdt(X,t):
        V = v_clamp
        #V = X[0:1]
        m = X[0:1]
        h = X[1:2]
        n = X[2:3]

        #dVdt = (5 - I_Na(V, m, h) - I_K(V, n) - I_L(V)) / C_m 
        # Here the current injection I_injected = 5 uA
        
        
        
        n0,tn = K_prop(V)
        #set_trace()
        m0,tm,h0,th = Na_prop(V)
        
        dmdt = - (1.0/tm)*(m-m0)
        dhdt = - (1.0/th)*(h-h0)
        dndt = - (1.0/tn)*(n-n0)

        out = np.concatenate([dmdt,dhdt,dndt],0)
        return out

    V=v_clamp
    epsilon = 0.01
    t = np.arange(0, 30, epsilon)
    y0 = np.float64([0,1,0])
    
    state = odeint_rk4(dXdt, y0, t)
    

    #V = state[3]
    m = state[0]
    h = state[1]
    n = state[2]
    
    i_na = I_Na(V, m, h)
    i_k = I_K(V, n)
    i_l = I_L(V)
    i_m = i_na + i_k + i_l
    
    fig, ax = plt.subplots(1)
    ax.set_title("Voltage Clamp = " + str(v_clamp) + "V")
    ax.set_xlabel("Time")
    ax.plot(t, m**3, label = "m^3")
    ax.plot(t, h, label = "h")
    ax.plot(t, m**3*h, label= "m^3h")
    ax.legend()
    
    return #state, i_na, i_k, i_l, i_m

1. HH Model V-clamp at v=(0, 30, 60)

In [26]:
def run_HH_K_Na(v_clamp):
    
    def dXdt(X,t):
        V = v_clamp
        #V = X[0:1]
        m = X[0:1]
        h = X[1:2]
        n = X[2:3]
        
        n0,tn = K_prop(V)
        #set_trace()
        m0,tm,h0,th = Na_prop(V)
        
        dmdt = - (1.0/tm)*(m-m0)
        dhdt = - (1.0/th)*(h-h0)
        dndt = - (1.0/tn)*(n-n0)

        out = np.concatenate([dmdt,dhdt,dndt],0)
        return out


    V=v_clamp
    epsilon = 0.01
    t = np.arange(0, 5, epsilon)
    values_Na=Na_prop(-65)
    m_inf = values_Na[0]
    h_inf = values_Na[2]
    values_k=K_prop(-65)
    n_inf = values_k[0]
    y0 = [m_inf, h_inf, n_inf]
    
    state = odeint_rk4(dXdt, y0, t)
    

    #V = state[3]
    m = state[0]
    h = state[1]
    n = state[2]
    
    i_na = I_Na(V, m, h)
    i_k = I_K(V, n)
    i_l = I_L(V)
    i_m = i_na + i_k + i_l

    return t, i_na, i_k

voltages = [0, 30, 60]
V_currents = [run_HH_K_Na(V) for V in voltages]


plt.figure(figsize=(12, 6))
for i, (t, i_na, i_k) in enumerate(V_currents):
    plt.plot(t, i_na, label=f"I_Na (V={voltages[i]} mV)")
    plt.plot(t, i_k, label=f"I_K (V={voltages[i]} mV)")

plt.xlabel("Time (ms)")
plt.ylabel("Current")
plt.title("Voltage-Clamp: Na and K Currents")
plt.legend()
plt.show()
/tmp/ipykernel_76/2954535638.py:2: DeprecationWarning: Converting `np.inexact` or `np.floating` to a dtype is deprecated. The current result is `float64` which is not strictly correct.
  return y.dtype == np.floating and t.dtype == np.floating
No description has been provided for this image

Explanation of Na current:

In the voltage-clamp experiment, we see how Na ions flow at different voltage steps (0 mV, +30 mV, and +60 mV)

At 0 mV, Na channels open quickly, causing a strong inward current as Na rushes into the cell due to the large driving force (V - E_Na = -50 mV). With time inactivation reduces the current

At +30 mV, Na still enters the cell, but the inward current is smaller because the driving force is weaker (V - E_Na = -20 mV). Inactivation happens faster at this voltage.

At +60 mV, the voltage exceeds the sodium reversal potential (E_Na = +50 mV), causing Na to enter briefly before reversing direction and exiting the membrane. This results in an outward Na current (V - E_Na = +10 mV)

In [ ]:
 

2. Activation, Inactivation and Time Constant Plots

Activation and Inactivation Curves

In [27]:
V_values = np.linspace(-100, 50, 500)

m_inf_values, tau_m_values, h_inf_values, tau_h_values = zip(*[Na_prop(V) for V in V_values])
n_inf_values, tau_n_values = zip(*[K_prop(V) for V in V_values])

m_inf_values = np.array(m_inf_values)
h_inf_values = np.array(h_inf_values)
n_inf_values = np.array(n_inf_values)

tau_m_values = np.array(tau_m_values)
tau_h_values = np.array(tau_h_values)
tau_n_values = np.array(tau_n_values)

#plot
plt.figure(figsize=(12, 6))
plt.plot(V_values, m_inf_values, label="Na activation")
plt.plot(V_values, h_inf_values, label="Na inactivation")
plt.plot(V_values, n_inf_values, label="K activation")

plt.xlabel("Membrane Voltage (mV)")
plt.ylabel("Values at Steady-State")
plt.title("Activation and Inactivation Curves")
plt.legend()
plt.show()
No description has been provided for this image
In [ ]:
 

Time Contants

In [28]:
#plotting using above values 
plt.figure(figsize=(12, 6))
plt.plot(V_values, tau_m_values, label="Na Activation")
plt.plot(V_values, tau_h_values, label="Na Inactivation")
plt.plot(V_values, tau_n_values, label="K Activation")

plt.xlabel("Membrane Voltage (mV)")
plt.ylabel("Time Constant (ms)")
plt.title("Channels' Time Constants ")
plt.legend()
plt.show()
No description has been provided for this image

Explanation of Activation and Inactivation Curves and Time Contants

The activation and inactivation curves describe how ion channels respond to changes in voltage. The activation curves m_inf, n_inf show the probability of Na and K channels opening as the membrane depolarizes, with Na channels activating quickly, m_inf, and K channels activating more slowly, n_inf. However, the inactivation curve, h_inf, shows how Na channels begin to close at higher voltages, showing that depolarization is brief.

The time constants determine the speed at which these gating variables reach their steady state values. A small time constant means faster activation or inactivation, while a larger one means a slower response. Since Na activates and inactivates quickly, it allows the quick depolarization of an action potential while K with slower activation enables repolarization of the neuron. all these properties shape the action potentials timing and size and other properties.

In [ ]:
 

3. Solving HH Equations Using Euler method at Different Frequencies

In [29]:
#defined these functions outside the K and Na property functions 
def alpha_n(V): return 0.032 * (V + 52) / (1 - np.exp(-(V + 52) / 5))
def beta_n(V): return 0.5 * np.exp(-(V + 65) / 80)
def alpha_m(V): return 0.32 * (V + 54) / (1 - np.exp(-(V + 54) / 4))
def beta_m(V): return 0.28 * (V + 27) / (np.exp((V + 27) / 5) - 1)
def alpha_h(V): return 0.128 * np.exp(-(V + 50) / 18)
def beta_h(V): return 4 / (1 + np.exp(-(V + 27) / 5))

def n_inf(V): return alpha_n(V) / (alpha_n(V) + beta_n(V))
def tau_n(V): return 1 / (alpha_n(V) + beta_n(V))
def m_inf(V): return alpha_m(V) / (alpha_m(V) + beta_m(V))
def tau_m(V): return 1 / (alpha_m(V) + beta_m(V))
def h_inf(V): return alpha_h(V) / (alpha_h(V) + beta_h(V))
def tau_h(V): return 1 / (alpha_h(V) + beta_h(V))

def I_Na(V, m, h): return g_Na * (m**3) * h * (V - E_Na)
def I_K(V, n): return g_K * (n**4) * (V - E_K)
def I_L(V): return g_L * (V - E_L)


def simulate_HH(freq, amplitude, t_start=0, t_end=100, dt=0.01):
    t = np.arange(t_start, t_end, dt) 
    w = 2 * np.pi * freq / 1000 

    def sine_current(t):
        return amplitude * np.sin(w * t)

    def dXdt(X, t):
        V, m, h, n = X 

        I_Na_val = I_Na(V, m, h)
        I_K_val = I_K(V, n)
        I_L_val = I_L(V)
        I_ext = sine_current(t) 

        dVdt = (I_ext - I_Na_val - I_K_val - I_L_val) / C_m

        n0, tn = n_inf(V), tau_n(V)
        m0, tm, h0, th = m_inf(V), tau_m(V), h_inf(V), tau_h(V)

        dmdt = -(m - m0) / tm
        dhdt = -(h - h0) / th
        dndt = -(n - n0) / tn

        return np.array([dVdt, dmdt, dhdt, dndt])

    X0 = np.array([-65, m_inf(-65), h_inf(-65), n_inf(-65)])  

    num_steps = len(t)
    X = np.zeros((num_steps, len(X0)))
    X[0] = X0

    # Euler Integration
    for i in range(1, num_steps):
        dt_step = t[i] - t[i - 1]
        X[i] = X[i - 1] + dt_step * dXdt(X[i - 1], t[i])

    return t, X[:, 0], sine_current(t) 


def plot_response_variation(freq_list, stim_amplitude):
    fig, subplots = plt.subplots(len(freq_list), 1, figsize=(9, 12), sharex=True)
    plt.subplots_adjust(hspace=0.5)

    for ax, freq in zip(subplots, freq_list):
        time_vals, voltage_trace, input_current = simulate_HH(freq, stim_amplitude)

        ax.plot(time_vals, voltage_trace, label="Neuron Response (mV)")
        ax.plot(time_vals, input_current * 2, label="Applied Current (Scaled)")

        ax.set_title(f"Neural Response at {freq} Hz")
        ax.set_ylabel("Membrane Voltage (mV)")
        ax.set_xlim(time_vals[0], time_vals[-1])
        ax.set_ylim(-150 if freq < 1000 else -75, 50)

        ax.legend()
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)

    subplots[-1].set_xlabel("Time (ms)")
    plt.tight_layout()
    plt.show()

# Run the modified simulation
freq_values = [50, 100, 500, 1000]
stim_intensity = 10  

plot_response_variation(freq_values, stim_intensity)
No description has been provided for this image
In [ ]:
 

Explanation: Membrane potential and Action potential changes with frequency

Neurons filter frequency inputs and they respond well to slow signals but struggle with fast signals. The voltage response is smooth and follows the sinusoidal input. The neuron has enough time to depolarize and repolarize in response to the sinusoidal current.

At low Frequencies (50, 100 Hz): Neuron fires distinct spikes, closely following the stimulus. At medium Frequencies (500 Hz): Spikes become less distinct, showing irregular responses. At high Frequencies (1000 Hz): Dampened response, neuron fails to fire properly due to ion channel inactivation. The membrane potential becomes more irregular and has difficulty followin rapid oscilations. Na channels don’t reset fast enough and this limits action potentials.

In [ ]:
 

4. Compare the accuracy of the Euler integration with the RK2 Using RK4 as gold Standard

In [30]:
def dXdt(X, t, I_ext):
    V, m, h, n = X  

    n0, tn = K_prop(V)
    m0, tm, h0, th = Na_prop(V)

    dmdt = -(m - m0) / tm
    dhdt = -(h - h0) / th
    dndt = -(n - n0) / tn

    i_na = I_Na(V, m, h)
    i_k = I_K(V, n)
    i_l = I_L(V)

    dVdt = (I_ext - i_na - i_k - i_l) / C_m

    return np.array([dVdt, dmdt, dhdt, dndt])

class _Integrator():
    def integrate(self, func, y0, t, method='rk4', I_ext=None):
        time_delta_grid = t[1:] - t[:-1]
        y = np.zeros((y0.shape[0], t.shape[0]))
        y[:, 0] = y0

        if I_ext is None:
            I_ext = np.zeros_like(t)  # Default to zero external input if none is provided

        if method == 'euler':
            for i in range(time_delta_grid.shape[0]):
                y[:, i+1] = time_delta_grid[i] * func(y[:, i], t[i], I_ext[i]) + y[:, i]
        elif method == 'rk2':
            for i in range(time_delta_grid.shape[0]):
                k1 = (1/2) * time_delta_grid[i] * func(y[:, i], t[i], I_ext[i])
                y[:, i+1] = y[:, i] + time_delta_grid[i] * func(y[:, i] + k1, t[i] + time_delta_grid[i] / 2, I_ext[i])
        elif method == 'rk4':
            for i in range(time_delta_grid.shape[0]):
                k1 = func(y[:, i], t[i], I_ext[i])
                half_step = t[i] + time_delta_grid[i] / 2
                k2 = func(y[:, i] + time_delta_grid[i] * k1 / 2, half_step, I_ext[i])
                k3 = func(y[:, i] + time_delta_grid[i] * k2 / 2, half_step, I_ext[i])
                k4 = func(y[:, i] + time_delta_grid[i] * k3, t[i] + time_delta_grid[i], I_ext[i])
                y[:, i+1] = (k1 + 2 * k2 + 2 * k3 + k4) * (time_delta_grid[i] / 6) + y[:, i]

        return y

def run_HH_stimulation(frequency, amplitude, method='rk4'):
    t = np.linspace(0, 45, 10000)
    w = 2 * np.pi * frequency
    I_ext = amplitude * np.sin(w * t)

    values_Na = Na_prop(-65)
    m_inf = values_Na[0]
    h_inf = values_Na[2]
    values_k = K_prop(-65)
    n_inf = values_k[0]
    y0 = np.array([-65, m_inf, h_inf, n_inf])

    integrator = _Integrator()
    Y = integrator.integrate(dXdt, y0, t, method=method)
    V = Y[0, :]

    return t, V, I_ext

# Run simulations for Euler, RK2, and RK4
t, V_euler, _ = run_HH_stimulation(100, amplitude=10, method='euler')
t, V_rk2, _ = run_HH_stimulation(100, amplitude=10, method='rk2')
t, V_rk4, _ = run_HH_stimulation(100, amplitude=10, method='rk4') 

# Plot Action Potentials
plt.figure(figsize=(10, 5))
plt.plot(t, V_rk4, label="RK4 (Gold Standard)", linestyle='-', linewidth=2)
plt.plot(t, V_rk2, label="RK2", linestyle='--')
plt.plot(t, V_euler, label="Euler", linestyle='-.')
plt.xlabel("Time (ms)")
plt.ylabel("Membrane Potential (mV)")
plt.title("Action Potential Simulations using Different Methods")
plt.legend()
plt.show()

# Calculate and plot errors
error_euler = np.abs(V_rk4 - V_euler)
error_rk2 = np.abs(V_rk4 - V_rk2)

plt.figure(figsize=(10, 5))
plt.plot(t, error_euler, label="Euler Error")
plt.plot(t, error_rk2, label="RK2 Error")
plt.xlabel("Time (ms)")
plt.ylabel("Absolute Error (mV)")
plt.title("Numerical Error Compared to RK4")
plt.legend()
plt.show()
No description has been provided for this image
No description has been provided for this image

Explanation: Euler with Rk2 methods using Rk4

Euler Method: Simple and fast, but accumulates large numerical errors. Its poor at handling fast voltage changes (spikes). It can deviate away from true values over time.

RK2 Method: More stable than Euler. It reduces error but still deviates slightly from RK4 in fast-changing phases.

RK4 Method (Gold Standard): Most accurate and stable across all phases of the action potential. Its best method for capturing fast voltage changes. Therfore, Euler is useful when high accuracy is not required. RK2 is still better than Euler but still shows deviation. and RK4 is the most reliable method for simulating neuronal changes.

Euler’s error varies across different phases of the action potential due to its inability to accurately capture rapid voltage changes. During the resting phase, when the membrane potential is stable, Euler’s error remains low because there are minimal fluctuations in voltage. However, as the neuron enters the depolarization phase, where voltage rises steeply due to Na influx, Euler’s error increases significantly since it struggles to approximate the sharp slope accurately leading to overshooting. At the peak of the action potential, Euler may slightly overestimate the maximum voltage compared to RK4, which provides a more precise calculation. During repolarization, as K channels open and voltage rapidly decreases, Euler’s method tends to lag behind, accumulating more error similar to the depolarization phase. In the afterhyperpolarization phase, where the voltage momentarily drops below resting potential, Euler may exaggerate this undershoot before gradually stabilizing. As the membrane returns to rest, the error decreases again. Overall, Euler’s method introduces the most error during the depolarization and repolarization phases, where voltage changes are the steepest, while RK4 maintains stability and accuracy throughout all phases.

In [ ]:
 

5. Action Potential with Shifted Inactivation

In [31]:
def simulate_HH_shifted(freq, amplitude, t_start=0, t_end=100, dt=0.01):
    t = np.arange(t_start, t_end, dt)  
    w = 2 * np.pi * freq / 1000  

    def sine_current(t):
        return amplitude * np.sin(w * t)

    def dXdt(X, t):
        V, m, h, n = X  

        I_Na_val = g_Na * (m**3) * h * (V - E_Na)
        I_K_val = g_K * (n**4) * (V - E_K)
        I_L_val = g_L * (V - E_L)
        I_ext = sine_current(t) 

        dVdt = (I_ext - I_Na_val - I_K_val - I_L_val) / C_m

        n0, tn = K_prop(V)
        m0, tm, h0, th = shifted_Na_prop(V)  

        dmdt = -(m - m0) / tm
        dhdt = -(h - h0) / th
        dndt = -(n - n0) / tn

        return np.array([dVdt, dmdt, dhdt, dndt])

    X0 = np.array([-65, shifted_Na_prop(-65)[0], shifted_Na_prop(-65)[2], K_prop(-65)[0]])

    num_steps = len(t)
    X = np.zeros((num_steps, len(X0)))
    X[0] = X0

    # Euler Integration
    for i in range(1, num_steps):
        dt_step = t[i] - t[i - 1]
        X[i] = X[i - 1] + dt_step * dXdt(X[i - 1], t[i])

    return t, X[:, 0], sine_current(t) 

V_values = np.linspace(-100, 50, 500)

h_inf = np.array([Na_prop(V)[2] for V in V_values])
h_inf_shifted = np.array([shifted_Na_prop(V)[2] for V in V_values])


# Plot the old and new inactivation curves
plt.figure(figsize=(8, 5))
plt.plot(V_values, h_inf, label="Original Inactivation")
plt.plot(V_values, h_inf_shifted, label="Shifted Inactivation (+20 mV)")
plt.xlabel("Voltage (mV)")
plt.ylabel("h_inf")
plt.title("Comparison of Original and Shifted Na Inactivation")
plt.legend()
plt.show()


#Original and Shifted Inactivation
def simulate_HH(freq, amplitude, t_start=0, t_end=100, dt=0.01):
    t = np.arange(t_start, t_end, dt) 
    w = 2 * np.pi * freq / 1000  

    def sine_current(t):
        return amplitude * np.sin(w * t)

    def dXdt(X, t):
        V, m, h, n = X  

        I_Na_val = g_Na * (m**3) * h * (V - E_Na)
        I_K_val = g_K * (n**4) * (V - E_K)
        I_L_val = g_L * (V - E_L)
        I_ext = sine_current(t)

        dVdt = (I_ext - I_Na_val - I_K_val - I_L_val) / C_m

        n0, tn = K_prop(V)
        m0, tm, h0, th = Na_prop(V)  

        dmdt = -(m - m0) / tm
        dhdt = -(h - h0) / th
        dndt = -(n - n0) / tn

        return np.array([dVdt, dmdt, dhdt, dndt])

    X0 = np.array([-65, Na_prop(-65)[0], Na_prop(-65)[2], K_prop(-65)[0]])

    num_steps = len(t)
    X = np.zeros((num_steps, len(X0)))
    X[0] = X0

    # Euler method
    for i in range(1, num_steps):
        dt_step = t[i] - t[i - 1]
        X[i] = X[i - 1] + dt_step * dXdt(X[i - 1], t[i])

    return t, X[:, 0], sine_current(t)

# Run simulations
t, V_original, _ = simulate_HH(freq=100, amplitude=10)
t, V_shifted, _ = simulate_HH_shifted(freq=100, amplitude=10)

#action potentials with and withoout shift
plt.figure(figsize=(10, 5))
plt.plot(t, V_original, label="Original Action Potential")
plt.plot(t, V_shifted, label="Shifted Inactivation (+20 mV)")
plt.xlabel("Time (ms)")
plt.ylabel("Membrane Potential (mV)")
plt.title("Comparison of Original and Shifted Action Potentials")
plt.legend()
plt.show()
No description has been provided for this image
No description has been provided for this image

Explanation: Action potential with Shifted Inactivation by +20mV

This function modifies inactivation by shifting it +20 mV toward more positive values. This means the Na⁺ channels take longer to inactivate. This means that h-inactivation requires a stronger depolarization to occur. Na channels stay open longer, prolonging the depolarization phase of the action potential. The action potential graph shows similar plots. To check whether this shift of +20 affects the action potential or not , we have plotted a voltage difference graph between V_original and V_shifted. It barely spikes and remains depolarized after an initial slight increase. Since inactivation is shifted toward more positive values, Na channels stay open too long. This results in persistent depolarization, preventing further action potentials from occurring. The neuron becomes unable to reset and fire again, leading to a flat membrane potential.

In [ ]: