% GenerateHtml - Generates html documentation for the learning results.
%

%clear
close all;
% parameter settings
maxDisplayImg = 6000;
working_add='working';

tr_or_tt='train';
load partLocConfig % templateSize category locationShiftLimit orientShiftLimit numElement numCluster numIter
load learning_result %bestActivations bestS2Templates
activations = bestActivations;
zipname = sprintf('ABC.zip');
imFolder = 'ABC';

activations = bestActivations;
scores = activations(6,:);
overallScore = sum(scores);
totalACT=size(activations,2);
BIC = overallScore - sum(numElementAll)*log(sqrt(totalACT));


% delete the previous version
html_dir = 'document';
if ~exist(html_dir,'dir')
    mkdir(html_dir);
%else
%     rmdir(html_dir,'s');  % TODO: find out why removing existing dir causes error (in GenerateHtml.m) 
%     mkdir(html_dir);
end

html_path = sprintf('%s/%s.html',html_dir,imFolder);
html = fopen(html_path,'w');

html_img_dir = sprintf('document/%s/',imFolder);
if ~exist(html_img_dir,'dir')
    mkdir(html_img_dir);
end

%% html header
% note: modified on Jan 13, 2010. Some url's are now absolute. Only 
%   copied files are linked with relative url.
tmp = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n';
tmp = [tmp '<html>\n'];
tmp = [tmp '<head>\n'];
tmp = [tmp '<title>ABC: Active Basis Codebooks</title>\n'];
tmp = [tmp '</head>\n'];
fprintf(html,tmp);
fprintf(html, '<body>\n');
fprintf( html, '<div id="header">\n');
fprintf( html, '<h1>ABC: Active Basis Codebooks</h1></div>\n' );
fprintf( html, '\n<div id="content">\n');

