clear all; close all;
disp(['================> Getting the exponential family model using negative images']);
load working/parameter; 
%% read in negative examples 
imageName = dir('negativeImage/*.jpg');  % folder that contains negative examples as q(I)
numImage = size(imageName, 1); % number of negative examples
imageSize = zeros(numImage, 2); % size of negative examples
for i = 1 : numImage
    tmpIm = imread(['negativeImage' '/' imageName(i).name]);
    if size(tmpIm,3) == 3
        tmpIm = rgb2gray(tmpIm);
    end
    I{i} = imresize(double(tmpIm), 1, 'nearest'); 
    imageSize(i, :) = size(I{i});
end
sizex = min(imageSize(:, 1)); sizey = min(imageSize(:, 2)); 
for i = 1 : numImage
    I{i} = I{i}(1:sizex, 1:sizey); 
end   % make the sizes of the training images to be the same
%% filtering negative examples
for (s = 1 : numScale)
scaleFilter = scales(s); 
localHalfx = floor(localHalfx1*scales(s)/scales(1)); 
localHalfy = floor(localHalfy1*scales(s)/scales(1)); 
disp(['start filtering negative images at Gabor Scale ' num2str(s)]);
tic
[allFilter, allSymbol] = MakeFilter(scaleFilter, numOrient);  % generate Gabor filters 
halfFilterSize = (size(allFilter{1}, 1)-1)/2;  % half size of Gabor
allFilteredImage = ApplyFilterfftSame(I, allFilter, localOrNot, localHalfx, localHalfy, 1);  % filter training images
disp(['filtering time: ' num2str(toc) ' seconds']);
%% compute histogram of q()
numBin = floor(saturation/binSize)+1;  % binnumbers
histog = zeros(numBin, 1);  % store F  
disp(['start histogramming negative images at Gabor Scale ' num2str(s)]);
Chistogram(numImage, numOrient, allFilteredImage, halfFilterSize, sizex, sizey, binSize, numBin, histog, saturation);
disp(['histogramming time: ' num2str(toc) ' seconds']);
%% compute stored lambda, expectation, logZ
figure; 
r = (0:(numBin-1))*binSize;
plot(r, histog); 
figure; 
storedExpectation = zeros(numStoredPoint, 1); 
Z = zeros(numStoredPoint, 1); 
for (k=1:numStoredPoint)
   lambda = (k-1.)*spacing; 
   p = exp(lambda*r).*(histog'); 
   Z(k) = sum(p*binSize); p = p/Z(k); 
   storedExpectation(k) = sum(r.*p*binSize);
end
storedlambda = (0:(numStoredPoint-1))*spacing; 
storedLogZ = log(Z); 
subplot(2, 1, 1); plot(storedlambda, storedExpectation);
subplot(2, 1, 2); plot(storedlambda, storedLogZ);
%% store filter properties and exponential model
Correlation = CorrFilter(allFilter, epsilon);  % correlation between filters 
storeName = ['working/storedExponentialModel' num2str(s)]; 
save(storeName, 'storedlambda', 'storedExpectation', 'storedLogZ', ...
                'scaleFilter', 'halfFilterSize', 'allFilter', 'allSymbol', 'Correlation', ...
                'localHalfx', 'localHalfy'); 
end






