% Title: FFT Compressor
%
% Name: Sargant Raphael
%
% Matriculation number: m12001618
%
% Date: 23.06.2022
%
% Task: Excersie for FFT
%
%% Prepare Workspace
close all;
clear;
%% Import Data
% locate the data

fileName = ('CompressorRawSignal12891Hz.csv');
folderPath = pwd;
filePath = fullfile(folderPath, fileName);

csvData = readtable(filePath);

%% Extract our Data
% Use all colums and line 1

vibData = csvData{:,'ch1DataRaw'}

% Compute the sampling time

samplingFrequency = 12891;
samplingTime = 1/samplingFrequency;

% COmpute the number of samples

nrSamples = numel(vibData);
%n = numel(A) returns the number of elemnts n, in array A, equivalent to
%prod(size(A))

indexTime = [1:1:nrSamples]';

% Create the time vector

time = indexTime*samplingTime;

%% Compute the FFT of the vibrational data

[halfspectrum, fvals] = realFFT(vibData, samplingFrequency);

%% Plot the given Data

fig = figure;
subplot(2,1,1);
plot(time,vibData);
hold on;
grid minor;
xlim([0 max(time)]);
ylim([-4000 4000]);
xlabel('Time [s]');
title('Fourier Analysis of a Piston Compressor');
ylabel('Amplitude [mg]');

% Find the maximum frequency and magnitude
[maxMagnitude, indexMaxMag] = max(abs(halfspectrum));

maxFrequency = fvals(indexMaxMag);

rotaionSpeed = maxFrequency*60;

% Plot the second graph
subplot(2,1,2);
stem((fvals .* 60), abs(halfspectrum));
grid minor;
hold on;
xlim([0 4000]);
ylim([0 1100]);
xlabel ('Frequency [RPM]');
ylabel ('Magnitude [mg]');

plot(rotaionSpeed, maxMagnitude, 'ro');

% Define the interpolation and plot it

% x values
x1 = fvals(indexMaxMag - 1)*60;
x2 = fvals(indexMaxMag)*60;
x3 = fvals(indexMaxMag + 1)*60;

% y values
y1 = abs(halfspectrum(indexMaxMag - 1));
y2 = abs(halfspectrum(indexMaxMag));
y3 = abs(halfspectrum(indexMaxMag + 1));

% the interpolation
x = [x1 x2 x3];
y = [y1 y2 y3];
xx = x1 : 0.05 : x3;
s = spline(x,y,xx);
plot(xx, s, 'r');
hold on;

% Add additional text
txt = ['Maximum Peak at' num2str(rotaionSpeed) 'RPM'];
text( 50,800,txt);






