%% =========================================================================
%% SIMULASI KOMPREHENSIF MOTOR INDUKSI 3-FASA (MINGGU 11 & MINGGU 12)
%% Mata Kuliah   : Teknik Tenaga Listrik (Program Studi S-1 Teknik Mesin)
%% Dosen Pengampu: Novalio Daratha, S.T., M.Sc., Ph.D.
%% Institusi     : Fakultas Teknik, Universitas Bengkulu
%% =========================================================================

clear; clc; close all;
graphics_toolkit('qt');
set(0, 'defaultaxesfontname', 'Helvetica');
set(0, 'defaultaxesfontsize', 9.5);

fprintf('=== Memulai Simulasi Motor Induksi 3-Fasa (Minggu 11 & 12) ===\n');

%% =========================================================================
%% PARAMETER RANGKAIAN EKUIVALEN IEEE PER-FASA (400 V, 50 Hz, 4-Kutub, 15 kW)
%% =========================================================================
V_LL = 400;                  % Tegangan antar-saluran (Line-to-Line) [V]
V_ph = V_LL / sqrt(3);       % Tegangan per fasa (Y-connected) [V] = 230.94 V
f_nom = 50;                  % Frekuensi nominal [Hz]
p = 4;                       % Jumlah kutub
n_sync = 120 * f_nom / p;    % Kecepatan sinkron [rpm] = 1500 rpm
w_sync = 2 * pi * n_sync / 60; % Kecepatan sudut sinkron [rad/s] = 157.08 rad/s

% Parameter Impedansi per Fasa (Ohm) pada 50 Hz (Motor 15 kW, 400 V)
R1 = 0.32;                   % Resistansi belitan stator
X1 = 0.78;                   % Reaktansi bocor stator
R2_nom = 0.28;               % Resistansi rotor rujukan stator (NEMA Kelas B)
X2 = 0.78;                   % Reaktansi bocor rotor rujukan stator
Xm = 28.0;                   % Reaktansi magnetisasi celah udara

% Parameter Ekivalen Thevenin Stator
Z1 = R1 + 1i * X1;
Zm = 1i * Xm;
V_th = abs(V_ph * (Zm / (Z1 + Zm)));
Z_th = (Z1 * Zm) / (Z1 + Zm);
R_th = real(Z_th);
X_th = imag(Z_th);

% Rentang Kecepatan & Slip (dari n = 0 [s=1] hingga n = 1499 rpm [s->0])
s_vec = linspace(1.0, 0.0005, 500);
n_vec = (1 - s_vec) .* n_sync;

%% =========================================================================
%% FIGUR 1: KARAKTERISTIK TORSI-SLIP & EFEK RESISTANSI ROTOR (MINGGU 11)
%% =========================================================================
R2_eff = R2_nom .* (1 + 0.55 .* (s_vec.^1.4));
T_base = (3 / w_sync) .* (V_th^2 .* (R2_eff ./ s_vec)) ./ ((R_th + R2_eff ./ s_vec).^2 + (X_th + X2)^2);
T_pullup_dip = -24 .* exp(-((s_vec - 0.72) ./ 0.16).^2);
T_nemaB = T_base + T_pullup_dip;

% Hitung Titik-Titik Penting
[T_max, idx_max] = max(T_nemaB);
s_max = s_vec(idx_max);
n_max = n_vec(idx_max);
T_start = T_nemaB(1);

% Titik Kerja Beban Penuh (Full-Load Operating Point, T_FL = 95 Nm)
T_FL = 95;
idx_FL = find(n_vec > n_max & T_nemaB >= T_FL, 1, 'last');
n_FL = n_vec(idx_FL);
s_FL = s_vec(idx_FL);

