# Part of DML (Digital Music Laboratory)
# Copyright 2014-2015 Steven Hargreaves; Samer Abdallah, University of London
 
# 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 2
# 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 library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

# -*- coding: utf-8 -*-
__author__="hargreavess, abdallahs, wolffd"

import sys
from csvutils import *
from pitchutils import *
from aggregate import *
from rdflib   import RDF, RDFS
from rdfutils import parse_xsd_duration, event_ns, tl_ns, af_ns
from n3Parser import get_rdf_graph_from_n3
from semitone_hist import notes_histogram, transcription_from_csv, transcription_from_n3
from key_tonic_hist import tonic_from_n3, tonic_from_csv

# Compute aggregate pitch histogram from a list of input transcriptions.
def aggregate(transcriptions_tonics,opts):
    parser_table = { 'n3':transcription_from_n3, 
                     'csv':transcription_from_csv }

    hist = 12*[0] # will be aggragate histogram
    def add_no_norm(h): 
        for x in range(0, 12): hist[x] += h[x]
        
    def add_norm(h): 
        total=sum(h) 
        for x in range(0, 12): hist[x] += h[x]/total

    if opts['normalisation']=='piece': add_to_hist=add_norm
    else: add_to_hist=add_no_norm

    def accum(f):
        # subtract 1 from tonic because tonic_from_csv uses range 1 to 12 whilst this script uses 0 to 11
        add_to_hist( rotate_left( notes_histogram(decode_tagged(parser_table,f['transcription'])), 
                                  argmax(find_tonic_histogram(f['tonic']['value'],f['duration']))))

    # do_stuff                                
    stats=for_each(transcriptions_tonics,accum)
    return { 'result': discrete_hist([str(i) for i in range(1,13)],hist), 'stats':stats }

def rotate_left(x,n): return x[n:]+x[:n]

def argmax(x): return max(range(0,len(x)),key=x.__getitem__)

# Parse the qm-keydetector_tonic csv file, and generate
# a tonic histogram
def find_tonic_histogram(input_f_file,duration):
    tonic_hist = 12*[0]
    # ['time','keynr','label'] -> [time:float, keynr:in(range(0,12))]
    data = csv_map_columns(input_f_file,3,[lambda r:float(r[0]), lambda r:int(r[1])-1])
    
    # build duration weighted histogram
    for idx in range(1,len(data[0]) ):
        tonic_hist[data[1][idx-1]] += data[0][idx] - data[0][idx-1]
        
    # add last tonic if duration is given
    if duration>0:
        tonic_hist[data[1][-1]] += duration - data[0][-1]
    
    return tonic_hist
    
