package svm.instances.dependency.kernel;

import java.util.HashMap;

import svm.instances.dependency.TokenSequence;
import base.CachedKernel;

public class BagOfWordKernel extends CachedKernel<TokenSequence>
{
	int degree = 1;
	/**
	 * 
	 */
	private static final long serialVersionUID = -7214455271269701004L;

	public BagOfWordKernel(int i)
	{
		degree = i;
	}

	protected double sK(TokenSequence a, TokenSequence b)
	{
		if (b.tokens.length < a.tokens.length)
		{
			TokenSequence c = b;
			b = a;
			a = c;
		}
		HashMap<String, Integer> words = new HashMap<>();
		for (int i = 0; i < a.tokens.length; i++)
		{
			if (!words.containsKey(a.tokens[i]))
				words.put(a.tokens[i], 1);
			else
				words.put(a.tokens[i], words.get(a.tokens[i]) + 1);
		}
		double sum = 0.000;
		for (int i = 0; i < b.tokens.length; i++)
		{
			if (words.containsKey(b.tokens[i]))
				sum += words.get(b.tokens[i]);

		}
		return sum;
	}

	@Override
	protected double K(TokenSequence a, TokenSequence b)
	{
		// TODO Auto-generated method stub
		double k = sK(a, b);
		return Math.pow(1 + k,degree);// *(1+k);// Math.exp(-0.1*(-2*sK(a,b)+sK(a,a)+sK(b,b)));
	}

}
