#!/usr/bin/env python
#This is a wrapper that connect svmprob.py-common.py
from svmprob import *
from sys import exit
#-------[Interface of svmplatt]---------------------------------------------------------------
#SvmPlattTrain(PostiveAttribute[], NagtiveAttribute[], #pos, #neg, #svm_param, #platt_cv_fold):
def SvmPlattTrain(pos_x, neg_x, (svm_param, platt_cv_fold)):
	npos=len(pos_x)
	nneg=len(neg_x)
	#make x,y
	prob_x = pos_x + neg_x 	#list concate
	prob_y = [ 1]*npos + [-1]*nneg
	if platt_cv_fold > 0:
		#CV gives #platt_cv_fold model, but we have to prepare one from full-train to return
		model = svm_model(svm_problem(prob_y, prob_x), svm_param)
		#use validation decision values
		AB = SigmoidTrain(get_cv_deci(prob_x, prob_y, svm_param, platt_cv_fold), prob_y, npos, nneg)
	else:
		#use training decision values
		deci, model = get_pos_deci(prob_x, prob_y, prob_x, svm_param)
		AB = SigmoidTrain(deci, prob_y, npos, nneg)
	return AB, model

def SvmPlattProb(test_x, model):
	AB, SVMPredictor = model
	return SigmoidPredict(SVMPredictor.predict_values(test_x)[1,-1], AB)


#-------[Interface of svmdeci]---------------------------------------------------------------
def SvmDeciTrain(pos_x, neg_x, svm_param):
	#make x,y
	prob_x = pos_x + neg_x 	#list concate
	prob_y = [ 1]*len(pos_x)+ [-1]*len(neg_x)
	return svm_model(svm_problem(prob_y, prob_x), svm_param)

def SvmDeciTest(test_x, model):
	return model.predict_values(test_x)[1,-1]

#-------[Unit Test]---------------------------------------------------------------------------
def unitest():
	from random import seed
	seed(0)
	tr_p = [{1:11,2:12},{1:21,2:22}]
	tr_n = [{1:31,2:32},{1:41,2:42}]
	test = {1:41,2:42}
	#SvmPlattTrain&Prob
	model = SvmPlattTrain(tr_p, tr_n, (svm_parameter(), 2))
	if SvmPlattProb(test, model) == 0.5:
		print "OK-1"
	else:
		print "Fail-1"
		exit(1)
	#SvmDeciTrain&Prob
	model = SvmDeciTrain(tr_p, tr_n, svm_parameter())
	if SvmDeciTest(test, model) == -1.0:
		print  SvmDeciTest(test, model) 
		print "OK-2"
	else:
		print "Fail-2"
		exit(2)
	exit(0)
		
if __name__ == '__main__':
	unitest()