% Variasi Resistansi Rotor R2' Murni (Rotor Belitan / Kelas NEMA A/B, C, D)
R2_list = [0.28, 0.55, 1.05, 1.80]; % Ohm
T_R2_mat = zeros(length(R2_list), length(s_vec));
s_max_list = zeros(1, length(R2_list));
n_max_list = zeros(1, length(R2_list));
T_max_pure = (3 / (2 * w_sync)) * (V_th^2 / (R_th + sqrt(R_th^2 + (X_th + X2)^2)));

for idx = 1:length(R2_list)
    R2_curr = R2_list(idx);
    T_R2_mat(idx, :) = (3 / w_sync) .* (V_th^2 .* (R2_curr ./ s_vec)) ./ ...
                       ((R_th + R2_curr ./ s_vec).^2 + (X_th + X2)^2);
    s_max_list(idx) = R2_curr / sqrt(R_th^2 + (X_th + X2)^2);
    n_max_list(idx) = (1 - s_max_list(idx)) * n_sync;
end

hFig1 = figure('visible', 'off', 'position', [40, 40, 1220, 490]);

% --- Subplot 1(a): Kurva Karakteristik Lengkap Torsi-Kecepatan/Slip ---
subplot(1, 2, 1);
fill([n_max n_sync n_sync n_max], [0 0 320 320], [0.85 0.97 0.88], 'facealpha', 0.35, 'linestyle', 'none'); hold on;
h_curve = plot(n_vec, T_nemaB, 'b-', 'linewidth', 2.3);
h_load = plot([0 n_sync], [T_FL T_FL], 'k--', 'linewidth', 1.4);

% Garis bantu vertikal pada T_max dan Full-Load
plot([n_max n_max], [0 T_max], 'k:', 'linewidth', 1.1);
plot([n_FL n_FL], [0 T_FL], 'g:', 'linewidth', 1.3);

% Penanda Titik Kritis
h_p1 = plot(0, T_start, 'ro', 'markersize', 7, 'markerfacecolor', 'r');
h_p2 = plot(n_max, T_max, 'ks', 'markersize', 7.5, 'markerfacecolor', [0.95 0.75 0.1]);
h_p3 = plot(n_FL, T_FL, 'go', 'markersize', 7.5, 'markerfacecolor', [0.1 0.75 0.2]);
plot(n_sync, 0, 'bo', 'markersize', 6.5, 'markerfacecolor', 'w');

% Label Anotasi (bebas tumpang tindih)
text(35, T_start + 22, sprintf('T_{start} = %.0f Nm\n(s = 1.0)', T_start), 'fontsize', 8, 'fontweight', 'bold', 'color', [0.75 0 0]);
text(280, 118, sprintf('Pull-up Torque\n(Torsi Pelana)'), 'fontsize', 8, 'color', [0.2 0.2 0.55], 'fontweight', 'bold');
text(n_max - 480, T_max + 20, sprintf('Breakdown Torque\nT_{max} = %.0f Nm (s_{max}=%.2f)', T_max, s_max), 'fontsize', 8, 'fontweight', 'bold');
text(980, 148, sprintf('Titik Kerja Nominal\n(%.0f rpm, s=%.1f%%, %d Nm)', n_FL, s_FL*100, T_FL), 'fontsize', 8, 'fontweight', 'bold', 'color', [0.05 0.45 0.15]);
text(1240, 22, sprintf('n_s = %d rpm\n(s = 0)', n_sync), 'fontsize', 8, 'color', 'b', 'fontweight', 'bold');
text(1235, 290, sprintf('ZONA STABIL\n(s < s_{max})'), 'fontsize', 7.8, 'fontweight', 'bold', 'color', [0.08 0.48 0.18]);

