%% =========================================================================
%% SIMULASI KOMPREHENSIF MESIN SINKRON (ALTERNATOR & MOTOR SINKRON)
%% Mata Kuliah   : Teknik Tenaga Listrik (Program Studi S1 Teknik Mesin)
%% Dosen Pengampu: Novalio Daratha, S.T., M.Sc., Ph.D.
%% Institusi     : Fakultas Teknik, Universitas Bengkulu
%% =========================================================================
%% Fitur Pemodelan:
%% 1. karakteristik_genset_sinkron.png (Minggu 9):
%%    (a) Kurva Karakteristik Terminal (V_t vs I_a) Generator Sinkron 3-Fasa
%%        (Diesel Genset 125 kVA, 400 V L-L, 50 Hz) pada PF Lagging, Unity, Leading
%%    (b) Komparasi Regulasi Tegangan (VR%) terhadap Sudut Faktor Daya Beban
%% 2. kurva_v_motor_sinkron.png (Minggu 10):
%%    (a) Kurva-V Motor Sinkron (I_a vs Arus Medan I_f) pada beban poros 25%, 50%, 100%
%%        beserta lokus Faktor Daya Satu (Unity PF), Under-excited, & Over-excited
%%    (b) Karakteristik Daya-Sudut Torsi (P_3phi vs delta) & Batas Pull-Out Torque
%% =========================================================================

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

fprintf('=== Memulai Simulasi Mesin Sinkron (Minggu 9 & Minggu 10) ===\n');

%% =========================================================================
%% BAGIAN 1: GENERATOR SINKRON / ALTERNATOR 3-FASA (MINGGU 9)
%% =========================================================================
% Parameter Diesel Generator Set 3-Fasa, 125 kVA, 400 V (L-L), 50 Hz, Y-connected
V_LL_nom = 400;                  % Tegangan jala-jala nominal (V line-to-line)
V_phi_nom = V_LL_nom / sqrt(3);  % Tegangan per fasa nominal (230.94 V)
S_nom = 125e3;                   % Kapasitas daya semu nominal (125 kVA)
Ia_nom = S_nom / (sqrt(3) * V_LL_nom); % Arus beban penuh (~180.4 A)
Ra = 0.035;                      % Resistansi jangkar per fasa (Ohm)
Xs = 0.320;                      % Reaktansi sinkron per fasa (Ohm)

Ia_vec = linspace(0, 180, 200);  % Rentang arus beban Ia (A)

phi_lag = acos(0.8);             % Lagging PF = 0.8 (induktif, sin(phi) > 0)
phi_uni = acos(1.0);             % Unity PF = 1.0 (resistif, sin(phi) = 0)
phi_lead = -acos(0.8);           % Leading PF = 0.8 (kapasitif, sin(phi) < 0)

% Kalibrasi E_a konstan pada masing-masing kurva agar tepat bertemu di
% titik kerja nominal beban penuh (Ia_ref = 150 A, V_LL = 400 V):
Ia_ref = 150;
Ea_lag  = sqrt((V_phi_nom*cos(phi_lag)  + Ia_ref*Ra)^2 + (V_phi_nom*sin(phi_lag)  + Ia_ref*Xs)^2);
Ea_uni  = sqrt((V_phi_nom*cos(phi_uni)  + Ia_ref*Ra)^2 + (V_phi_nom*sin(phi_uni)  + Ia_ref*Xs)^2);
Ea_lead = sqrt((V_phi_nom*cos(phi_lead) + Ia_ref*Ra)^2 + (V_phi_nom*sin(abs(phi_lead)) - Ia_ref*Xs)^2);

calc_VLL = @(Ea, Ia, cosphi, sinphi) sqrt(3) .* ( ...
    sqrt(max(0, Ea.^2 - (Ia .* (Xs.*cosphi - Ra.*sinphi)).^2)) ...
    - Ia .* (Ra.*cosphi + Xs.*sinphi) );

VLL_lag  = calc_VLL(Ea_lag,  Ia_vec, 0.8,  0.6);
VLL_uni  = calc_VLL(Ea_uni,  Ia_vec, 1.0,  0.0);
VLL_lead = calc_VLL(Ea_lead, Ia_vec, 0.8, -0.6);

% Regulasi Tegangan (VR%) pada Arus Beban Penuh (Ia_ref = 150 A)
VR_lag  = ((sqrt(3)*Ea_lag  - V_LL_nom) / V_LL_nom) * 100;
VR_uni  = ((sqrt(3)*Ea_uni  - V_LL_nom) / V_LL_nom) * 100;
VR_lead = ((sqrt(3)*Ea_lead - V_LL_nom) / V_LL_nom) * 100;

