%% ========================================================================
% Demo codes for Membership Function training for Super Resolution
% =========================================================================
% Code Developed by Pulak Purkait 
% ------------------------------
% ECSU, Indian Statistical Institute Kolkata
% For any questions/bug related issues, send email to: pulak_r@isical.ac.in
% Referece 
%      P. Purkait and B chanda, Fuzzy-Rule Based Approach for Single Frame 
%                                           Super Resolution, FuzzIEEE 2013
% =========================================================================
clear;
TR_IMG_PATH = 'Training';

par.dict_size  = 100;            % dictionary size
par.patch_size  = 7;            % image patch size
par.num_patch   = 100000;            % number of Document to sample
par.upscale      = 1.6;            % upscaling factor
par.ovrlap       = 2;

% par.num_patch = (par.num_patch+par.ovrlap)^2; % number of words in document

dict_path = ['Dictionary/D_' num2str(par.dict_size) ...
    '_' num2str(par.patch_size) '_' num2str(par.upscale) '.mat' ];

% % Randomly sample image patches from trainning images
% The feature vector corresponding to HR and LR patches : Xh and XWrds
% The mean vector of HR patches : XHmn , it used only for display purpose
% and has nothing to do with our algorithm

[OXh, XWrds] = rnd_smp_patch(TR_IMG_PATH, par);

hDim = size(OXh, 1);
lDim = size(XWrds, 1);

% Generating Words from the documents
% par.nSmpDoc = floor(size(XWrds, 2) / par.num_patch);
disp('Total Number of patches :');
disp(par.num_patch);

Xh = OXh - repmat(mean(OXh), size(OXh, 1), 1);
% XWrds = XWrds(:, 1:par.nSmpDoc*par.num_patch);

% [Xh, XWrds] = patch_pruning(Xh, XWrds, 20); 

Xh = Xh./repmat(sqrt(sum(Xh.^2))+eps, hDim, 1);
XWrds = XWrds./repmat(sqrt(sum(XWrds.^2))+eps, lDim, 1);
% XWrds = XWrds./repmat(sqrt(sum(XWrds.^2, 2))+eps, 1, size(XWrds, 2));


%% Parameters For k-means Clustering and the Sparse coding Technique 

X = [XWrds; Xh];
[CC, indx, Energy] = vl_kmeans(X, par.dict_size, 'verbose', 'distance', 'l2', 'algorithm', 'elkan');  
                    % You need to download and place 'vlfeat' in matlab dir. 
C = CC(1:lDim, :); 

% save matlab.mat; 

%% Fuzzy Membership Learning . 
% sig = 2.5; 
% Sig = repmat(sig, par.dict_size, lDim);
% [NewC, NewSig, D] = modularlearning(XWrds', Xh', C', Sig); 
% 
% save(dict_path, 'D', 'NewC', 'NewSig', 'par');   
% clear;
I = DispDictionary(CC(lDim+1:end, :));
imwrite(I, 'documents.png'); 
imshow(I); 

