%% Problem 4 - Alfvén-speed regression and Jeans-stability classification
% Both training datasets are generated from analytical expressions.
% No physical dataset, special MATLAB toolbox or external data file needed.
% Helpers: nn_train.m, nn_predict.m.
clear; clc; close all;

%% Part A. Learn vA/vref = b/sqrt(r) in [0.55,2]^2.
rng(41);
N = 800;
b = 0.55 + 1.45*rand(1,N);    % normalized magnetic field
r = 0.55 + 1.45*rand(1,N);    % normalized density
y = b./sqrt(r);               % dimensionless Alfvén speed

% Normalize each input using the fixed domain midpoint and half-width.
scaleInput = @(b,r) [(b-1.275)/0.725; (r-1.275)/0.725];
[netReg,regLoss] = nn_train(scaleInput(b,r),y,24,3200,0.012,false);

% Compare the neural-network prediction with the analytical surface.
axisValues = linspace(0.55,2,61);
[B,R] = meshgrid(axisValues,axisValues);
reference = B./sqrt(R);
prediction = reshape(nn_predict(netReg,scaleInput(B(:)',R(:)')),size(B));
errorMap = prediction-reference;
rmseA = sqrt(mean(errorMap(:).^2));
fprintf('Alfvén-speed regression RMSE on 61-by-61 grid: %.6g\n',rmseA);

figure;
subplot(1,3,1); imagesc(axisValues,axisValues,reference); axis xy image;
title('Exact v_A'); xlabel('b'); ylabel('r'); colorbar;
subplot(1,3,2); imagesc(axisValues,axisValues,prediction); axis xy image;
title('Network prediction'); xlabel('b'); ylabel('r'); colorbar;
subplot(1,3,3); imagesc(axisValues,axisValues,errorMap); axis xy image;
title('Prediction - exact'); xlabel('b'); ylabel('r'); colorbar;
sgtitle('Problem 4A: Alfvén speed v_A/v_{ref}=b/sqrt(r)');

figure;
semilogy(regLoss,'LineWidth',1.3); grid on;
xlabel('Epoch'); ylabel('MSE loss'); title('Alfvén regressor training');

%% Part B. Train a stable/unstable classifier for Jeans' criterion.
% q=k/kJ.  Idealized Jeans relation: omega^2/(4*pi*G*rho0)=q^2-1.
% q>1: stable; q<1: unstable; q=1: marginal (not a training label).
rng(42);
qTrain = 0.4 + 1.2*rand(1,500);
yStable = double(qTrain>1);  % stable=1, unstable=0
Xclass = (qTrain-1)/0.6;
[netClass,classLoss] = nn_train(Xclass,yStable,8,2000,0.02,true);

qTest = linspace(0.4,1.6,601);
score = nn_predict(netClass,(qTest-1)/0.6);
trueStable = double(qTest>1);
notMarginal = abs(qTest-1)>1e-12;
predStable = double(score>=0.5);
accuracy = mean(predStable(notMarginal)==trueStable(notMarginal));
brier = mean((score(notMarginal)-trueStable(notMarginal)).^2);

% Locate the network's 0.5-score decision boundary by interpolation.
idx = find(score(1:end-1)<0.5 & score(2:end)>=0.5,1);
if ~isempty(idx)
    qBoundary = qTest(idx) + (0.5-score(idx))* ...
        (qTest(idx+1)-qTest(idx))/(score(idx+1)-score(idx));
else
    qBoundary = NaN;
end
fprintf('Jeans classifier accuracy: %.2f%%\n',100*accuracy);
fprintf('Score threshold q: %.4f (exact boundary q=1)\n',qBoundary);
fprintf('Brier score on test grid: %.6g\n',brier);

figure;
plot(qTest,score,'b-','LineWidth',1.8); hold on;
plot(qTest,trueStable,'k--','LineWidth',1.2);
xline(1,':','exact marginal boundary');
yline(0.5,':','classification threshold');
xlabel('q = k/k_J'); ylabel('Predicted stable score'); grid on;
legend('Neural classifier','Exact stable label','Location','best');
title('Problem 4B: Jeans stability classification');

figure;
semilogy(classLoss,'LineWidth',1.3); grid on;
xlabel('Epoch'); ylabel('Binary cross-entropy loss');
title('Classifier training');

% Interpretation: a sigmoid score is NOT automatically a calibrated
% physical probability or a measure of uncertainty in the Jeans criterion.