hold off; grid on;
title('(a) Kurva Torsi-Kecepatan & Titik Kritis Motor Induksi', 'fontsize', 10, 'fontweight', 'bold');
xlabel('Kecepatan Putar Rotor, n_r (rpm)   [Slip s = 1 \rightarrow 0]', 'fontsize', 9.5);
ylabel('Torsi Elektromagnetik, T_e (Nm)', 'fontsize', 9.5);
legend([h_curve, h_load, h_p1, h_p2, h_p3], ...
       {'Kurva Motor (400V, 50Hz, 4p)', ...
        'Beban Nominal (T_L = 95 Nm)', ...
        'Starting Torque (T_{start}, s = 1)', ...
        'Breakdown Torque (T_{max}, s = s_{max})', ...
        'Titik Kerja Penuh (Full-Load)'}, ...
       'location', 'southwest', 'fontsize', 7.3);
xlim([0 1550]); ylim([0 320]);

% --- Subplot 1(b): Efek Resistansi Rotor R2' & Kelas Desain NEMA ---
subplot(1, 2, 2);
colors_R2 = {[0 0.25 0.75], [0.1 0.65 0.25], [0.85 0.45 0.0], [0.8 0.1 0.1]};
styles_R2 = {'-', '--', '-.', ':'};
h_R2 = zeros(1, length(R2_list));

hold on;
for idx = 1:length(R2_list)
    h_R2(idx) = plot(n_vec, T_R2_mat(idx, :), 'color', colors_R2{idx}, 'linestyle', styles_R2{idx}, 'linewidth', 2.2);
end
h_env = plot([0 n_sync], [T_max_pure T_max_pure], 'k:', 'linewidth', 1.4);
for idx = 1:length(R2_list)
    plot(n_max_list(idx), T_max_pure, 'ko', 'markersize', 6, 'markerfacecolor', colors_R2{idx});
end

text(45, T_max_pure + 34, sprintf('T_{max} = %.0f Nm Tetap Konstan (Independen dari R_2'')!', T_max_pure), ...
     'fontsize', 8, 'fontweight', 'bold', 'color', 'k');
text(45, T_max_pure + 14, sprintf('Kenaikan R_2'' menggeser s_{max} \\rightarrow 1.0 (T_{start} naik drastis)'), ...
     'fontsize', 8, 'color', [0.65 0.05 0.05], 'fontweight', 'bold');

hold off; grid on;
title('(b) Efek Resistansi Rotor (R_2'') & Kelas NEMA A/B, C, D', 'fontsize', 10, 'fontweight', 'bold');
xlabel('Kecepatan Putar Rotor, n_r (rpm)', 'fontsize', 9.5);
ylabel('Torsi Elektromagnetik, T_e (Nm)', 'fontsize', 9.5);
legend([h_R2, h_env], ...
       {'R_2'' = 0.28 \Omega (NEMA Kelas A/B: Pompa, Kipas)', ...
        'R_2'' = 0.55 \Omega (NEMA Kelas C: Konveyor, Kompresor)', ...
        'R_2'' = 1.05 \Omega (Rotor Belitan + R_{ext})', ...
        'R_2'' = 1.80 \Omega (NEMA Kelas D: Punch Press, Hoist)', ...
        'Selubung T_{max} Konstan'}, ...
       'location', 'southwest', 'fontsize', 7.3);
xlim([0 1550]); ylim([0 320]);

print(hFig1, 'torsi_slip_induksi.png', '-dpng', '-r300');
fprintf('1. Grafik torsi_slip_induksi.png (300 DPI) berhasil diperbarui.\n');
close(hFig1);

%% =========================================================================
%% FIGUR 2: METODE STARTING (DOL vs Y-D vs SOFT STARTER) & VFD (MINGGU 12)
%% =========================================================================
Z_tot_vec = (R1 + R2_eff ./ s_vec) + 1i * (X1 + X2);
I_L_DOL = sqrt(3) .* (V_ph ./ abs(Z_tot_vec));
I_nom = 29.0;

I_L_YD = (1/3) .* I_L_DOL;
T_YD = (1/3) .* T_nemaB;
idx_trans = find(n_vec >= 1280, 1, 'first');
I_L_YD(idx_trans:end) = I_L_DOL(idx_trans:end);
T_YD(idx_trans:end) = T_nemaB(idx_trans:end);

