%%
% Do auto clust detector training
%
% 1) Train the initial models from the clusters
% 2) Construct initial detectors.
% 3) Do run of initial detectors on train pos
% 4) Learn mixtures and construct detectors.


%% Load necessary information

load([PROCESSING_DIR 'POSITIVE_PATCHES'], 'positivePatchesPerImg', ...
  'locationInfo');
load([PROCESSING_DIR 'POS_CALC_FEATURES'], 'posFeatures', ...
  'positivePatches', 'posPatchIndexes', 'PARAMS');

load([PROCESSING_DIR 'FIG_PATCH_CLUSTERS_REF'], 'assignedClust', ...
  'centers', 'PARAMS', 'selectedClusters', 'positivePatches', ...
  'posFeatures', 'posPatchIndexes');

%% Construct the initial detectors.

load([PROCESSING_DIR 'CLUSTER_PROCESSING_INFO'], 'clusterInformation');
firstTrainDir = [PROCESSING_DIR 'firstTrainDirRef/'];
detectors = constructInitialDetectors(firstTrainDir, ...
  clusterInformation, locationInfo, posPatchIndexes, PARAMS);
save([PROCESSING_DIR 'INIT_DETECTOR_VOTE'], 'detectors');

%% Modify the mined detectors

load([PROCESSING_DIR 'detectors_MINED_ORG.mat'], 'detectors');
[voteMix, allMix] = getPerClusterVoteMix( ...
  clusterInformation, locationInfo, posPatchIndexes);
clustVotes = prepareClusterVotes(voteMix);
detectors.setMixModel(clustVotes);

save([PROCESSING_DIR 'detectors_MINED.mat'], 'detectors');


%% Do collation of detection results

load([PROCESSING_DIR 'detectors_MINED.mat'], 'detectors');
detResDir = [PROCESSING_DIR 'detectionResultTestRef/'];
collateDetectionResults(PROCESSING_DIR, detResDir, detectors, ...
  'res', 'all_detections', 0.5)
%%
detResDir = [PROCESSING_DIR 'detectionResultTrainRef/'];
collateDetectionResults(PROCESSING_DIR, detResDir, detectors, ...
  'res', 'all_detections', 0.5)

%% Collate the MMHT training data.

disp('Collating the MMHT training data');
mmhtDir = [PROCESSING_DIR 'mmhtTrainingRef2/'];
detectionResultsDir = [PROCESSING_DIR 'detectionResultTrainRef/'];
mmhtTraining = collateMMHTData(mmhtDir, detectionResultsDir);
save([PROCESSING_DIR 'MMHT_TRAINING_DATA_TEST2'], 'mmhtTraining');
disp('Done');

%% Train for the MMHT weights.

tic;
[mmhtWeights, mmhtBias] = cvx_weights_train(mmhtTraining.features, ...
  mmhtTraining.labels, 0.1);
toc;
save([PROCESSING_DIR 'MMHT_LEARNED_WTS_TEST1_p1'], 'mmhtWeights', ...
  'mmhtBias');
disp('Done');
