clear all
close all
%% Import data from text file
% Script for importing data from the following text file:
%
%    filename: \\atlas\projectlibrary\ChemSensors\GeneM\GDF pH Sensor\Data\Performances\GDF2001\AE_GDF2001_122022_Ch F\AE_GDF2001_122022_Ch F.csv
%
% Auto-generated by MATLAB on 03-Jan-2023 13:19:14

%% Set up the Import Options and import the data
opts = delimitedTextImportOptions("NumVariables", 30);

% Specify range and delimiter
opts.DataLines = [25, Inf];
opts.Delimiter = ",";

% Specify column names and types
%opts.VariableNames = ["LabviewDateTime", "ThermistorTemp", "BathTemp", "BathSetPoint", "PressuredBar", "MaxFlow", "FlowRate", "PumpVolume", "CRC", "ID", "DATETIME", "UTCSECS", "CTDDEPTH", "CTDTEMP", "CTDSALINITY", "SAMPLECOUNTER", "RESETCOUNTER", "ERRORCOUNTER", "HOUSINGTEMPERATURE", "HOUSINGHUMIDITY", "INPUTVOLTAGE", "INPUTCURRENT", "FOOBARPHVALUE", "BACKUPBATTERY", "VRSVOLTS", "VRSSTDDEV", "VKVOLTS", "VKSTDDEV", "IKAMPS", "IBAMPS"];
opts.VariableNames = ["dtLV",     "thermTemp", "bathTemp", "bathSP", "pressureDBar", "maxFlow", "flowRate", "pumpVolume", "CRC",    "ID",          "dateTime", "utcSecs", "ctdDepth", "ctdTemp", "ctdSalinity", "sampleCounter", "resetCounter", "errorCounter", "housingTemp", "housingHumidity", "inputVoltage", "inputCurrent", "foobarPHValue", "backupBattery", "vrsVolts", "vrsStdDev", "vkVolts", "vkStdDev", "ikAmps", "ibAmps"];
opts.VariableTypes = ["datetime", "double",    "double",   "double", "double",       "double",  "double",   "double",     "string", "categorical", "datetime", "double",  "double",   "double",   "double",      "double",        "double",       "double",      "double",       "double",         "double",       "double",       "double",        "double",         "double",   "double",    "double",  "double",   "double", "double"];
%opts.VariableNames = ["dtLV",              "thermTemp",      "bathTemp", "bathSP",       "pressureDBar", "maxFlow", "flowRate", "cycleNum",    "pumpVolume", "CRC", "ID", "dateTime", "utcSecs", "ctdDepth", "ctdTemp", "ctdSalinity", "sampleCounter", "resetCounter", "errorCounter", "housingTemp", "housingHumidity", "inputVoltage", "inputCurrent", "foobarPHValue", "backupBattery", "vrsVolts", "vrsStdDev", "vkVolts", "vkStdDev", "ikAmps", "ibAmps"];
%opts.VariableTypes = ["datetime", "double", "double",   "double", "double",         "double", "double",     "double",   "double", "string", "categorical", "datetime", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double"];

% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";

% Specify variable properties
opts = setvaropts(opts, "CRC", "WhitespaceRule", "preserve");
opts = setvaropts(opts, ["CRC", "ID"], "EmptyFieldRule", "auto");
%opts = setvaropts(opts, "dtLV", "InputFormat", "MM/dd/uuuu hh:mm:ss aa");
%opts = setvaropts(opts, "dateTime", "InputFormat", "MM/dd/uuuu hh:mm:ss aa");

%% Process files
path = '\\atlas\ProjectLibrary\ChemSensors\GeneM\GDF pH Sensor\Data\Cal Data\Calcs\DataFiles\';
fullPath = strcat(path, '*.csv');

dataFiles = dir(strcat(path, '*.csv'));
fileDatenums = dataFiles.date;
[sortedTime, i] = sort([dataFiles.datenum]);
sortedDataFiles = dataFiles(i);

figIncr = 0.05;

%for i=1:length(dataFiles)
for i=1:1
    % Import the data
    disp("Processing: " + dataFiles(1).name);
    %data{i} = readtable(strcat(path, sortedDataFiles(i).name), opts);
    data{i} = readtable('\\atlas\ProjectLibrary\ChemSensors\GeneM\GDF pH Sensor\Data\Cal Data\Calcs\DataFiles\GDF033_04102024_Ch A.csv', opts);

    %% Plot Environmental Conditions
    figure('Units', 'Normalized', 'Position', [.01 + i*figIncr, .01 + i*figIncr, .7 .7], 'Name', sortedDataFiles(i).name, 'NumberTitle', 'off')
    subplot(3,2,1)
    yyaxis right
    plot(data{i}.dtLV, data{i}.pressureDBar)
    ylabel("Pressure (dBar)")
    yyaxis left
    plot(data{i}.dtLV, data{i}.thermTemp, data{i}.dtLV, data{i}.bathTemp, data{i}.dtLV, data{i}.housingTemp)
    ylabel("Temperature (degC)")
    legend(["Thermistor Temp" "Bath Temp" " Housing Temp" "Pressure"]);
    title("Pressure, Temperature vs Time");

    subplot(3,2,2)
    pRate{i} = (data{i}.pressureDBar(2:end) - data{i}.pressureDBar(1:end-1))./seconds(data{i}.dtLV(2:end) - data{i}.dtLV(1:end-1));
    plot(data{i}.dtLV(2:end), pRate{i})
    title("Pressurization Rate vs. Time");
    ylabel("Pressurization Rate (dBar/sec)")

    %% Plot sensor data vs time
    subplot(3,2,3)
    title("Vrs and Vrs Std Dev vs Time");
    yyaxis left
    plot(data{i}.dtLV, data{i}.vrsVolts)
    ylabel("Vrs (volts)");
    yyaxis right
    plot(data{i}.dtLV, data{i}.vrsStdDev)
    ylim([0 0.001]);
    ylabel("Vrs Std Dev (volts)");

    subplot(3,2,4)
    title("Vk and Vk Std Dev vs Time");
    yyaxis left
    plot(data{i}.dtLV, data{i}.vkVolts)
    ylabel("Vk (volts)");
    yyaxis right
    plot(data{i}.dtLV, data{i}.vkStdDev)
    ylim([0 0.001]);
    ylabel("Vk Std Dev (volts)");

    subplot(3,2,5)
    title("Ik and Ib vs Time");
    yyaxis left
    plot(data{i}.dtLV, data{i}.ikAmps)
    ylabel("Ik (amps)");
    yyaxis right
    plot(data{i}.dtLV, data{i}.ibAmps)
    ylabel("Ib (amps)");
end

%Plot basic 3D view
figure
x = datenum(data{1}.dtLV)';
y = data{1}.pressureDBar' ;
z = data{1}.vrsVolts';

plot3(x, y, z)

for i=1:10
    cycle{i}.dt = data{1}.dtLV(find(data{1}.cycleNum == i));
    cycle{i}.pressureDBar = data{1}.pressureDBar(find(data{1}.cycleNum == i));
    cycle{i}.vrsVolts = data{1}.vrsVolts(find(data{1}.cycleNum == i));
    cycle{i}.vrsStdDev = data{1}.vrsStdDev(find(data{1}.cycleNum == i));
    cycle{i}.thermTemp = data{1}.thermTemp(find(data{1}.cycleNum == i));
    cycle{i}.pressureDBar = data{1}.pressureDBar(find(data{1}.cycleNum == i));
    cycle{i}.vkVolts = data{1}.vkVolts(find(data{1}.cycleNum == i));
    cycle{i}.vkStdDev = data{1}.vkStdDev(find(data{1}.cycleNum == i));
    cycle{i}.ikAmps = data{1}.ikAmps(find(data{1}.cycleNum == i));
    cycle{i}.ibAmps = data{1}.ibAmps(find(data{1}.cycleNum == i));
    cycle{i}.temperature = data{1}.thermTemp(find(data{1}.cycleNum == i));
end

figure
hold on;

colormap(jet);
colorValue = -5;

for i=1:10
    x = datenum(cycle{i}.dt)';
    y = cycle{i}.pressureDBar' ;
    z = cycle{i}.vrsVolts';
    temperature = cycle{i}.temperature';

    lineColor = colorValue * ones(1, length(x));
    plot3(x, y, z);
    patch([x nan], [y nan], [z nan], [lineColor nan],'EdgeColor','interp','FaceColor','none')
    if(mod(i,2) == 0)
        colorValue = colorValue + 5;
    end
end
set(gca, 'ydir', 'reverse');
view(3);
datetick('x', 'mmmdd HH:MM')
grid on
colorbar;
xStart = datenum(cycle{1}.dt(1));
xEnd = datenum(cycle{length(cycle)}.dt(end));
xlim([xStart xEnd]);

xTemperature = datenum(data{1}.dtLV)';
yTemperature = zeros(size(xTemperature))';
zTemperature = data{1}.thermTemp';
zLimits = zlim;
zSpan = zLimits(2) - zLimits(1);
tSpan = max(zTemperature) - min(zTemperature);
zT = zTemperature / max(zTemperature);
zT = zT * zSpan;
zT = zT + min(data{1}.vrsVolts);
plot3(xTemperature, yTemperature, zT)

hold off

errorsIndex = 1;
for i= 1:2:10
    x = [cycle{i}.pressureDBar' cycle{i+1}.pressureDBar'];
    y = [cycle{i}.vrsVolts' cycle{i+1}.vrsVolts'];
    
    polyFitVals = polyfit(x, y, 3);
    yFit = polyval(polyFitVals, x);
    errors = yFit - y;

    cycleMaxError(errorsIndex) = max(errors);
    cycleMinError(errorsIndex) = min(errors);
    errorsIndex = errorsIndex + 1;
   
    figure
    plot(x, y, x, yFit);
    ylabel('Vrs (volts)');
    xlabel('Pressure dBar)')
    hold on
    yyaxis right
    plot(x, errors)
    title(['Cycle Num:' num2str(i) ' and ' num2str(i+1) ' at Temperature: ' num2str(cycle{i}.temperature(1)) ' to ' num2str(cycle{i+1}.temperature(end))]);
    ylabel('Vrs Fit - Vrs (volts)');
    ylim([-0.002 0.002]);
    hold off
end

figure
plot(cycleMaxError)
hold on
plot(cycleMinError)
title('Max and Min fit errors for each up/down cycle')
ylabel('Vrs fit error (volts)')


