function scoreLogis = learnScoreLogistics(detectors, posFeatures, ...
  negFeatures, selectedClusters, assignedClust, outputDir)
% Learns the logistic regression for each detector to rescale its scores.
%
% Author: saurabh.me@gmail.com (Saurabh Singh).

fprintf('Learning score logistics ');
logisData = getLogisTrainingData(selectedClusters, ...
  posFeatures, negFeatures, assignedClust, detectors);
scoreLogis = fitLogisRegression(logisData);
if exist('outputDir', 'var')
  plotLogis(logisData, scoreLogis, outputDir)
end
fprintf('Done\n');
end

function logisData = getLogisTrainingData(selectedClusters, ...
  posFeatures, negFeatures, assignedClust, detectors)
logisData = cell(size(selectedClusters));
for i = 1 : length(selectedClusters)
  clustId = selectedClusters(i);
  elements = assignedClust == clustId;
  posFeats = posFeatures(elements, :);
  negFeats = negFeatures;
  
  features = [posFeats; negFeats];
  labels = [ones(size(posFeats, 1), 1); ...
    ones(size(negFeatures, 1), 1) * -1];

  [unused, unused, decision] = mySvmPredict(labels, ...
    features, detectors.firstLevModels{i});
  logisData{i}.id = clustId;
  logisData{i}.labels = labels;
  logisData{i}.decision = decision;
end
end

function logisParams = fitLogisRegression(logisData)
logisParams = cell(size(logisData));
for i = 1 : length(logisData)
  labs = logisData{i}.labels;
  labs(labs < 0) = 0;
  lambda = 0.3 * ones(2, 1);
  b = fitLogReg(logisData{i}.decision, labs, lambda, false);
  logisParams{i} = b;
end
end

function plotLogis(logisData, logisParams, outputDir)
for i = 1 : length(logisParams)
  x = logisData{i}.decision;
  xi = -2:0.01:2;
  y = logisData{i}.labels;
  yi = valLogReg(logisParams{i}, xi');
  yp = valLogReg(logisParams{i}, x);
  fig1 = figure(1); clf;
  plot(xi, yi, '.g');
  hold on;
  plot(x, yp, 'ob');
  plot(x, y, 'xr');
  saveas(fig1, [outputDir sprintf('%d.jpg', i)], 'jpg');
end
end