%%  Dictionary Learning for Automatic Music Transcription - KSVD residual 
%%  error test
%   
%   *WARNING!* You should have SPAMS in your search path in order for this
%   script to work.Due to licensing issues SPAMS can not be automatically 
%   provided in SMALLbox (http://www.di.ens.fr/willow/SPAMS/downloads.html).
%
%   This file contains an example of how SMALLbox can be used to test diferent
%   dictionary learning techniques in Automatic Music Transcription problem.
%   It calls generateAMT_Learning_Problem that will let you to choose midi,
%   wave or mat file to be transcribe. If file is midi it will be first
%   converted to wave and original midi file will be used for comparison with
%   results of dictionary learning and reconstruction.
%   The function will generarte the Problem structure that is used to learn
%   Problem.p notes spectrograms from training set Problem.b using
%   dictionary learning technique defined in DL structure.
%

%
%   Centre for Digital Music, Queen Mary, University of London.
%   This file copyright 2010 Ivan Damnjanovic.
%
%   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.  See the file
%   COPYING included with this distribution for more information.
%%

clear;


% Defining Automatic Transcription of Piano tune as Dictionary Learning
% Problem

SMALL.Problem = generateAMTProblem();
TPmax=0;
for i=1:5
    %%
    %   Use KSVD Dictionary Learning Algorithm to Learn 88 notes (defined in
    %   SMALL.Problem.p) using sparsity constrain only
    
    %   Initialising Dictionary structure
    %   Setting Dictionary structure fields (toolbox, name, param, D and time)
    %   to zero values
    
    SMALL.DL(i)=SMALL_init_DL(i);
    
    % Defining the parameters needed for dictionary learning
    
    SMALL.DL(i).toolbox = 'KSVD';
    SMALL.DL(i).name = 'ksvd';
    
    %   Defining the parameters for KSVD
    %   In this example we are learning 88 atoms in 100 iterations, so that
    %   every frame in the training set can be represented with maximum 10
    %   dictionary elements. However, our aim here is to show how individual
    %   parameters can be ested in the AMT problem. We test five different
    %   values for residual error (Edata) in KSVD algorithm.
    %   Type help ksvd in MATLAB prompt for more options.
    
    Edata(i)=8+i*2;
    SMALL.DL(i).param=struct(...
        'Edata', Edata(i),...
        'dictsize', SMALL.Problem.p,...
        'iternum', 100,...
        'maxatoms', 10);
    
    % Learn the dictionary
    
    SMALL.DL(i) = SMALL_learn(SMALL.Problem, SMALL.DL(i));
    
    %   Set SMALL.Problem.A dictionary and reconstruction function
    %   (backward compatiblity with SPARCO: solver structure communicate
    %   only with Problem structure, ie no direct communication between DL and
    %   solver structures)
    
    SMALL.Problem.A = SMALL.DL(i).D;
    SMALL.Problem.reconstruct = @(x) AMT_reconstruct(x, SMALL.Problem);
    
    %%
    %   Initialising solver structure
    %   Setting solver structure fields (toolbox, name, param, solution,
    %   reconstructed and time) to zero values
    %   As an example, SPAMS (Julien Mairal 2009) implementation of LARS
    %   algorithm is used for representation of training set in the learned
    %   dictionary.
    
    SMALL.solver(1)=SMALL_init_solver;
    
    % Defining the parameters needed for sparse representation
    
    SMALL.solver(1).toolbox='SPAMS';
    SMALL.solver(1).name='mexLasso';
    SMALL.solver(1).param=struct('lambda', 2, 'pos', 1, 'mode', 2);
    
    %Represent Training set in the learned dictionary
    
    SMALL.solver(1)=SMALL_solve(SMALL.Problem, SMALL.solver(1));
    
    %%
    %   Analysis of the result of automatic music transcription. If groundtruth
    %   exists, we can compare transcribed notes and original and get usual
    %   True Positives, False Positives and False Negatives measures.
    
    AMT_res(i) = AMT_analysis(SMALL.Problem, SMALL.solver(1));
    
    if AMT_res(i).TP>TPmax
        TPmax=AMT_res(i).TP;
        BLmidi=SMALL.solver(1).reconstructed.midi;
        max=i;
    end
    
end %end of for loop

%%
% Plot results and save midi files

figAMTbest=SMALL_AMT_plot(SMALL, AMT_res(max));

resFig=figure('Name', 'Automatic Music Transcription KSVD Error TEST');

subplot (3,1,1); plot(Edata(:), [AMT_res(:).TP], 'ro-');
title('True Positives vs Edata');

subplot (3,1,2); plot(Edata(:), [AMT_res(:).FN], 'ro-');
title('False Negatives vs Edata');

subplot (3,1,3); plot(Edata(:), [AMT_res(:).FP], 'ro-');
title('False Positives vs Edata');

FS=filesep;
[pathstr1, name, ext, versn] = fileparts(which('SMALLboxSetup.m'));
cd([pathstr1,FS,'results']);
[filename,pathname] = uiputfile({' *.mid;' },'Save midi');
if filename~=0 writemidi(BLmidi, [pathname,FS,filename]);end
[filename,pathname] = uiputfile({' *.fig;' },'Save figure TP/FN/FP vs lambda');
if filename~=0 saveas(resFig, [pathname,FS,filename]);end

[filename,pathname] = uiputfile({' *.fig;' },'Save BEST AMT figure');
if filename~=0 saveas(figAMTbest, [pathname,FS,filename]);end

