% run graz-02 experiments
% written by Jimei Yang @UCM, Oct 2011
clear all;
clc

addpath('sparse-coding');
addpath('svm-struct-matlab-1.1');
addpath('graph-cut');
addpath(genpath('BP'));
addpath(genpath('liblinear-1.8'));

root_data_dir = 'Graz02';
output_dir = 'Graz02-output';
if ~isdir(output_dir)
    mkdir(output_dir);
end

img_dir = fullfile(root_data_dir,'image');
gt_dir = fullfile(root_data_dir,'gt');  

try
    load(fullfile(output_dir,'database.mat'));
catch
    database = build_database(img_dir, gt_dir);
    save(fullfile(output_dir,'database.mat'), 'database');
end

try
    load(fullfile(output_dir,'lists.mat'));
catch
    [train_list, test_list] = train_test_split(database, numTrains);
    save(fullfile(output_dir,'lists.mat'), 'train_list', 'test_list');
end

% paramters for data
pars.gridSpacing = 16;
pars.patchSizes = [64];
pars.numOBins = 16;
pars.numSBins = 4;
pars.maxImSize = 640;

% ground truth labeling
gt_dir = fullfile(output_dir,sprintf('gtLabelSet_patch%d',pars.patchSizes(1)));
try
    load([gt_dir,'.mat']);
catch
    gtLabelSet = gt_labeling(database, gt_dir, pars);
    save([gt_dir,'.mat'], 'gtLabelSet');
end

% sift feature computing
fea_dir = fullfile(output_dir,sprintf('siftFeatureSet_patch%d_o%d_s%d',pars.patchSizes(1),pars.numOBins,pars.numSBins));
try
    load([fea_dir,'.mat']);
catch
    siftFeatureSet = sift_descriptors_computing(database, fea_dir, pars);
    save([fea_dir,'.mat'], 'siftFeatureSet');
end

% max margin learning of slv-crf with lbp
category = 2;
cname = siftFeatureSet.cname{category};
pars.numBases = 512;
pars.gamma = 1e-3;
pars.lambda = 0.30;
pars.nu = 1e-6;
pars.rho = 1e-3;
pars.maxIters = 40;
pars.numTrains = 300;

model_dir = fullfile(output_dir,sprintf('slvcrf_model_%s_d%d_i%d',cname,pars.numBases,pars.maxIters));
pars.m0file = [model_dir,'_i0.mat'];
try
%     load(pars.m0file);
    load([model_dir,'.mat']);
catch
    model = slvcrf_mmlearning(siftFeatureSet, gtLabelSet, train_list{category}, category, pars);
    save([model_dir,'.mat'], 'model');
end

% crf inference for test images
result_dir = fullfile(output_dir,sprintf('slvcrf_result_%s_d%d',cname,pars.numBases));
if ~isdir(result_dir)
    mkdir(result_dir);
end
[error, score, gt] = slvcrf_testing(model, siftFeatureSet, gtLabelSet, test_list{category}, result_dir, pars);
fprintf('The mean error is %.2f.\n',mean(error));
[prec, tpr, fpr, thresh] = prec_rec(score, gt, 'plotPR', 1);
[m,idx] = min(abs(prec-tpr));
eer = tpr(idx); clfr = prec(idx);
fprintf('The equal error rate of Prec-Recall Curve is %.3f.\n',eer);
fprintf('The classification rate at EER is %.3f.\n',clfr);
save(fullfile(result_dir,'result.mat'), 'error', 'score', 'gt', 'eer', 'clfr');
