Sesi 05 dari 16

Self-Tuning Regulators &
Identifikasi Sistem Online

Kontroller yang "mengenal" sistemnya lebih baik dari waktu ke waktu — estimasi, desain, kontrol, ulangi. Seperti dokter yang terus memperbarui diagnosa pasiennya.

Konsep STR Recursive Least Squares Arsitektur STR Minimum Variance Studi Kasus Air Python Lengkap
🔧
Topik 5.1
Konsep Self-Tuning: Estimasi Real-Time
🩺 Analogi — ICU dengan Monitoring Kontinyu

Di ICU rumah sakit, pasien dipantau 24 jam. Setiap jam dokter melihat data terbaru (tekanan darah, saturasi O₂, kadar obat dalam darah) → mengestimasi kondisi terkini pasienmenyesuaikan dosis obat. STR bekerja persis sama: estimasi parameter sistem dari data terbaru → desain controller optimal → kontrol → dan siklus berulang terus-menerus.

STR adalah pendekatan indirect adaptive control: ada dua tahap yang berjalan paralel secara online:

📡 Estimator

RLS memperbarui parameter model θ̂ dari data input/output terbaru

🧮 Controller Design

Hitung parameter kontroller optimal berdasarkan θ̂ terbaru

🏭 Plant

Jalankan kontrol, kumpulkan data baru u(k), y(k)

↑_____________________ Data Feedback ______________________↑

💡 STR vs MRAC: Kapan Pilih Yang Mana?

  • STR: Proses lambat (kimia, pengolahan air), perlu interpretasi parameter, sistem MIMO. Waktu respon menit-jam.
  • MRAC: Proses cepat (motor, servo), ada model referensi yang jelas, sistem SISO. Waktu respon milidetik-detik.
📈
Topik 5.2
Recursive Least Squares (RLS)
📸 Analogi — Foto yang Makin Jelas

Bayangkan mengambil foto dengan kamera murah di ruang gelap. Foto pertama buram. Foto kedua sedikit lebih jelas. Semakin banyak foto yang digabung (rata-rata), gambar semakin jelas. RLS seperti itu — setiap data baru membuat estimasi parameter makin akurat. Dan dengan forgetting factor, foto lama "dilupakan" sehingga kamera bisa mengikuti pergerakan objek!

RLS adalah versi rekursif dari Ordinary Least Squares — tidak perlu menyimpan semua data historis, cukup update estimasi saat ada data baru.

📐 Algoritma RLS dengan Forgetting Factor λ
Model : y(k) = φᵀ(k) · θ + ε(k)
            φ = vektor regresi, θ = parameter, ε = noise

Inovasi : e(k) = y(k) − φᵀ(k)·θ̂(k−1)
Kalman gain: K(k) = P(k−1)·φ(k) / [λ + φᵀ(k)·P(k−1)·φ(k)]
Update θ̂ : θ̂(k) = θ̂(k−1) + K(k)·e(k)
Update P : P(k) = [P(k−1) − K(k)·φᵀ(k)·P(k−1)] / λ
Parameter RLSNilai TipikalEfek
λ (forgetting factor)0.95 – 0.99λ kecil = melupakan data lama lebih cepat (tracking perubahan), tapi lebih sensitif noise
P(0) (kovarians awal)P₀·I, P₀=10–1000Besar = estimasi awal sangat tidak yakin (cepat bergerak)
θ̂(0) (estimasi awal)Nol atau dugaan engineeringSebaiknya mendekati nilai sebenarnya untuk konvergensi cepat

✅ Keunggulan RLS

  • Tidak perlu menyimpan semua data (komputasi O(n²) bukan O(n³))
  • Bisa berjalan real-time di embedded system / PLC
  • Forgetting factor memungkinkan tracking parameter yang berubah
  • Optimal secara statistik untuk noise Gaussian
🏗️
Topik 5.3
Arsitektur STR: Estimator + Controller Design

STR klasik bekerja dengan model ARMAX:

📐 Model ARMAX (ARX Sederhana)
A(q⁻¹)·y(k) = B(q⁻¹)·u(k) + e(k)

Contoh orde-2:
y(k) + a₁·y(k−1) + a₂·y(k−2) = b₁·u(k−1) + b₂·u(k−2) + e(k)

Vektor regresi:
φ(k) = [−y(k−1), −y(k−2), u(k−1), u(k−2)]ᵀ
θ = [a₁, a₂, b₁, b₂]ᵀ

