% SHARED SKETCH ALGORITHM FOR LEARNING ACTIVE BASIS -- piecewise version
%% Load in exponential model, mex C codes, and set parameters
% ExponentialModel; % this line is not needed if 'storedExponentialModel' exists
clear; close all; 
load 'storedExponentialModel'; % load in exponential model 
mex CsharedSketch.c; % learning by shared sketch algorithm
mex Csigmoid.c; % sigmoid transformation
mex CgetMAX1track.c; % get MAX1 maps and track maps
mex ClocalNormalize.c; % local normalization
epsilon = .1; % allowed correlation between selected Gabors 
subsample = 2; % subsample in computing MAX1 maps   
locationShiftLimit = 3; % shift in normal direction = locationShiftLimit*subsample pixels
orientShiftLimit = 1; % shift in orientation
numElement = 50; % number of Gabors in active basis   
Correlation = CorrFilter(allFilter, epsilon); % correlation between filters 
%% Load in training images
useMinimumSize = 1; resizeFactor = .3; % resize the input image 
useFixedSize = -1; sizex = 82; sizey = 164; % forced size of inpu image
imageFolder = 'positiveImage'; % folder of training images  
imageName = dir([imageFolder '/*.jpg']);
numImage = size(imageName, 1); % number of training images 
I = cell(1, numImage); 
for (img = 1 : numImage)
    tmpIm = imread([imageFolder '/' imageName(img).name]); 
    if size(tmpIm,3) == 3
        tmpIm = rgb2gray(tmpIm);
    end
    if (useMinimumSize>0)
       I{img} = imresize(single(tmpIm), resizeFactor, 'nearest');
    end
    if (useFixedSize>0)
       I{img} = imresize(single(tmpIm), [sizex sizey], 'nearest');      
    end     
end
if (useMinimumSize>0)   
    imageSize = zeros(numImage, 2);
    for (img = 1 : numImage)
      imageSize(img, :) = size(I{img});   
    end
    sizex = min(imageSize(:, 1)); sizey = min(imageSize(:, 2)); 
    for (img = 1 : numImage)
      I{img} = I{img}(1:sizex, 1:sizey); 
    end
end    
allSizex = zeros(1, numImage)+sizex; 
allSizey = zeros(1, numImage)+sizey; 
%% Compute SUM1 maps by Gabor filtering
disp(['start filtering']); tic
SUM1map = ApplyFilterfftSame(I, allFilter, localOrNot, localHalfx, localHalfy, -1); % SUM1 maps by Gabor filtering
disp(['filtering time: ' num2str(toc) ' seconds']);
Csigmoid(numImage, allSizex, allSizey, numOrient, saturation, SUM1map);
MAX1map = cell(numImage, numOrient); 
trackMap = cell(numImage, numOrient); 
for (img = 1:numImage)
    for (orient = 1:numOrient)
        MAX1map{img, orient} = single(zeros(floor(sizex/subsample), floor(sizey/subsample))); 
        trackMap{img, orient} = single(zeros(floor(sizex/subsample), floor(sizey/subsample))); 
    end
end
CgetMAX1track(numImage, allSizex, allSizey, numOrient, locationShiftLimit, orientShiftLimit, subsample, ...
              SUM1map, MAX1map, trackMap); 
%% Prepare output variables for learning
selectedOrient = zeros(1, numElement);  % orientation and location of selected Gabors
selectedx = zeros(1, numElement); 
selectedy = zeros(1, numElement); 
selectedlambda = zeros(1, numElement); % weighting parameter for scoring template matching
selectedLogZ = zeros(1, numElement); % normalizing constant
commonTemplate = single(zeros(sizex, sizey)); % template of active basis 
deformedTemplate = cell(1, numImage); % templates for training images 
for (img = 1 : numImage)
    deformedTemplate{img} = single(zeros(sizex, sizey));  
end
SUM2score = zeros(numImage, 1); % template matching scores for training images 
%% Learning by shared sketch algorithm
disp(['start mex-C learning']); tic
CsharedSketch(numOrient, locationShiftLimit, orientShiftLimit, saturation, subsample, ... % about active basis  
       numElement, numImage, sizex, sizey, ...
       SUM1map, MAX1map, trackMap, ... % about training images 
       halfFilterSize, Correlation, allSymbol(1, :), ... % about filters
       numStoredPoint, storedlambda, storedExpectation, storedLogZ, ... % about exponential model 
       selectedOrient, selectedx, selectedy, selectedlambda, selectedLogZ, SUM2score, ... % learned parameters
       commonTemplate, deformedTemplate); % learned templates 
disp(['mex-C learning time: ' num2str(toc) ' seconds']);
%% Display and save results
OutLearningResult; 
sizeTemplatex = sizex; sizeTemplatey = sizey; 
templateHalfx = floor(sizex/2.); templateHalfy = floor(sizey/2.); 
save 'learnedTemplate' numElement selectedOrient selectedx selectedy selectedlambda selectedLogZ ...
      numOrient halfFilterSize allFilter allSymbol locationShiftLimit orientShiftLimit saturation subsample ...
      localOrNot localHalfx localHalfy templateHalfx templateHalfy sizeTemplatex sizeTemplatey windowNormalizeOrNot; 