%% table of content
fprintf( html, '<div id="content">\n' );
fprintf( html, '<div id="TableOfContents">\n' );
fprintf( html, '<p>Contents</p>\n' );
fprintf( html, '<ul>\n' );
fprintf( html, '<li>\n' );
fprintf( html, '<A href="#download">Download</A>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '<li>\n');
fprintf( html, '<a href="#traindata">Learned templates</a>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '<li>\n');
fprintf( html, '<a href="#traindata">Training examples</a>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '<li>\n' );
fprintf( html, '<a href="#templates">Testing examples</a>\n' );
fprintf( html, '</li>\n' );
fprintf( html, '</ul>\n' );
fprintf( html, '</div>\n' );

%% for download
fprintf( html, '<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div>\n' );
fprintf( html, '<a name="download"></a> <table cellspacing="10" cellpadding="10" class="center" width="60%%">\n' );
fprintf( html, '\n<tr><td>\n' );
fprintf( html, '\n<b>Code and data: (<a href="%s">ZIP</a>).</b>\n', zipname );
fprintf( html, '\n</td>\n' );
fprintf( html, '\n<td>\n' );
fprintf( html, '\n</td>\n' );
fprintf( html, '\n</tr>\n' );
fprintf( html, '\n<tr>\n' );
fprintf( html, '\n<td colspan=2 align=left>\n' );
fprintf( html, '\nRun StartFromHere.m in Matlab. You can monitor intermediate results in the folder: output/. \n' );
fprintf( html, '\n</td>\n' );
fprintf( html, '\n</tr>\n' );
fprintf( html, '\n</table>\n' );

%% explain the parameters
fprintf(html, '<div style="border-top:1 solid #dddddd; margin-top:0.3em;"></div> ');
fprintf(html, '\n<p><b>Parameters</b>: <br>');
fprintf( html, sprintf('The number of training images is %d. ',numImageTrain));
fprintf( html, sprintf('The size of each active basis template is %d (width) by %d (height) pixels. ',templateSize(2),templateSize(1)));
fprintf( html, sprintf('Maximum number of Gabor elements in each template is %d. ',numElement));
fprintf( html, sprintf('For Gabor wavelets we use a scale of %.2f and %d quantized orientations within PI (in radian). ',scales,numOrient));
fprintf( html, sprintf('Each Gabor element is allowed to move %d pixels and rotate %d orientation step(s) at most. ',locationShiftLimit,orientShiftLimit));
fprintf( html, sprintf('<p>In total the codebook consists of %d active basis templates. ',numCluster));
fprintf( html, sprintf('For unsupervised learning, we randomly start at %d initializations. ',numRandomStart));
fprintf( html, sprintf('Then %d iterations are carried out. ',numIter));
fprintf( html, sprintf('In the encoding step, the activated templates need to have a SUM2 score of at least %d. ',S2Thres));
fprintf( html, sprintf('For local inhibition between templates, the minimum distance between two activated template is %.2f times the size of template. ',locationPerturbationFraction));
fprintf( html, sprintf('Allowed template rotations: ['));
fprintf( html, sprintf('%d',rotationRange(1)) );
for rr = rotationRange(2:end)
	fprintf( html, sprintf(', %d',rr) );
end
fprintf( html, ']. ');
fprintf( html, sprintf('Allowed image resolutions (relative): ['));
fprintf( html, sprintf('%.2f',allResolution(1)) );
for rr = allResolution(2:end)
	fprintf( html, sprintf(', %.2f',rr) );
end
fprintf( html, ']. ');
if resizeTrainingImages
	fprintf( html, sprintf('As a pre-processing step, the input images are resized by a factor of %.2f.', resizeFactor));
end
fprintf( html, '</p>\n ');

%% show learned templates
fprintf(html, '<div style="border-top:1 solid #dddddd; margin-top:0.3em;"></div> ');
fprintf(html, '\n<p><b>Learned templates</b>. ');
% show sorted template with black and white
fprintf( html, ['<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div><a name="templates"></a>Show sorted templates according to their log-lik (some entries may be empty):\n']);
fprintf( html, '\n</p>' );
fprintf( html, '\n<p>' );
new_template_name = sprintf('template_sorted.png');
src = sprintf('./output/%s',new_template_name);
dst = sprintf('document/%s/%s', imFolder,new_template_name);
copyfile(src,dst);
fprintf( html, '\n<img src="%s" alt="" width="600"/>', sprintf('%s/%s',imFolder,new_template_name) );
fprintf( html, '\n</p>\n' );
% show sorted template with different colors
fprintf( html, ['<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div><a name="templates"></a>Learned templates for ' num2str(numCluster) ' entries of the codebook (after ' num2str(numIter) ' iterations)' ...
    ' (some entries may be empty):\n']);
fprintf( html, '\n</p>' );
fprintf( html, '\n<p>' );
for cc=1:numActiveClusters
    new_img_name = sprintf('color_template%d.png',tempOrder(cc));
    src = sprintf('./output/%s',new_img_name);
    dst = sprintf('document/%s/%s', imFolder,new_img_name);
    copyfile(src,dst);
    fprintf( html, '\n<img src="%s" alt="" width="60"/>', sprintf('%s/%s',imFolder,new_img_name) );
end;
fprintf( html, '\n</p>\n' );
% show sequences of templates
fprintf( html, ['<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div><a name="templates"></a>Show sequences of iterations of templates: \n']);
fprintf( html, '\n<p>' );
for cc=1:numCluster
    for iter = 1:numIter
        new_img_name = sprintf('template%d_Iter%d.png',cc,iter);
        src = sprintf('./output/%s',new_img_name);
        dst = sprintf('document/%s/%s', imFolder,new_img_name);
        copyfile(src,dst);
        fprintf( html, '\n<img src="%s" alt="" width="60"/>', sprintf('%s/%s',imFolder,new_img_name) );
    end;
    fprintf( html, '<br>' );
end;
fprintf( html, '\n</p>' );
fprintf( html, sprintf('numbers of elements: ['));
fprintf( html, sprintf('%d',numElementAllsort(1)) );
for rr = numElementAllsort(2:end)
	fprintf( html, sprintf(', %d',rr) );
end
fprintf( html, ']. ');
%% training examples
fprintf(html, '<div style="border-top:1 solid #dddddd; margin-top:0.3em;"></div> ');
fprintf(html, '\n<p><b>Traing images and their sketches:</b></p>');
% read the training examples
Iname = dir('positiveImage/*.jpg');
n = length(Iname);
if n > maxDisplayImg
	ind = randperm(n);
	selected_img = ind(1:maxDisplayImg);
	Iname = Iname(selected_img);
else
	selected_img = 1:n;
end
% render sketched images with activated partial templates
destFolder = sprintf('document/%s',imFolder);
displayActivations;
% move the images to img/ folder
for i = 1:length(Iname)
    new_img_name = Iname(i).name;
    src = sprintf('positiveImage/%s',new_img_name);
    dst = sprintf('document/%s/%s_%s',imFolder, tr_or_tt,new_img_name);
    copyfile(src,dst);
end
% generate corresponding html
fprintf( html, '\n<p>' );
for i = 1:length(Iname)
    fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_%s',imFolder,tr_or_tt,Iname(i).name) );
end
fprintf( html, '\n</p>\n' );
% show sketched images
% 1) overlayed with the source image
% 2) with different colors indicating different codewords
% 3) with bounding boxes of codewords
fprintf( html, ['<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div>\n<a name="templates"></a><p>' ...
	'Sketching the observed images by overlaying the activated templates on them:' ...
	'</p>\n']);
