import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.optimize import fsolve
import warnings
warnings.filterwarnings('ignore')
class Repressilator:
"""Repressilator synthetic clock with three genes in cyclic repression"""
def __init__(self, alpha=250, n=2.0):
self.alpha = alpha
self.n = n
def repressilator_odes(self, state, t):
"""Core repressilator ODEs"""
x, y, z = state
repressor_x = self.alpha / (1 + y**self.n)
repressor_y = self.alpha / (1 + z**self.n)
repressor_z = self.alpha / (1 + x**self.n)
dxdt = repressor_x - x
dydt = repressor_y - y
dzdt = repressor_z - z
return [dxdt, dydt, dzdt]
def find_fixed_point(self, initial_guess=None):
"""Find the symmetric fixed point"""
if initial_guess is None:
initial_guess = self.alpha / 2
def equations(x):
# At symmetric fixed point: x* = α/(1 + x*^n)
return x - self.alpha / (1 + x**self.n)
try:
solution = fsolve(equations, initial_guess)
return solution[0]
except:
return None
def jacobian_at_fixed_point(self, x_star):
"""
Compute Jacobian matrix at symmetric fixed point.
The cyclic structure gives eigenvalues: λ₁ = -1-β,
λ₂,₃ = -1 + β/2 ± i·β√3/2
where β is the magnitude of repression slope
"""
# Derivative of repression function at x*
# g'(x*) = -n·α·x*^(n-1)/(1 + x*^n)²
# Since x* = α/(1 + x*^n), we have: 1 + x*^n = α/x*
# Alternative form: β = |g'(x*)| = n(α - x*)/α
beta = self.n * (self.alpha - x_star) / self.alpha
# Eigenvalues
lambda_1 = -1 - beta
lambda_23_real = -1 + beta/2
lambda_23_imag = beta * np.sqrt(3) / 2
return {
'beta': beta,
'lambda_1': lambda_1,
'lambda_23': (lambda_23_real, lambda_23_imag),
'max_real_eigenvalue': lambda_23_real
}
def is_oscillatory(self, x_star):
"""Check if system exhibits oscillations (Hopf bifurcation criterion)"""
eigs = self.jacobian_at_fixed_point(x_star)
# Oscillations occur when max(Re(λ)) > 0
return eigs['max_real_eigenvalue'] > 0
# ==============================================================================
# ANALYSIS 1: Bifurcation as function of Hill coefficient
# ==============================================================================
print("="*70)
print("REPRESSILATOR ANALYSIS: Hill Coefficient Dependency")
print("="*70)
alpha = 250 # Fixed synthesis rate
n_values = np.linspace(1.5, 4.0, 30)
oscillation_status = []
fixed_points = []
eigenvalue_real = []
for n in n_values:
rep = Repressilator(alpha=alpha, n=n)
x_star = rep.find_fixed_point()
if x_star is not None and x_star > 0:
fixed_points.append(x_star)
eigs = rep.jacobian_at_fixed_point(x_star)
eigenvalue_real.append(eigs['max_real_eigenvalue'])
oscillation_status.append(rep.is_oscillatory(x_star))
else:
fixed_points.append(np.nan)
eigenvalue_real.append(np.nan)
oscillation_status.append(False)
# Find approximate bifurcation point
n_critical_idx = np.where(np.array(eigenvalue_real) > 0)[0]
if len(n_critical_idx) > 0:
n_critical = n_values[n_critical_idx[0]]
print(f"\nCritical Hill coefficient (bifurcation): n ≈ {n_critical:.3f}")
else:
n_critical = 2.0
print(f"Theoretical prediction: n = 2.0")
# ==============================================================================
# ANALYSIS 2: Oscillations for different Hill coefficients
# ==============================================================================
print("\n" + "="*70)
print("OSCILLATION REGIMES")
print("="*70)
n_test = [1.5, 2.0, 2.5, 3.0, 4.0]
t_span = np.linspace(0, 500, 5000)
fig, axes = plt.subplots(3, 2, figsize=(14, 11))
axes = axes.flatten()
for idx, n in enumerate(n_test):
rep = Repressilator(alpha=alpha, n=n)
# Find fixed point
x_star = rep.find_fixed_point()
# Start from perturbed initial condition
initial_state = np.array([x_star * 1.5, x_star * 0.7, x_star * 1.2])
# Solve ODEs
solution = odeint(rep.repressilator_odes, initial_state, t_span)
x, y, z = solution.T
# Compute eigenvalues
eigs = rep.jacobian_at_fixed_point(x_star)
max_eig = eigs['max_real_eigenvalue']
# Plot time series
ax = axes[idx]
ax.plot(t_span, x, 'r-', label='TetR', linewidth=1.5)
ax.plot(t_span, y, 'g-', label='cI', linewidth=1.5)
ax.plot(t_span, z, 'b-', label='LacI', linewidth=1.5)
ax.set_xlim([0, 500])
ax.set_xlabel('Time')
ax.set_ylabel('Protein concentration')
status = "OSCILLATORY" if eigs['max_real_eigenvalue'] > 0 else "STABLE - No oscillations"
ax.set_title(f"n = {n:.1f} | λ_max = {max_eig:.3f}\n{status}")
ax.legend(loc='upper right', fontsize=8)
ax.grid(True, alpha=0.3)
ax.set_ylim([0, 350])
# Phase plane for last case
ax = axes[5]
rep = Repressilator(alpha=alpha, n=4.0)
x_star = rep.find_fixed_point()
initial_state = np.array([x_star * 1.5, x_star * 0.7, x_star * 1.2])
solution = odeint(rep.repressilator_odes, initial_state, t_span)
x, y, z = solution.T
ax.plot(x, y, 'purple', linewidth=1.5, alpha=0.7)
ax.plot(x[0], y[0], 'go', markersize=8, label='Start')
ax.plot(x_star, x_star, 'r*', markersize=15, label='Fixed point')
ax.set_xlabel('TetR (x)')
ax.set_ylabel('cI (y)')
ax.set_title('Phase plane projection (n=4.0)')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('repressilator_oscillations.png', dpi=300, bbox_inches='tight')
plt.show()
print("\nOscillation characteristics for different Hill coefficients:")
for n in n_test:
rep = Repressilator(alpha=alpha, n=n)
x_star = rep.find_fixed_point()
eigs = rep.jacobian_at_fixed_point(x_star)
print(f"\nn = {n:.1f}:")
print(f" Fixed point: x* = {x_star:.2f}")
print(f" β (repression strength): {eigs['beta']:.3f}")
print(f" λ_max (real part): {eigs['max_real_eigenvalue']:.4f}")
print(f" Complex eigenvalues: {eigs['lambda_23'][0]:.4f} ± {eigs['lambda_23'][1]:.4f}i")
print(f" Status: {'OSCILLATIONS' if eigs['max_real_eigenvalue'] > 0 else 'STABLE'}")
# ==============================================================================
# ANALYSIS 3: Bifurcation diagram - Hill coefficient effect
# ==============================================================================
fig, axes = plt.subplots(2, 2, figsize=(13, 10))
# Subplot 1: Eigenvalue vs Hill coefficient
ax = axes[0, 0]
ax.plot(n_values, eigenvalue_real, 'b-', linewidth=2.5, label='Max Re(λ)')
ax.axhline(y=0, color='r', linestyle='--', linewidth=2, label='Stability boundary')
ax.axvline(x=2, color='g', linestyle='--', linewidth=2, label='Theoretical: n=2')
ax.fill_between(n_values, 0, eigenvalue_real, where=(np.array(eigenvalue_real)>0),
alpha=0.3, color='red', label='Oscillatory region')
ax.set_xlabel('Hill coefficient (n)', fontsize=11)
ax.set_ylabel('Maximum eigenvalue', fontsize=11)
ax.set_title('Hopf Bifurcation Diagram', fontsize=12, fontweight='bold')
ax.legend(fontsize=10)
ax.grid(True, alpha=0.3)
ax.set_xlim([1.5, 4.0])
# Subplot 2: β parameter vs Hill coefficient
ax = axes[0, 1]
beta_values = [rep.jacobian_at_fixed_point(fp)['beta'] for rep, fp in
zip([Repressilator(alpha=alpha, n=n) for n in n_values], fixed_points)]
ax.plot(n_values, beta_values, 'g-', linewidth=2.5)
ax.axhline(y=2, color='r', linestyle='--', linewidth=2, label='Critical β = 2')
ax.fill_between(n_values, 0, 2, alpha=0.2, color='yellow', label='Stable (β < 2)')
ax.fill_between(n_values, 2, max(beta_values)+0.5, alpha=0.2, color='red', label='Oscillatory (β > 2)')
ax.set_xlabel('Hill coefficient (n)', fontsize=11)
ax.set_ylabel('Repression strength (β)', fontsize=11)
ax.set_title('Parameter β: Loop Gain', fontsize=12, fontweight='bold')
ax.legend(fontsize=10)
ax.grid(True, alpha=0.3)
ax.set_xlim([1.5, 4.0])
ax.set_ylim([0, max(beta_values)+0.5])
# Subplot 3: Fixed point vs Hill coefficient
ax = axes[1, 0]
ax.plot(n_values, fixed_points, 'orange', linewidth=2.5, marker='o', markersize=4)
ax.set_xlabel('Hill coefficient (n)', fontsize=11)
ax.set_ylabel('Fixed point value (x*)', fontsize=11)
ax.set_title('Symmetric fixed point location', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.set_xlim([1.5, 4.0])
# Subplot 4: Oscillation frequency vs Hill coefficient
# Frequency from imaginary part: ω = β√3/2
ax = axes[1, 1]
frequencies = [b * np.sqrt(3) / 2 for b in beta_values]
ax.plot(n_values, frequencies, 'purple', linewidth=2.5, marker='s', markersize=4)
ax.set_xlabel('Hill coefficient (n)', fontsize=11)
ax.set_ylabel('Oscillation frequency', fontsize=11)
ax.set_title('Period decreases with increasing n', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
ax.set_xlim([1.5, 4.0])
plt.tight_layout()
plt.savefig('repressilator_bifurcation.png', dpi=300, bbox_inches='tight')
plt.show()
# ==============================================================================
# ANALYSIS 4: Limit cycle analysis
# ==============================================================================
print("\n" + "="*70)
print("LIMIT CYCLE CHARACTERISTICS")
print("="*70)
fig, axes = plt.subplots(2, 2, figsize=(13, 10))
# Calculate limit cycle properties for different n values
n_osc = [2.2, 2.5, 3.0, 4.0]
periods = []
amplitudes = []
frequencies_list = []
for n in n_osc:
rep = Repressilator(alpha=alpha, n=n)
x_star = rep.find_fixed_point()
# Initial condition
initial_state = np.array([x_star * 1.3, x_star * 0.6, x_star * 1.1])
# Long integration to establish limit cycle
t_long = np.linspace(0, 1000, 20000)
solution = odeint(rep.repressilator_odes, initial_state, t_long)
x = solution[:, 0]
# Skip transient
skip = 10000
x_cycle = x[skip:]
# Find peaks to estimate period
from scipy.signal import find_peaks
peaks, _ = find_peaks(x_cycle, height=np.mean(x_cycle))
if len(peaks) >= 2:
period = 2 * np.mean(np.diff(peaks)) * (t_long[-1] - t_long[0]) / len(t_long)
frequency = 1 / period if period != 0 else 0
periods.append(period)
frequencies_list.append(frequency)
amplitudes.append((np.max(x_cycle) - np.min(x_cycle)) / 2)
# Plot 1: Phase space 3D projection
ax = axes[0, 0]
from mpl_toolkits.mplot3d import Axes3D
ax.remove()
ax = fig.add_subplot(2, 2, 1, projection='3d')
n = 3.0
rep = Repressilator(alpha=alpha, n=n)
x_star = rep.find_fixed_point()
initial_state = np.array([x_star * 1.3, x_star * 0.6, x_star * 1.1])
t = np.linspace(0, 300, 10000)
solution = odeint(rep.repressilator_odes, initial_state, t)
x, y, z = solution.T
ax.plot(x, y, z, 'b-', linewidth=0.5, alpha=0.7)
ax.scatter(*initial_state, color='green', s=100, label='Initial', marker='o')
ax.scatter(x_star, x_star, x_star, color='red', s=200, label='Fixed point', marker='*')
ax.set_xlabel('TetR (x)')
ax.set_ylabel('cI (y)')
ax.set_zlabel('LacI (z)')
ax.set_title(f'3D Limit Cycle (n={n})')
ax.legend()
# Plot 2: Oscillation period vs Hill coefficient
ax = axes[0, 1]
ax.plot(n_osc, periods, 'ro-', linewidth=2, markersize=8)
ax.set_xlabel('Hill coefficient (n)', fontsize=11)
ax.set_ylabel('Period', fontsize=11)
ax.set_title('Oscillation Period vs Hill Coefficient', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
# Plot 3: Amplitude vs Hill coefficient
ax = axes[1, 0]
ax.plot(n_osc, amplitudes, 'go-', linewidth=2, markersize=8)
ax.set_xlabel('Hill coefficient (n)', fontsize=11)
ax.set_ylabel('Amplitude', fontsize=11)
ax.set_title('Oscillation Amplitude vs Hill Coefficient', fontsize=12, fontweight='bold')
ax.grid(True, alpha=0.3)
# Plot 4: Return map
ax = axes[1, 1]
n = 3.0
rep = Repressilator(alpha=alpha, n=n)
x_star = rep.find_fixed_point()
initial_state = np.array([x_star * 1.3, x_star * 0.6, x_star * 1.1])
t_long = np.linspace(0, 1000, 20000)
solution = odeint(rep.repressilator_odes, initial_state, t_long)
x_full = solution[:, 0]
# Skip transient and take local maxima
skip = 10000
x_cycle = x_full[skip:]
peaks, props = find_peaks(x_cycle, height=np.mean(x_cycle))
if len(peaks) > 1:
x_max = x_cycle[peaks]
x_next = x_max[1:]
x_curr = x_max[:-1]
ax.plot(x_curr, x_next, 'ko', markersize=6)
ax.plot([x_curr.min(), x_curr.max()], [x_curr.min(), x_curr.max()],
'r--', linewidth=1, label='Identity')
ax.set_xlabel('$x_n$ (maximum at cycle n)', fontsize=11)
ax.set_ylabel('$x_{n+1}$ (maximum at cycle n+1)', fontsize=11)
ax.set_title('Return Map - Limit Cycle', fontsize=12, fontweight='bold')
ax.legend()
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('repressilator_limit_cycle.png', dpi=300, bbox_inches='tight')
plt.show()
# ==============================================================================
# THEORETICAL SUMMARY
# ==============================================================================
print("\n" + "="*70)
print("THEORETICAL REQUIREMENTS FOR OSCILLATIONS")
print("="*70)
summary = """
The repressilator exhibits limit cycle oscillations if and only if:
1. HILL COEFFICIENT REQUIREMENT: n > 2
Justification:
- The symmetric fixed point is always: x* = α/(1 + x*^n)
- Stability eigenvalues: λ₁ = -1-β, λ₂,₃ = -1 + β/2 ± i·β√3/2
- Where β = n(α - x*)/α is the loop gain
- Complex eigenvalues become unstable when: β > 2
- This requires: n(α - x*)/α > 2
- For typical parameters, this demands n > 2
2. PARAMETER RANGE for α:
- For given n > 2, oscillations require α ≥ α_min(n)
- Larger α enables oscillations at smaller n values
- Typical range: α ∈ [100, 500] (in protein copy numbers)
3. BIFURCATION CHARACTERISTICS:
- At n = 2: Supercritical Hopf bifurcation occurs
- For n > 2: Limit cycle amplitude and frequency increase
- Oscillation frequency: ω ∝ β√3/2, increases with n
4. PHYSICAL INTERPRETATION:
- Cooperativity (n > 2) ensures strong repression
- Strong repression creates delay in feedback loop
- Delay enables overshooting → oscillations
- Weak cooperativity (n ≤ 2): System reaches equilibrium instantly
- Strong cooperativity (n > 2): Time delay enables sustained oscillations
5. ROBUSTNESS:
- Oscillations persist for n > 2 across wide parameter ranges
- Period scales roughly as 1/(loop gain)
- Biological relevance: Real systems use n ≥ 2.5 for robust clocks
"""
print(summary)
# Verify theoretical predictions
print("\nNUMERICAL VERIFICATION:")
print(f"Bifurcation from numerical analysis: n ≈ {n_critical:.3f}")
print(f"Theoretical prediction: n = 2.0")
print(f"Difference: {abs(n_critical - 2.0):.3f}")