%%%%%%%%%This method is based Wang, Bo, Antoniette M. Maldonado-Devincci, and Lin Jiang. "Evaluating line-broadening factors on a reference spectrum as a bucketing method for NMR based metabolomics." Analytical biochemistry 606 (2020): 113872. %%%%%%%%%
clc
clear
%%%%%%%import the data from NMR%%%%%%%%%%%%
fec_raw_s = tdfread('1r.txt','tab'); %load the reference spectrum
%fec_raw = fec_raw_s.ppm_intensity;
fec_raw = [fec_raw_s.ppm,fec_raw_s.intensity];
%%%%%%%%calibrate the chemical shift%%%%%%%%%%%%%%%
fec_p = fec_raw';%transpose
fec_f = size(fec_p,2)/range(fec_p(1,:),2);
max_ppm = max(fec_p(1,:));
fecal_r = fec_p(:, (max_ppm-9.0)*fec_f:(max_ppm -0.3)*fec_f);%trim the chemical shift range to 0.3 ppm to 10.0 ppm
reference_a=fecal_r;
a_ppm = reference_a(1,:);
a_int = reference_a(2,:);
noise_left = std(a_int(12200:end));
a_int = a_int/noise_left;
a_int = a_int+10;
a_int(find(a_int<0)) = rand(1);%fill with random
%%%%%%%%find the peak ranges using the reference peak%%%%%%%%%%
a_dif = diff([1,a_int,1]);%find the difference between points
a_dif_1 = [realmin,a_dif];
a_dif_2 = [a_dif,realmin];
a_dif_p = a_dif_1.*a_dif_2;%find the crests and troughs
a_dif_p_1 = a_dif_p(2:end);
a_dif_p_1(find(a_dif_p_1>0)) = 0;
a_fin = a_dif_p_1.*a_dif;
a_ppm(find(a_fin(1:end-1)<=0))=[];%delete crest?
a_ppm_2 = [a_ppm,0];
a_ppm_3 = [0,a_ppm-0.0005];
a_ppm_4 = [a_ppm_2;a_ppm_3]';
a_ppm_f = a_ppm_4(2:end-1,:);%find the peak ranges
a_ppm_f1=a_ppm_f';
a_ppm_d = diff(a_ppm_f1);
a_ppm_f1(:,find(abs(a_ppm_d)>0.5 | abs(a_ppm_d)<0.003))=[];%delete large peaks >0.3 ppm and small peaks <0.003 ppm
a_ppm_f1(:,find(a_ppm_f1(2,:)>4.6 & a_ppm_f1(1,:)<5.2))=[];%delete the water region
a_ppm_f1 = a_ppm_f1'; % ppm range of each peaks
a_ppm_pattern = [a_ppm_f1(:,2),a_ppm_f1(:,1)];
save('a_ppm_pattern', 'a_ppm_pattern') %save files to a_ppm_pattern