#!/usr/bin/python
# -*- coding: utf-8 -*-

import pylab, pymatrices, pycomparator, codecs, os, numpy 

class TScoreHistogram(object):
	def __init__(self, matrix, words_file, min_cdf_p = 0.9999):
		self.min_cdf_p = min_cdf_p
		self.words = self.__load_words(words_file)
		if isinstance(matrix, pymatrices.SuperMatrixPtr):
			self.matrix = matrix
		else:
			self.matrix = self.__load_matrix(matrix_path)
		self.flex = 'subst'

	def save_histogram(self,word, outfile, bins = 100, show = True, normed = True):
		row_vals = self.matrix.GetRow(word).GetValues()
		if len(row_vals) == 0:
			print "Empty row for word", word
			return
		vals = numpy.zeros( len(row_vals) )
		i = 0
		for ind in row_vals.keys():
			vals[i] = row_vals[ ind ]
			i += 1

		if bins == None:
			(en, eb) = numpy.histogram(vals, normed = normed)
			bins = eb

		pylab.hist(vals, bins=bins, normed=normed)
		pylab.title(word.decode('cp1250'))
		pylab.ylabel("Liczba cech")
		pylab.xlabel(u"Wartość t-score")
		pylab.savefig(outfile)
		if show:
			pylab.show()
		pylab.close()

	def save_all(self, bins, show = True, path = './', normed = True):
		for w in self.words:
			word = self.flex + ":" + w
			word = word.encode('cp1250')
			if self.matrix.GetRowIndex(word) > self.matrix.NumberOfRows():
				print "No word",word,"in matrix, skipping..."
				continue
			filename = os.path.join(path, w + "_hist.png")
			print "Writing histogram to file",filename
			self.save_histogram(word, filename.encode('utf-8'), bins, show, normed)

	def __load_words(self, filename, encoding = 'cp1250'):
		words = []
		for line in codecs.open( filename, 'r', encoding):
			line = line.strip()
			if len(line) > 0:
				words.append(line)
		return words

	def __load_matrix(self, matrix_path):
		mdir, mname = os.path.split( os.path.dirname(matrix_path))
		matrix = pymatrices.LoadSuperMatrix(mdir, mname, False, True)
		#pycomparator.tscore_weight_matrix(matrix)
		pycomparator.tscore_cdfp_weight_matrix(matrix, self.min_cdf_p)
		return matrix