fprintf( html, '\n<p>' );
for i = 1:length(Iname)
	fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_overlayed_image%d.png',imFolder,tr_or_tt,i) );
end
fprintf( html, '\n</p>\n' );
fprintf( html, '\n<p>Showing only the activated templates (with color): </p><p>' );
for i = 1:length(Iname)
	fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_colorsketch_image%d.png',imFolder,tr_or_tt,i) );
end
fprintf( html, '\n<p>Showing only the activated templates (with bounding boxes): </p><p>' );
for i = 1:length(Iname)
	fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_sketch_image%d.png',imFolder,tr_or_tt,i) );
end
fprintf( html, '\n</p>\n' );

%fprintf( html, sprintf('The BIC is %.2f.', BIC));
fprintf( html, '\n</p>\n' );
adjustedBIC  = ratio*overallScore - sum(numElementAll)*log(sqrt(totalACT));
fprintf( html, sprintf('The adjusted BIC is %.2f.', adjustedBIC));
fprintf( html, '\n</p>\n' );



%% testing examples
if  exist('./testImage','dir')
    fprintf(html, '<div style="border-top:1 solid #dddddd; margin-top:0.3em;"></div> ');
    fprintf(html, '\n<p><b>Testing images and their sketches:</b></p>');
    % read the training examples
    tr_or_tt='test';
    working_add='test_working';
    activations = test_activations;
    Iname = dir('testImage/*.jpg');
    n = length(Iname);
    if n > maxDisplayImg
        ind = randperm(n);
        selected_img = ind(1:maxDisplayImg);
        Iname = Iname(selected_img);
    else
        selected_img = 1:n;
    end
    % render sketched images with activated partial templates
    destFolder = sprintf('document/%s',imFolder);
    displayActivations;
    % move the images to img/ folder
    for i = 1:length(Iname)
        new_img_name = Iname(i).name;
        src = sprintf('testImage/%s',new_img_name);
        dst = sprintf('document/%s/%s_%s',imFolder,tr_or_tt, new_img_name);
        copyfile(src,dst);
    end
    % generate corresponding html
    fprintf( html, '\n<p>' );
    for i = 1:length(Iname)
        fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_%s',imFolder,tr_or_tt,Iname(i).name) );
    end
    fprintf( html, '\n</p>\n' );
    % show sketched images
    % 1) overlayed with the source image
    % 2) with different colors indicating different codewords
    % 3) with bounding boxes of codewords
    fprintf( html, ['<div style="border-bottom:1 solid #dddddd; margin-top:0.3em;"></div>\n<a name="templates"></a><p>' ...
        'Sketching the observed images by overlaying the activated templates on them:' ...
        '</p>\n']);
    fprintf( html, '\n<p>' );
    for i = 1:length(Iname)
        fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_overlayed_image%d.png',imFolder,tr_or_tt,i) );
    end
    fprintf( html, '\n</p>\n' );
    fprintf( html, '\n<p>Showing only the activated templates (with color): </p><p>' );
    for i = 1:length(Iname)
        fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_colorsketch_image%d.png',imFolder,tr_or_tt,i) );
    end
    fprintf( html, '\n<p>Showing only the activated templates (with bounding boxes): </p><p>' );
    for i = 1:length(Iname)
        fprintf( html, '<img src="%s" alt="" height=80/>', sprintf('%s/%s_sketch_image%d.png',imFolder,tr_or_tt,i) );
    end
    fprintf( html, '\n</p>\n' );
    
end;


%% finishing off
fprintf( html, '\n\n\n</div> \n');
fprintf( html, '<div id="last" class="footer"></div>' );
fprintf(html, '</body> </html> \n');
fclose(html);
disp('finished generating Html... go to document folder and click the html');

close all