% Variasi Regulasi Tegangan terhadap sudut faktor daya phi (-60 deg s.d. +60 deg)
phi_deg_vec = linspace(-60, 60, 200);
phi_rad_vec = phi_deg_vec * pi / 180;
Ea_vs_pf = sqrt((V_phi_nom.*cos(phi_rad_vec) + Ia_ref*Ra).^2 + ...
                (V_phi_nom.*sin(phi_rad_vec) + Ia_ref*Xs).^2);
VR_vs_pf = ((sqrt(3).*Ea_vs_pf - V_LL_nom) ./ V_LL_nom) .* 100;

hFig1 = figure('visible', 'off', 'position', [50, 50, 1220, 500]);

% Subplot 1(a): V_t vs I_a
subplot(1, 2, 1);
plot(Ia_vec, VLL_lag, 'b-', 'linewidth', 2.3); hold on;
plot(Ia_vec, VLL_uni, 'g-.', 'linewidth', 2.2);
plot(Ia_vec, VLL_lead, 'r--', 'linewidth', 2.3);
plot([0 180], [400 400], 'k:', 'linewidth', 1.3);
plot(Ia_ref, 400, 'ko', 'markersize', 8, 'markerfacecolor', [1 0.85 0]);

text(6, 472, sprintf('E_{a0,Lag} = %.1f V (VR = +%.1f%%)', sqrt(3)*Ea_lag, VR_lag), ...
     'color', 'b', 'fontsize', 8, 'fontweight', 'bold');
text(6, 426, sprintf('E_{a0,Unity} = %.1f V (VR = +%.1f%%)', sqrt(3)*Ea_uni, VR_uni), ...
     'color', [0 0.5 0], 'fontsize', 8, 'fontweight', 'bold');
text(6, 376, sprintf('E_{a0,Lead} = %.1f V (VR = %.1f%%)', sqrt(3)*Ea_lead, VR_lead), ...
     'color', [0.8 0 0], 'fontsize', 8, 'fontweight', 'bold');
text(122, 422, sprintf('Titik Nominal\n(150 A, 400 V)'), 'fontsize', 8, 'fontweight', 'bold');

hold off; grid on;
title('(a) Karakteristik Terminal Genset 3-Fasa (V_{t,LL} vs I_a)', 'fontsize', 10.5, 'fontweight', 'bold');
xlabel('Arus Beban Jangkar, I_a (A)', 'fontsize', 9.5);
ylabel('Tegangan Terminal Antarfasa, V_{t,LL} (V)', 'fontsize', 9.5);
legend({'PF = 0.8 Lagging (Induktif)', ...
        'PF = 1.0 Unity (Resistif)', ...
        'PF = 0.8 Leading (Kapasitif)', ...
        'Tegangan Nominal (400 V)', ...
        'Titik Beban Penuh (150 A)'}, 'location', 'southwest', 'fontsize', 7.8);
xlim([0 180]); ylim([255 510]);

% Subplot 1(b): Regulasi Tegangan VR% vs Sudut Faktor Daya Beban
subplot(1, 2, 2);
plot(phi_deg_vec, VR_vs_pf, 'b-', 'linewidth', 2.4); hold on;
plot([-60 60], [0 0], 'k-', 'linewidth', 1.1);
plot([0 0], [-20 30], 'k:', 'linewidth', 1.2);

plot(36.87, VR_lag, 'bo', 'markersize', 8, 'markerfacecolor', 'b');
plot(0, VR_uni, 'go', 'markersize', 8, 'markerfacecolor', 'g');
plot(-36.87, VR_lead, 'ro', 'markersize', 8, 'markerfacecolor', 'r');

fill([-60 0 0 -60], [-20 -20 30 30], [1 0.9 0.9], 'facealpha', 0.22, 'linestyle', 'none');
fill([0 60 60 0], [-20 -20 30 30], [0.9 0.95 1], 'facealpha', 0.22, 'linestyle', 'none');

text(-56, 22, sprintf('ZONA LEADING (Kapasitif)\nFluks diperkuat -> VR < 0\n(Tegangan V_t Naik)'), ...
     'fontsize', 8, 'color', [0.75 0 0], 'fontweight', 'bold');
text(5, -11, sprintf('ZONA LAGGING (Induktif)\nDemagnetisasi -> VR > 0\n(Tegangan V_t Turun)'), ...
     'fontsize', 8, 'color', [0 0.2 0.7], 'fontweight', 'bold');