Setelah parameter θ̂ diestimasi RLS, controller didesain berdasarkan pole placement atau minimum variance:

📐 Pole Placement Controller Design
Inginkan poles closed-loop di: z = z₁, z₂, ...
Cari R(q⁻¹) dan S(q⁻¹) sedemikian sehingga:
A(q⁻¹)·R(q⁻¹) + B(q⁻¹)·S(q⁻¹) = P(q⁻¹)

Signal kontrol:
R(q⁻¹)·u(k) = T(q⁻¹)·r(k) − S(q⁻¹)·y(k)
📉
Topik 5.4
Minimum Variance Control
🎯 Analogi — Mesin ATM yang Akurat

ATM bank harus mengeluarkan uang tepat sesuai nominal. Jika ada variasi (Rp 100.100 bukan Rp 100.000), itu "variance". Minimum Variance Control bertujuan meminimalkan varians output — membuat output sedekat mungkin dengan setpoint dengan fluktuasi seminimal mungkin. Ideal untuk proses yang membutuhkan presisi tinggi seperti dosis bahan kimia pengolahan air.

📐 Minimum Variance Control (MVC)
Minimasi: J = E[y²(k+d)]  (d = dead time)

Solusi optimal:
u(k) = −[G(q⁻¹)/B(q⁻¹)] · y(k)

Generalized MVC (dengan kontrol effort):
J = E[(y(k+d) − r(k+d))² + ρ·u²(k)]
ρ = bobot kontrol (trade-off akurasi vs energi)
💧
Topik 5.5
Studi Kasus: STR pada Pengolahan Air Bersih
🏭 Skenario: PDAM Kota Besar — Kontrol Dosis Klorin

PDAM harus menambahkan klorin untuk disinfeksi air. Dosis ideal tergantung pada kekeruhan air baku yang berubah-ubah (musim hujan vs kemarau) dan debit air yang fluktuatif. Parameter "gain" sistem (hubungan dosis klorin → konsentrasi residual) berubah terus. STR akan secara otomatis menyesuaikan pompa dosing klorin.

ParameterMusim KemarauMusim Hujan
Kekeruhan air baku5 NTU150–500 NTU
Gain sistem (klorin)0.80.3 – 0.5 (klorin banyak terserap kotoran)
Dead time2 menit3–4 menit (mixing lebih lama)
Respons kontrol idealStabil, dosis rendahAgresif, dosis tinggi
🐍
Topik 5.6
Python: STR Lengkap untuk Pengolahan Air
Python 🐍 — str_water_treatment.py
import numpy as np
import matplotlib.pyplot as plt

# ==========================================
# SELF-TUNING REGULATOR: KONTROL KLORIN PDAM
# Model: y(k) = a1*y(k-1) + b1*u(k-1) + e(k)
# ==========================================

np.random.seed(7)
N   = 400           # langkah simulasi (1 langkah = 1 menit)
k_arr = np.arange(N)

# === PARAMETER SISTEM NYATA (berubah seiring musim) ===
a1_true = np.where(k_arr < 200, 0.7, 0.8)  # koef autoregresi
b1_true = np.where(k_arr < 200, 0.8, 0.4)  # musim hujan: gain turun (klorin terserap)

setpoint = 0.5  # target konsentrasi klorin residual (mg/L)

# === VARIABEL SIMULASI ===
y = np.zeros(N)     # output (konsentrasi klorin)
u = np.zeros(N)     # input (dosis pompa klorin)
y[0] = 0.1

# === RLS ESTIMATOR ===
theta_hat = np.array([0.5, 0.5])  # estimasi awal [a1, b1]
P   = np.eye(2) * 100             # kovarians awal
lam = 0.97                         # forgetting factor

# History estimasi
theta_hist = np.zeros((N, 2))
theta_hist[0] = theta_hat

# Controller: proportional tuning berdasarkan estimasi
def design_controller(theta_hat, setpoint, y_prev):
    a1_est, b1_est = theta_hat
    # Inverse model (minimum variance sederhana)
    if abs(b1_est) < 0.01: b1_est = 0.01  # hindari div/0
    u_desired = (setpoint - a1_est * y_prev) / b1_est
    return np.clip(u_desired, 0, 5.0)  # batas fisik pompa

