package svm.instances.binary;

import java.util.Map;
import java.util.Map.Entry;

import base.DenseVector;
import base.OutputKernel;

public class BinaryOutputKernel implements OutputKernel<DenseVector,BinaryLabel>
{

	@Override
	public double k(BinaryLabel a, BinaryLabel b)
	{
//		return a.y * b.y;
		 if((a.y<0 && b.y<0) || (a.y>0 && b.y>0))
			 return 1;
		 return 0;
	}

	@Override
	public BinaryLabel preImage(Map<BinaryLabel, Double> alphaY,DenseVector x)
	{
		double posSum = 0;
		double negSum = 0;
		for (Entry<BinaryLabel,Double> e : alphaY.entrySet())
		{
			posSum += e.getValue() * k(e.getKey(), BinaryLabel.YPOS);
			negSum += e.getValue() * k(e.getKey(), BinaryLabel.YNEG);
		}
		if (posSum > negSum)
			return BinaryLabel.ypos();
		return BinaryLabel.yneg();
	}

	@Override
	public BinaryLabel preImagePenelized(Map<BinaryLabel, Double> alphaY, BinaryLabel y,DenseVector x)
	{
		double posSum = 0;
		double negSum = 0;
		for (Entry<BinaryLabel,Double> e : alphaY.entrySet())
		{
			posSum += e.getValue() * k(e.getKey(), BinaryLabel.YPOS);
			negSum += e.getValue() * k(e.getKey(), BinaryLabel.YNEG);
		}
		if (y.equals(BinaryLabel.YNEG))
			posSum += k(BinaryLabel.YPOS,BinaryLabel.YPOS)-2*k(y,BinaryLabel.YPOS)+k(y,y);
		else
			negSum += k(BinaryLabel.YNEG,BinaryLabel.YNEG)-2*k(y,BinaryLabel.YNEG)+k(y,y);
//		System.out.println(posSum + "\t" + negSum);
		if (posSum > negSum)
			return BinaryLabel.ypos();
		return BinaryLabel.yneg();
	}

}