text(12, VR_lag+3.2, sprintf('0.8 Lag (+%.1f%%)', VR_lag), 'fontsize', 8, 'fontweight', 'bold', 'color', 'b');
text(4, VR_uni-2.8, sprintf('Unity (+%.1f%%)', VR_uni), 'fontsize', 8, 'fontweight', 'bold', 'color', [0 0.5 0]);
text(-52, VR_lead+3.5, sprintf('0.8 Lead (%.1f%%)', VR_lead), 'fontsize', 8, 'fontweight', 'bold', 'color', [0.8 0 0]);

hold off; grid on;
title('(b) Regulasi Tegangan (VR%) vs Sudut Faktor Daya (\phi)', 'fontsize', 10.5, 'fontweight', 'bold');
xlabel('Sudut Faktor Daya Beban, \phi (Derajat) [ - Leading | + Lagging ]', 'fontsize', 9.5);
ylabel('Regulasi Tegangan, VR (%)', 'fontsize', 9.5);
xlim([-60 60]); ylim([-20 30]);

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

%% =========================================================================
%% BAGIAN 2: MOTOR SINKRON - KURVA-V & SUDUT TORSI DELTA (MINGGU 10)
%% =========================================================================
Vm_LL = 400;
Vm_phi = Vm_LL / sqrt(3);        % 230.94 V
Xs_mot = 2.5;                    % Reaktansi sinkron per fasa (Ohm)
If_vec = linspace(1.5, 9.5, 250);
k_f = 50.0;                      % E_a = k_f * I_f (V/fasa)
Ea_vec = k_f .* If_vec;

P_loads = [15e3, 30e3, 60e3];

Ia_v25  = nan(size(If_vec));
Ia_v50  = nan(size(If_vec));
Ia_v100 = nan(size(If_vec));

for idx = 1:length(If_vec)
    Ea_val = Ea_vec(idx);
    Ip1 = P_loads(1) / (3 * Vm_phi);
    if Ea_val >= Xs_mot * Ip1
        Iq1 = (Vm_phi - sqrt(Ea_val^2 - (Xs_mot * Ip1)^2)) / Xs_mot;
        Ia_v25(idx) = sqrt(Ip1^2 + Iq1^2);
    end
    Ip2 = P_loads(2) / (3 * Vm_phi);
    if Ea_val >= Xs_mot * Ip2
        Iq2 = (Vm_phi - sqrt(Ea_val^2 - (Xs_mot * Ip2)^2)) / Xs_mot;
        Ia_v50(idx) = sqrt(Ip2^2 + Iq2^2);
    end
    Ip3 = P_loads(3) / (3 * Vm_phi);
    if Ea_val >= Xs_mot * Ip3
        Iq3 = (Vm_phi - sqrt(Ea_val^2 - (Xs_mot * Ip3)^2)) / Xs_mot;
        Ia_v100(idx) = sqrt(Ip3^2 + Iq3^2);
    end
end

% Lokus Faktor Daya Satu (Unity PF = 1.0)
P_locus = linspace(0, 80e3, 100);
Ip_locus = P_locus ./ (3 * Vm_phi);
Ea_unity_locus = sqrt(Vm_phi^2 + (Xs_mot .* Ip_locus).^2);
If_unity_locus = Ea_unity_locus ./ k_f;
Ia_unity_locus = Ip_locus;

% Karakteristik Daya - Sudut Torsi (P_3phi vs delta)
delta_deg = linspace(0, 180, 200);
delta_rad = delta_deg * pi / 180;
Ea_nom_mot = 300; % V/fasa pada If = 6.0 A
P_max_kw = (3 * Vm_phi * Ea_nom_mot / Xs_mot) / 1000; % ~83.14 kW
P_delta_kw = P_max_kw .* sin(delta_rad);

Ea_over_mot = 375; % V/fasa pada If = 7.5 A
P_max_over_kw = (3 * Vm_phi * Ea_over_mot / Xs_mot) / 1000; % ~103.9 kW
P_delta_over_kw = P_max_over_kw .* sin(delta_rad);

hFig2 = figure('visible', 'off', 'position', [50, 50, 1220, 500]);

% Subplot 2(a): Kurva-V Motor Sinkron
subplot(1, 2, 1);
plot(If_vec, Ia_v25, 'b-', 'linewidth', 2.1); hold on;
plot(If_vec, Ia_v50, 'g-.', 'linewidth', 2.2);
plot(If_vec, Ia_v100, 'r-', 'linewidth', 2.4);
plot(If_unity_locus, Ia_unity_locus, 'k--', 'linewidth', 1.8);

for m = 1:3
    Ip_m = P_loads(m) / (3 * Vm_phi);
    If_m = sqrt(Vm_phi^2 + (Xs_mot * Ip_m)^2) / k_f;
    plot(If_m, Ip_m, 'ko', 'markersize', 7, 'markerfacecolor', [1 0.85 0]);