V_ramp_ratio = 0.55 + 0.45 .* ((n_vec ./ n_sync).^1.15);
I_L_Soft = V_ramp_ratio .* I_L_DOL;

f_vfd_list = [15, 25, 35, 50, 60]; % Hz
n_axis_vfd = linspace(0, 1850, 500);

hFig2 = figure('visible', 'off', 'position', [40, 40, 1220, 490]);

% --- Subplot 2(a): Perbandingan Arus & Torsi Starting (DOL vs Y-Delta vs Soft Starter) ---
subplot(1, 2, 1);
[ax, h_c1, h_t1] = plotyy(n_vec, I_L_DOL ./ I_nom, n_vec, T_nemaB);
hold(ax(1), 'on'); hold(ax(2), 'on');

set(h_c1, 'color', [0.8 0.1 0.1], 'linestyle', '-', 'linewidth', 2.2);
h_c2 = plot(ax(1), n_vec, I_L_YD ./ I_nom, 'b--', 'linewidth', 2.2);
h_c3 = plot(ax(1), n_vec, I_L_Soft ./ I_nom, 'g-.', 'linewidth', 2.0);

set(h_t1, 'color', [0.8 0.1 0.1], 'linestyle', ':', 'linewidth', 1.6);
h_t2 = plot(ax(2), n_vec, T_YD, 'b:', 'linewidth', 1.8);

set(ax(1), 'ylim', [0 9.0], 'xlim', [0 1550], 'ycolor', [0.75 0.05 0.05], 'xtick', 0:250:1500, 'box', 'off');
set(ax(2), 'ylim', [0 340], 'xlim', [0 1550], 'ycolor', [0.05 0.25 0.75], 'xtick', []);

ylabel(ax(1), 'Rasio Arus Saluran, I_{start} / I_{nom} (x Nominal)', 'fontsize', 9.5);
ylabel(ax(2), 'Torsi Bangkitan, T_e (Nm) [Garis Titik]', 'fontsize', 9.5);
xlabel(ax(1), 'Kecepatan Putar Rotor, n_r (rpm)', 'fontsize', 9.5);
title('(a) Pengasutan: DOL vs Star-Delta (Y-\Delta) vs Soft Starter', 'fontsize', 10, 'fontweight', 'bold');
grid(ax(1), 'on');

text(ax(1), 40, 8.35, sprintf('DOL Start: I_{start} = %.1f x I_{nom}, T_{start} = %.0f Nm', I_L_DOL(1)/I_nom, T_nemaB(1)), ...
     'fontsize', 7.8, 'fontweight', 'bold', 'color', [0.75 0 0]);
text(ax(1), 40, 6.45, sprintf('Star-Delta (Y-\\Delta): I_Y = 1/3 I_{DOL} (%.1f x I_{nom})\nT_Y = 1/3 T_{DOL} (%.0f Nm)', I_L_YD(1)/I_nom, T_YD(1)), ...
     'fontsize', 7.6, 'fontweight', 'bold', 'color', [0 0.2 0.75]);
text(ax(1), 890, 5.15, sprintf('Transisi Y \\rightarrow \\Delta\n(n = 1280 rpm)'), 'fontsize', 7.8, 'color', 'b', 'fontweight', 'bold');

legend(ax(1), [h_c1; h_c2; h_c3; h_t1; h_t2], ...
       {'Arus DOL (Direct-On-Line, 100% V)', ...
        'Arus Star-Delta (Y-\Delta: 1/3 I_{DOL})', ...
        'Arus Soft-Starter (Ramp Sudut \alpha)', ...
        'Torsi DOL (100% T_{start})', ...
        'Torsi Star-Delta (1/3 T_{DOL})'}, ...
       'location', 'southwest', 'fontsize', 7.0);

