%% Function to apply PSPR method
% It symbolically discretizes, computes PTP 6 and 7 , and calculate
% similarity distance between new data and reference PAFE data. 
    % Input: 1 min. epoched data
    % Outputs: PTS 6 and PTS 7
% Written by  Ruhi Mahajan and Oguz Akbilgic
% UTHSC-ORNL Center for Biomedical Informatics, Memphis, TN

function [myall myall1]=pspr(data,Ref_db, matchedpatterninfo_ref)

%% Symbolic Discretization
leng=4;

allseq={};

NN_epochs=data;

for i=1:size(NN_epochs,2)  
    
    modif = tsmovavg(NN_epochs(:,i),'m',16,1);
   
    myquant=quantile(modif,leng);    
    
    allseq=[allseq; num2seq2( modif, myquant)];
    
end


%% PSPR clustering

oz=[];
oz.list_symbol='abcde';%'abcde123456789ABCDE'
oz.numletter=length(oz.list_symbol); 
oz.nseries=size(allseq,1);
oz.maxmem=7;
oz.disttype='euc';
oz.PTPtype='nonw';%nonw: rowsums=1, w=sum of all elements=1


oz.col=zeros(1,length(oz.list_symbol));
for i=1:length(oz.list_symbol)
    
    oz.col(1,i)=hex2num(oz.list_symbol(i));
    
end

%%  Calculate PTP 6 and PTP 7 
nseries=oz.nseries;
mypatterninfo=cell(size(allseq,1),1);

sayac=nseries;
for i=1:nseries    
    
	mypatterninfo{i,1} = ptm_20161109( allseq{i,1},oz);
    
    sayac=sayac-1;
    
end


%% Create pattern database
patterndb = patterndb_20161109( mypatterninfo);


%% Match the new patterns with the reference pattern database
newmatchedpatterninfo=match_ptm_20161109_toexternalDB( mypatterninfo, Ref_db);


%% Calculate similarity between new patterns and reference database
[distmat,alldistmat] = simmat_20161114_partial(newmatchedpatterninfo,matchedpatterninfo_ref, oz);


%% Similarity index wrt PAFE for averaged PTPs

simmatrix1=alldistmat(:,:,6);
myall=mean(simmatrix1,2);

simmatrix1=alldistmat(:,:,7);
myall1=mean(simmatrix1,2);
end