end

text(1.75, 138, sprintf('UNDER-EXCITED\n(PF Lagging / Induktif)\nMenyerap Q Reaktif'), ...
     'fontsize', 8, 'color', [0.75 0 0], 'fontweight', 'bold');
text(6.15, 138, sprintf('OVER-EXCITED\n(PF Leading / Kapasitif)\nMenyuplai Q (Kapasitor)'), ...
     'fontsize', 8, 'color', [0 0.25 0.7], 'fontweight', 'bold');
text(4.8, 108, sprintf('Lokus PF = 1.0\n(I_a Minimum)'), 'fontsize', 8, 'fontweight', 'bold');

hold off; grid on;
title('(a) Kurva-V Motor Sinkron (I_a vs Arus Medan I_f)', 'fontsize', 10.5, 'fontweight', 'bold');
xlabel('Arus Eksitasi Medan Rotor, I_f (A)', 'fontsize', 9.5);
ylabel('Arus Jangkar Stator, I_a (A)', 'fontsize', 9.5);
legend({'Beban Poros 25% (15 kW)', ...
        'Beban Poros 50% (30 kW)', ...
        'Beban Poros 100% (60 kW)', ...
        'Garis Faktor Daya Satu (PF = 1.0)', ...
        'Titik Arus Minimum (cos\phi = 1)'}, 'location', 'southeast', 'fontsize', 7.4);
xlim([1.5 9.5]); ylim([-45 160]);

% Subplot 2(b): Kurva Daya-Sudut Torsi (P vs delta)
subplot(1, 2, 2);
plot(delta_deg, P_delta_kw, 'b-', 'linewidth', 2.4); hold on;
plot(delta_deg, P_delta_over_kw, 'm--', 'linewidth', 2.0);
plot([0 180], [60 60], 'k:', 'linewidth', 1.4);
plot([90 90], [0 125], 'r:', 'linewidth', 1.6);

delta_op = asind(60 / P_max_kw);
plot(delta_op, 60, 'ko', 'markersize', 8, 'markerfacecolor', 'g');
plot(90, P_max_kw, 'ro', 'markersize', 8, 'markerfacecolor', 'y');

fill([0 90 90 0], [0 0 125 125], [0.9 1 0.9], 'facealpha', 0.20, 'linestyle', 'none');
fill([90 180 180 90], [0 0 125 125], [1 0.9 0.9], 'facealpha', 0.22, 'linestyle', 'none');

text(6, 111, sprintf('ZONA OPERASI STABIL\n(0 < \\delta < 90^\\circ, dP/d\\delta > 0)'), ...
     'fontsize', 8, 'color', [0 0.45 0], 'fontweight', 'bold');
text(94, 111, sprintf('ZONA TIDAK STABIL\n(\\delta > 90^\\circ -> Pull-Out / Stall!)'), ...
     'fontsize', 8, 'color', [0.75 0 0], 'fontweight', 'bold');
text(delta_op-38, 66, sprintf('Titik Kerja\n(\\delta=%.1f^\\circ, 60 kW)', delta_op), ...
     'fontsize', 7.8, 'fontweight', 'bold');
text(52, P_max_kw+5, sprintf('Pull-Out P_{max} = %.1f kW', P_max_kw), ...
     'fontsize', 8, 'fontweight', 'bold', 'color', 'b');

hold off; grid on;
title('(b) Kurva Daya-Sudut Torsi (P_{3\phi} vs \delta) & Pull-Out', 'fontsize', 10.5, 'fontweight', 'bold');
xlabel('Sudut Torsi / Beban Mekanik, \delta (Derajat Listrik)', 'fontsize', 9.5);
ylabel('Daya Elektromagnetik 3-Fasa, P_{3\phi} (kW)', 'fontsize', 9.5);
legend({'Eksitasi Nominal (I_f=6.0 A, E_a=300 V)', ...
        'Over-excited (I_f=7.5 A, E_a=375 V)', ...
        'Beban Poros Nominal (60 kW)', ...
        'Batas Pull-Out (\delta_{max} = 90^\circ)'}, 'location', 'southwest', 'fontsize', 7.5);
xlim([0 180]); ylim([0 125]);

print(hFig2, 'kurva_v_motor_sinkron.png', '-dpng', '-r300');
fprintf('2. Grafik kurva_v_motor_sinkron.png berhasil diperbarui (300 DPI).\n');
close(hFig2);

fprintf('=== Simulasi Mesin Sinkron Selesai ===\n');
