% multirunScript.m
close all;
set(0,'DefaultAxesFontSize',14)
%Run a 2d regression for each data set
[tDat,~,~,~,bFor,posDat,sysMass] = CdAMWrapper('2');
[~, ~, err3g] = runReg(tDat, posDat, bFor,sysMass);

[tDat,~,~,~,bFor,posDat,sysMass] = CdAMWrapper('3');
[~, ~, err7g] = runReg(tDat, posDat, bFor,sysMass);

[tDat,~,~,~,bFor,posDat,sysMass] = CdAMWrapper('1');
[~, ~, err10g] = runReg(tDat, posDat, bFor,sysMass);

[tDat,~,~,~,bFor,posDat,sysMass] = CdAMWrapper('4');
[~, ~, err19g] = runReg(tDat, posDat, bFor,sysMass);

% %normalize and add the L2 error from each data set
% [a,b] = size(err3g(:,:,3));
% summedErr = zeros(a,b);
% locErr = err7g(:,:,3);
% rowmax = zeros(a,1);
% for ai = 1:a
%     rowmax(ai) = max(locErr(ai,:));
% end
% locmax = max(rowmax);
% summedErr = summedErr+locErr./locmax;
% 
% locErr = err10g(:,:,3);
% rowmax = zeros(a,1);
% for ai = 1:a
%     rowmax(ai) = max(locErr(ai,:));
% end
% locmax = max(rowmax);
% summedErr = summedErr+locErr./locmax;
% 
% locErr = err19g(:,:,3);
% rowmax = zeros(a,1);
% for ai = 1:a
%     rowmax(ai) = max(locErr(ai,:));
% end
% locmax = max(rowmax);
% summedErr = summedErr+locErr./locmax;

%multiply the L2 errors from each data set
[a,b] = size(err3g(:,:,3));
summedErr = ones(a,b);
locErr = err7g(:,:,3);
summedErr = summedErr.*locErr;

locErr = err10g(:,:,3);
summedErr = summedErr.*locErr;

locErr = err19g(:,:,3);
summedErr = summedErr.*locErr;

summedErr = summedErr.^(1/3);

%plot the result, find the Cd and AM that result in the min error
figure('color','w');
massMat = err19g(:,:,1);
cdMat = err19g(:,:,2);
imagesc(massMat(1,:),cdMat(:,1),log(summedErr));
set(gca,'YDir','normal')
xlabel('Added Mass (kg)');
ylabel('Drag Coefficient')
title('Summed L1 Error Map')
colorbar

locErr = summedErr;
rowmin = zeros(a,2);
for ai = 1:a
    [rowmin(ai,1), rowmin(ai,2)] = min(locErr(ai,:));
end
[locmin, rowInd] = min(rowmin(:,1));
colInd = rowmin(rowInd,2);
hold on;
plot(massMat(1,colInd),cdMat(rowInd,1),'rx')


%rerun sims with these values
compFig = figure('color','w');
hold on;
cdGuess = cdMat(rowInd,1);
massGuess = massMat(1,colInd);

[tIn,~,~,~,bFor,realPos,sysMass] = CdAMWrapper('1');
bFor = [tIn bFor'];
R=sim('U:\matlabCalcs\updatedAddedMassSimulationNS.slx'...
    ,'srcworkspace','current');
a = R.get('posOut');
fitPos = a.signals.values;
figure(compFig);
plot(tIn,realPos,'b',tIn,fitPos,'b--');

[tIn,~,~,~,bFor,realPos,sysMass] = CdAMWrapper('3');
bFor = [tIn bFor'];
R=sim('U:\matlabCalcs\updatedAddedMassSimulationNS.slx'...
    ,'srcworkspace','current');
a = R.get('posOut');
fitPos = a.signals.values;
figure(compFig);
plot(tIn,realPos,'r',tIn,fitPos,'r--');

[tIn,~,~,~,bFor,realPos,sysMass] = CdAMWrapper('4');
bFor = [tIn bFor'];
R=sim('U:\matlabCalcs\updatedAddedMassSimulationNS.slx'...
    ,'srcworkspace','current');
a = R.get('posOut');
fitPos = a.signals.values;
figure(compFig);
plot(tIn,realPos,'g',tIn,fitPos,'g--');

xlabel('Elapsed Time (sec)');
ylabel('depth (m)');

        