# === SIMULASI UTAMA ===
for k in range(1, N):
    # 1. CONTROLLER: Hitung u berdasarkan estimasi terbaru
    u[k] = design_controller(theta_hat, setpoint, y[k-1])
    
    # 2. PLANT: Jalankan sistem nyata
    noise = 0.02 * np.random.randn()
    y[k]  = a1_true[k]*y[k-1] + b1_true[k]*u[k-1] + noise
    y[k]  = np.clip(y[k], 0, 3.0)
    
    # 3. RLS ESTIMATOR: Update parameter dari data baru
    if k >= 2:
        phi   = np.array([y[k-1], u[k-1]])   # vektor regresi
        y_pred = phi @ theta_hat               # prediksi
        innov  = y[k] - y_pred                 # inovasi / error prediksi
        
        K_gain    = P @ phi / (lam + phi @ P @ phi)
        theta_hat = theta_hat + K_gain * innov
        P         = (P - np.outer(K_gain, phi) @ P) / lam
        
        # Batasi estimasi agar realistis
        theta_hat[0] = np.clip(theta_hat[0], 0.0, 1.0)
        theta_hat[1] = np.clip(theta_hat[1], 0.05, 2.0)
    
    theta_hist[k] = theta_hat

# === PLOT ===
fig, axes = plt.subplots(3, 1, figsize=(12, 9))

# Plot 1: Output
axes[0].plot(k_arr, y, 'cyan', lw=1.5, label='Konsentrasi Klorin Aktual')
axes[0].axhline(setpoint, color='orange', ls='--', lw=2, label=f'Setpoint {setpoint} mg/L')
axes[0].fill_between(k_arr, setpoint-0.05, setpoint+0.05, alpha=0.15, color='orange')
axes[0].axvline(200, color='red', ls=':', lw=2, label='Musim hujan dimulai')
axes[0].set_ylabel('Klorin (mg/L)')
axes[0].set_title('STR: Kontrol Klorin PDAM — Adaptif terhadap Musim')
axes[0].legend(fontsize=9); axes[0].grid(alpha=0.3)

# Plot 2: Parameter estimasi vs true
axes[1].plot(k_arr, theta_hist[:,0], 'lime', lw=1.5, label='â₁ (estimasi)')
axes[1].plot(k_arr, a1_true, 'lime', ls='--', alpha=0.4, label='a₁ (true)')
axes[1].plot(k_arr, theta_hist[:,1], 'magenta', lw=1.5, label='b̂₁ (estimasi)')
axes[1].plot(k_arr, b1_true, 'magenta', ls='--', alpha=0.4, label='b₁ (true)')
axes[1].axvline(200, color='red', ls=':', lw=2)
axes[1].set_ylabel('Nilai Parameter')
axes[1].set_title('RLS: Estimasi Parameter Mengikuti Perubahan Sistem')
axes[1].legend(fontsize=9); axes[1].grid(alpha=0.3)

# Plot 3: Sinyal kontrol
axes[2].plot(k_arr, u, 'orange', lw=1.2, label='Dosis Pompa Klorin')
axes[2].axvline(200, color='red', ls=':', lw=2, label='Musim hujan')
axes[2].set_xlabel('Waktu (menit)'); axes[2].set_ylabel('Dosis (unit)')
axes[2].set_title('STR Otomatis Naikkan Dosis Klorin saat Musim Hujan!')
axes[2].legend(); axes[2].grid(alpha=0.3)

plt.tight_layout(); plt.show()

print(f"\n📊 Ringkasan Hasil:")
print(f"Error rata2 kemarau : {np.mean(np.abs(y[:190]-setpoint)):.4f} mg/L")
print(f"Error rata2 hujan   : {np.mean(np.abs(y[220:]-setpoint)):.4f} mg/L")
print(f"Dosis rerata kemarau: {np.mean(u[:190]):.3f}")
print(f"Dosis rerata hujan  : {np.mean(u[220:]):.3f} (otomatis lebih besar!)")

🔑 Kesimpulan Kunci

  • Saat musim hujan tiba (k=200), gain sistem turun dari 0.8 → 0.4
  • RLS mendeteksi perubahan dalam ~20–30 langkah dan memperbarui b̂₁
  • Controller otomatis menaikkan dosis pompa klorin tanpa intervensi manusia
  • Tanpa STR: operator harus manualrekalibrasi setiap ganti musim — berisiko over/under-dosing!
  • Dengan STR: sistem aman, efisien, sesuai standar WHO untuk kualitas air

🧠 Kuis Pemahaman Sesi 5

1. Apa yang dimaksud "forgetting factor" λ dalam RLS?

2. STR termasuk kategori kontrol adaptif apa?

3. Mengapa Minimum Variance Control cocok untuk proses pengolahan air bersih?