% --- Subplot 2(b): Kendali Kecepatan VFD Constant V/f & Hukum Afinitas Pompa ---
subplot(1, 2, 2);
hold on;
colors_vfd = {[0.55 0.1 0.7], [0.1 0.6 0.65], [0.1 0.65 0.2], [0 0.25 0.8], [0.85 0.2 0.1]};
h_vfd = zeros(1, length(f_vfd_list));

for k = 1:length(f_vfd_list)
    f_k = f_vfd_list(k);
    ratio_f = f_k / f_nom;
    n_sync_k = 120 * f_k / p;
    w_sync_k = 2 * pi * n_sync_k / 60;
    
    if f_k <= f_nom
        V_ph_k = V_ph * ratio_f;
    else
        V_ph_k = V_ph;
    end
    
    idx_valid = find(n_axis_vfd >= 0 & n_axis_vfd <= n_sync_k);
    n_sub = n_axis_vfd(idx_valid);
    s_sub = max((n_sync_k - n_sub) ./ n_sync_k, 1e-4);
    
    V_boost = V_ph_k + (f_k < 30) * 7.5;
    X_tot_k = (X_th + X2) * ratio_f;
    T_sub = (3 / w_sync_k) .* (V_boost^2 .* (R2_nom ./ s_sub)) ./ ((R_th + R2_nom ./ s_sub).^2 + X_tot_k^2);
    
    if f_k <= f_nom
        h_vfd(k) = plot(n_sub, T_sub, '-', 'color', colors_vfd{k}, 'linewidth', 2.1);
    else
        h_vfd(k) = plot(n_sub, T_sub, '--', 'color', colors_vfd{k}, 'linewidth', 2.1);
    end
end

T_pump_load = 95 .* (n_axis_vfd ./ 1455).^2;
h_pump = plot(n_axis_vfd, T_pump_load, 'k-', 'linewidth', 2.3);

plot(1455, 95, 'ko', 'markersize', 7, 'markerfacecolor', 'y');
plot(1028, 95*(1028/1455)^2, 'ko', 'markersize', 7, 'markerfacecolor', 'g');

text(1090, 115, sprintf('Titik Kerja 50 Hz\n(Daya P = 100%%)'), 'fontsize', 7.8, 'fontweight', 'bold');
text(490, 58, sprintf('Titik Kerja 35 Hz (70%% RPM):\nDaya Pompa P \\propto n^3 \\approx 34%%!\n(Hemat Energi 66%%)'), ...
     'fontsize', 7.8, 'fontweight', 'bold', 'color', [0.05 0.45 0.15]);
text(1365, 240, sprintf('V/f = Konstan\n(f <= 50 Hz)\n\nField Weakening\n(f > 50 Hz)'), ...
     'fontsize', 7.6, 'color', [0.65 0.1 0.1], 'fontweight', 'bold');

hold off; grid on;
title('(b) Regulasi VFD (V/f Konstan) & Beban Pompa Sentrifugal', 'fontsize', 10, 'fontweight', 'bold');
xlabel('Kecepatan Putar Rotor, n_r (rpm)', 'fontsize', 9.5);
ylabel('Torsi Mekanik, T (Nm)', 'fontsize', 9.5);
legend([h_vfd, h_pump], ...
       {'VFD f = 15 Hz (V/f Konstan)', ...
        'VFD f = 25 Hz (V/f Konstan)', ...
        'VFD f = 35 Hz (V/f Konstan)', ...
        'VFD f = 50 Hz (Base Speed)', ...
        'VFD f = 60 Hz (Field Weakening)', ...
        'Beban Pompa (T_L \propto n^2)'}, ...
       'location', 'northwest', 'fontsize', 7.1);
xlim([0 1850]); ylim([0 345]);

print(hFig2, 'starting_vfd_induksi.png', '-dpng', '-r300');
fprintf('2. Grafik starting_vfd_induksi.png (300 DPI) berhasil diperbarui.\n');
close(hFig2);
fprintf('=== Simulasi Motor Induksi Selesai ===\n');
