#! /usr/bin/env python

## Borda tool

## This code is written by Davide Albanese, <albanese@fbk.eu>.
## (C) 2008 Fondazione Bruno Kessler - Via Santa Croce 77, 38100 Trento, ITALY.

## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.

## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.

## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.


from numpy import *
from optparse import OptionParser
import csv
from mlpy import *

# Command line parsing
parser = OptionParser()
parser.add_option("-f", action = "store", type = "string",
                  dest = "flname", help = "feature-lists file - required")
parser.add_option("-k", action = "store", type = "int",
                  dest = "k", help = "k of top-k sublists - required")
parser.add_option("-o", action = "store", type = "string",
                  dest = "oname", help = "output file", default = "borda.txt")

(options, args) = parser.parse_args()
if not options.flname:
    parser.error("option -f (feature-lists file) is required")
if not options.k:
    parser.error("option -k (k of top-k sublists) is required")


# Import feature-lists file
try:
    fl_str = array([[x for x in line.split(None)] for line in open(options.flname)])
except ValueError:
    raise ValueError("'%s' is not a valid feature-lists file" % options.flname)


# Link feature-name to a feature-id (from first list)
fid, fname = {}, {}
for id, n in enumerate(fl_str[0]):
    fid[n] = id
    fname[id] = n

# Build numeric feature-lists
fl_num = empty((fl_str.shape[0], fl_str.shape[1]), dtype = int)
for i in range(fl_str.shape[0]):
    for j in range(fl_str.shape[1]):
        fl_num[i, j] = fid[fl_str[i, j]]


# Compute Borda
id, ext, pos = borda(fl_num, options.k)

# Write to file
ofile = open(options.oname, "w")
ofile_writer = csv.writer(ofile, delimiter='\t', lineterminator='\n')
ofile_writer.writerow(["element", "extractions", "position"])
for i in range(id.shape[0]):
    ofile_writer.writerow([fname[id[i]], ext[i], pos[i]])
ofile.close()
