#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 21 12:39:26 2020

@author: bme106
"""
import theano.tensor as T
import lasagne
import lasagne.layers as L
import theano
import numpy as np



def cos_sim_numpy(v1, v2):
    Cos = np.dot(v1, v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))
    return Cos

def compile_cos_sim_theano():
    """
        weighted mean
        inputs[0]: options, batch x 4 x h
        inputs[1]: passage, batch x h
    """
#    v1 = inputs[0]
#    v2 = inputs[1].dimshuffle(0, 'x', 1)
#    numerator = T.sum(v1*v2, axis=2)
#    denominator = T.sqrt(T.sum(v1**2, axis=2) * T.sum(v2**2, axis=2))
#    alpha = numerator / denominator
    
    v1 = T.tensor3()
    v2 = T.matrix()
    v22 = v2.dimshuffle(0, 'x', 1)
    numerator = T.sum(v1*v22, axis=2)
    denominator = T.sqrt(T.sum(v1**2, axis=2) * T.sum(v22**2, axis=2))
    
#    v1 = T.vector(dtype=theano.config.floatX)
#    v2 = T.vector(dtype=theano.config.floatX)
#    numerator = T.sum(v1*v2)
#    denominator = T.sqrt(theano.tensor.sum(v1**2)*theano.tensor.sum(v2**2))
    return theano.function([v1, v2], numerator / denominator)

cos_sim_theano_fn = compile_cos_sim_theano()

#v1 = np.array([1., 0])
#v2 = np.array([0.5, np.sqrt(3)/2])

v2 = np.array([[1, 0], [0, 1], [0.5, 0.5]])
v11 = np.array([[1, 0], [1, 0], [1, 0.]])
v12 = np.array([[0, 1], [0, 1], [0, 1.]])
v13 = np.array([[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]])
v14 = np.array([[0.5, np.sqrt(3)/2], [0.5, np.sqrt(3)/2], [0.5, np.sqrt(3)/2]])
v1 = np.concatenate((np.expand_dims(v11, axis=1), np.expand_dims(v12, axis=1),
                     np.expand_dims(v13, axis=1), np.expand_dims(v14, axis=1)), axis=1)


print cos_sim_theano_fn(v1.astype(np.float32), v2.astype(np.float32))
print cos_sim_numpy(v1, v2)