Mercurial > hg > smallbox
changeset 144:19e0af570914 release_1.5
Merge from branch "ivand_dev"
author | Ivan <ivan.damnjanovic@eecs.qmul.ac.uk> |
---|---|
date | Tue, 26 Jul 2011 15:14:15 +0100 |
parents | 8d866d96f006 (current diff) 18700ceb895f (diff) |
children | 65fc57f3903c 30872eb3d160 |
files | SMALLboxSetup.m |
diffstat | 97 files changed, 7685 insertions(+), 12 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Problems/AudioDeclipping_reconstruct.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,57 @@ +function reconstructed=AudioDeclipping_reconstruct(y, Problem, SparseDict) +%% Audio declipping Problem reconstruction function +% +% This reconstruction function is using sparse representation y +% in dictionary Problem.A to reconstruct declipped audio. +% +% [1] I. Damnjanovic, M. E. P. Davies, and M. P. Plumbley "SMALLbox - an +% evaluation framework for sparse representations and dictionary +% learning algorithms," V. Vigneron et al. (Eds.): LVA/ICA 2010, +% Springer-Verlag, Berlin, Germany, LNCS 6365, pp. 418-425 +% [2] A. Adler, V. Emiya, M. G. Jafari, M. Elad, R. Gribonval, and M. D. +% Plumbley, “Audio Inpainting,” submitted to IEEE Trans. Audio, Speech, +% and Lang. Proc., 2011, http://hal.inria.fr/inria-00577079/en/. + +% +% Centre for Digital Music, Queen Mary, University of London. +% This file copyright 2009 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. +%% + +windowSize = Problem.windowSize; +overlap = Problem.overlap; +ws = Problem.ws(windowSize); +wa = Problem.wa(windowSize); +A = Problem.B; + +orig = Problem.original; +clipped = Problem.clipped; +clipMask = Problem.clipMask; + +% reconstruct audio frames + +xFrames = diag(ws)*(A*y); +wNormFrames = (ws.*wa)'*ones(1,size(xFrames,2)); + +% overlap and add + +rec = col2imstep(xFrames, size(clipped), [windowSize 1], [windowSize*overlap 1]); +wNorm = col2imstep(wNormFrames, size(clipped), [windowSize 1], [windowSize*overlap 1]); +wNorm(find(wNorm==0)) = 1; +recN = rec./wNorm; + +% change only clipped samples + +recSignal = orig.*double(~clipMask) + recN.*double(clipMask); + +%% output structure image+psnr %% +reconstructed.audioAllSamples = recN; +reconstructed.audioOnlyClipped = recSignal; +[reconstructed.snrAll , reconstructed.snrMiss] = SNRInpaintingPerformance(orig, clipped, recSignal, clipMask, 1); + +end \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Problems/generateAudioDeclippingProblem.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,112 @@ +function data = generateAudioDeclippingProblem(soundfile, clippingLevel, windowSize, overlap, wa, ws, wd, Dict_fun, redundancyFactor) +%% Generate Audio Declipping Problem +% +% generateAudioDeclippingProblem is part of the SMALLbox [1] and generates +% Audio declipping is a problem proposed in Audio Inpaining Toolbox and +% in [2]. +% +% [1] I. Damnjanovic, M. E. P. Davies, and M. P. Plumbley "SMALLbox - an +% evaluation framework for sparse representations and dictionary +% learning algorithms," V. Vigneron et al. (Eds.): LVA/ICA 2010, +% Springer-Verlag, Berlin, Germany, LNCS 6365, pp. 418-425 +% [2] A. Adler, V. Emiya, M. G. Jafari, M. Elad, R. Gribonval, and M. D. +% Plumbley, “Audio Inpainting,” submitted to IEEE Trans. Audio, Speech, +% and Lang. Proc., 2011, http://hal.inria.fr/inria-00577079/en/. + + +% Centre for Digital Music, Queen Mary, University of London. +% This file copyright 2011 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. +% +%% +FS=filesep; +TMPpath=pwd; + +if ~ exist( 'soundfile', 'var' ) || isempty(soundfile) + %ask for file name + [pathstr1, name, ext, versn] = fileparts(which('SMALLboxSetup.m')); + cd([pathstr1,FS,'data',FS,'audio']); + [filename,pathname] = uigetfile({'*.mat; *.mid; *.wav'},'Select a file to transcribe'); + [pathstr, name, ext, versn] = fileparts(filename); + data.name=name; + + if strcmp(ext,'.mid') + midi=readmidi(filename); +% data.notesOriginal=midiInfo(midi); + y=midi2audio(midi); + wavwrite(y, 44100, 16, 'temp.wav'); + [x.signal, x.fs, x.nbits]=wavread('temp.wav'); + delete('temp.wav'); + elseif strcmp(ext,'.wav') +% cd([pathstr1,FS, 'data', FS, 'audio', FS, 'midi']); +% filename1=[name, '.mid']; +% if exist(filename1, 'file') +% midi=readmidi(filename1); +% data.notesOriginal=midiInfo(midi); +% end + cd([pathstr1,FS, 'data', FS, 'audio', FS, 'wav']); + [x.signal, x.fs, x.nbits]=wavread(filename); + else +% cd([pathstr1,FS, 'data', FS, 'audio', FS, 'midi']); +% filename1=[name, '.mid']; +% if exist(filename1, 'file') +% midi=readmidi(filename1); +% data.notesOriginal=midiInfo(midi); +% end + cd([pathstr1,FS, 'data', FS, 'audio', FS, 'mat']); + x=load([pathname,filename]); + end +else + [x.signal, x.fs, x.nbits]=wavread(soundfile); + [pathstr, name, ext, versn] = fileparts(soundfile); + data.name=name; +end + +if ~ exist( 'clippingLevel', 'var' ) || isempty(clippingLevel), clippingLevel = 0.6; end +if ~ exist( 'windowSize', 'var' ) || isempty(windowSize), windowSize = 256; end +if ~ exist( 'overlap', 'var' ) || isempty(overlap), overlap = 0.5; end +if ~ exist( 'wa', 'var' ) || isempty(wa), wa = @wRect; end % Analysis window +if ~ exist( 'ws', 'var' ) || isempty(ws), ws = @wSine; end % Synthesis window +if ~ exist( 'wd', 'var' ) || isempty(wd), wd = @wRect; end % Weighting window for dictionary atoms + +%% preparing signal + +[problemData, solutionData] = generateDeclippingProblem(x.signal,clippingLevel); + +x_clip = im2colstep(problemData.x,[windowSize 1],[overlap*windowSize 1]); +x_clip= diag(wa(windowSize)) * x_clip; +blkMask=im2colstep(double(~problemData.IMiss),[windowSize 1],[overlap*windowSize 1]); + +%% Building dictionary +if ~exist( 'redundancyFactor', 'var' ) || isempty(redundancyFactor), redundancyFactor = 2; end % Weighting window for dictionary atoms +if exist('Dict_fun', 'var')&&~isempty(Dict_fun) + param=struct('N', windowSize, 'redundancyFactor', redundancyFactor, 'wd', wd); + data.B = Dict_fun(param); +end + +data.b = x_clip; +data.M = blkMask; +data.original = solutionData.xClean; +data.clipped = problemData.x; +data.clipMask = problemData.IMiss; +data.clippingLevel = clippingLevel; +data.windowSize = windowSize; +data.overlap = overlap; +data.ws = ws; +data.wa = wa; +data.wd = wd; + +data.fs = x.fs; +data.nbits = x.nbits; + +[data.m, data.n] = size(x_clip); +data.p = windowSize*redundancyFactor; %number of dictionary elements + +cd(TMPpath); + +end
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/shortTest/license.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,3 @@ +License: these files are made available under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 license (http://creativecommons.org/licenses/by-nc-sa/2.0/). +Authors: Hiroshi Sawada, Shoko Araki and Emmanuel Vincent. +Downloaded from: http://sisec2008.wiki.irisa.fr/.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music02_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,5 @@ +Original name: 71296__Bopping__Acoustic_bass_test_2.wav +Author: Bopping +License: Creative Commons Sampling Plus 1.0 License (http://creativecommons.org/licenses/sampling+/1.0/) +Downloaded from: http://www.freesound.org/samplesViewSingle.php?id=71296 +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music03_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,10 @@ +LICENSE + +2007 - Licensed under Creative Commons Attribution Noncommercial (3.0) +Please read: http://creativecommons.org/licenses/by-nc/3.0/ + + +CREDITS + +"Que Pena / Tanto Faz" by Tamy, Curvemusic +Downloaded and modified from: http://ccmixter.org/curve/view/contest/sources
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music04_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,10 @@ +LICENSE + +2007 - Licensed under Creative Commons Attribution Noncommercial (3.0) +Please read: http://creativecommons.org/licenses/by-nc/3.0/ + + +CREDITS + +"Que Pena / Tanto Faz" by Tamy, Curvemusic +Downloaded and modified from: http://ccmixter.org/curve/view/contest/sources
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music06_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,21 @@ +LICENSE + +License: Creative Commons Attribution-Noncommercial-ShareAlike 3.0 +Please read: http://creativecommons.org/licenses/by-nc/3.0/ + + +CREDITS + +The Ultimate NZ Tour +URL: http://newzealandeducated.com/contest/ultimate-nz-tour-i/ + +Remix is done by Michel Desnoues from Telecom ParisTech + + +DESCRIPTION + +This snip is extracted from the corresponding full-length mix available in dev2_full_mix.zip + +Snip beginning : 43 seconds (1896300 samples) +Snip end : 61 seconds (2690100 samples) +Snip length : 18 seconds (793801 samples)
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music07_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,3 @@ +License: these files are made available under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 license (http://creativecommons.org/licenses/by-nc-sa/2.0/). +Authors: Another Dreamer and Alex Q. +Downloaded from: http://sisec2008.wiki.irisa.fr/.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music08_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,38 @@ +LICENSE + +All files in this archive are copyrighted material from Bearlin (Ignasi Calvo and Jordi Rabascall). However, the use of these audio files for scientific research purposes is granted if credit is given to them as follows: +<< +Artist: Bearlin (Ignasi Calvo & Jordi Rabascall) +Song: Roads +Producer: Sergi Vila & Bearlin +Website: www.bearlin.net +>> + +Using these audio files for any purposes that are not scientific research is explicitly prohibited. + + +CREDITS + +Music & lyrics +Ignasi Calvo + +Production +Sergi Vila & BEARLIN (Ignasi Calvo & Jordi Rabascall) + +Mixing +Sergi Vila at Garatge Produccions + +Personnel +Vocals: Jordi Rabascall +Acoustic piano, synthesizers and programming: Ignasi Calvo +Guitars: Xavier Fernndez de Mera +Acoustic drums: Carles Domingo Triquell +Acoustic bass: Pepe Curioni + +Recording +Acoustic piano and acoustic guitar: 44.1 Recording Studio (Girona), by Toni Paris. +Acoustic drums, percussion and acoustic bass: Palatzi estudis (Barcelona), by David Palatzi. +Synthesizers, guitars, programming and effects: BadQstudios and Garatge Produccions (Barcelona). + +Mastering +Music Lan Recording Studios (Girona), by Jordi Sol.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music09_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,12 @@ +LICENSE + +License: Creative Commons Attribution-NonCommercial 2.5 +Please read: http://creativecommons.org/licenses/by-nc/2.5/ + + +CREDITS + +"Remember the name" by Fort Minor, Warner Bros. Records and Machine Shop Recordings +URL: http://www.myspace.com/fortminor + +Remix is done by Michel Desnoues from Telecom ParisTech
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music10_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,2 @@ +License and authors: these files are licensed for research use only by their authors (see list of authors below). The authors of the dataset are Mads Dyrholm and Lucas Parra. The music used for recordings was taken from "Germ Germ" by Das Böse Ding and has kindly been approved for public presentation by Jan Klare of Das Böse Ding in the name of research. +Download from: http://sisec2008.wiki.irisa.fr/ \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music11_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,3 @@ +License: These files are made available under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 license (http://creativecommons.org/licenses/by-nc-sa/2.0/). +Authors: Shannon Hurley, Nine Inch Nails, AlexQ (Alexander Lozupone), Mokamed, Carl Leth and Jim's Big Ego for music source signals and Hiroshi Sawada for mixture signals. +Downloaded from: http://sisec.wiki.irisa.fr/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testMusic16kHz/music12_16kHz.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,3 @@ +License: These files are made available under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 license (http://creativecommons.org/licenses/by-nc-sa/2.0/). +Authors: Shannon Hurley, Nine Inch Nails, AlexQ (Alexander Lozupone), Mokamed, Carl Leth and Jim's Big Ego for music source signals and Hiroshi Sawada for mixture signals. +Downloaded from: http://sisec.wiki.irisa.fr/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testSpeech16kHz/license.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,3 @@ +License: these files are made available under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 license (http://creativecommons.org/licenses/by-nc-sa/2.0/). +Authors: Hiroshi Sawada, Shoko Araki and Emmanuel Vincent. +Downloaded from: http://sisec2008.wiki.irisa.fr/.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/data/audio/wav/testSpeech8kHz_from16kHz/license.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,3 @@ +License: these files are made available under the terms of the Creative Commons Attribution-NonCommercial-ShareAlike 2.0 license (http://creativecommons.org/licenses/by-nc-sa/2.0/). +Authors: Hiroshi Sawada, Shoko Araki and Emmanuel Vincent. +Downloaded from: http://sisec2008.wiki.irisa.fr/.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/AudioInpainting/Audio_Declipping_Example.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,148 @@ +%% Audio Declipping Example +% +% Audio declipping is a problem proposed in Audio Inpaining Toolbox and +% in [2]. This is an example of solving the problem with fast omp using +% Gabor dictionary and ompGabor implemented in SMALLbox [1]. +% +% [1] I. Damnjanovic, M. E. P. Davies, and M. P. Plumbley "SMALLbox - an +% evaluation framework for sparse representations and dictionary +% learning algorithms," V. Vigneron et al. (Eds.): LVA/ICA 2010, +% Springer-Verlag, Berlin, Germany, LNCS 6365, pp. 418-425 +% [2] A. Adler, V. Emiya, M. G. Jafari, M. Elad, R. Gribonval, and M. D. +% Plumbley, “Audio Inpainting,” submitted to IEEE Trans. Audio, Speech, +% and Lang. Proc., 2011, http://hal.inria.fr/inria-00577079/en/. + +% +% Centre for Digital Music, Queen Mary, University of London. +% This file copyright 2011 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 all; +% Defining the solvers to test in Audio declipping scenario + +% First solver omp2 - DCT+DST dictionary with no additional constraints + +SMALL.solver(1) = SMALL_init_solver('ompbox', 'omp2', '', 0); +SMALL.solver(1).add_constraints = 0; + +% Second solver omp2 - DCT+DST dictionary with additional constraints + +SMALL.solver(2) = SMALL_init_solver('ompbox', 'omp2', '', 0); +SMALL.solver(2).add_constraints = 1; + +% Third solver omp2 - Gabor dictionary with no additional constraints + +SMALL.solver(3) = SMALL_init_solver('ompbox', 'omp2Gabor', '', 0); +SMALL.solver(3).add_constraints = 0; + +% Fourth solver omp2- Gabor dictionary with no additional constraints + +SMALL.solver(4) = SMALL_init_solver('ompbox', 'omp2Gabor', '', 0); +SMALL.solver(4).add_constraints = 1; + +% Defining the Problem structure + +SMALL.Problem = generateAudioDeclippingProblem('male01_8kHz.wav', 0.6, 256, 0.5, @wRect, @wSine, @wRect, @Gabor_Dictionary, 2); + +for idxSolver = 1:4 + + fprintf('\nStarting Audio Declipping of %s... \n', SMALL.Problem.name); + fprintf('\nClipping level %s... \n', SMALL.Problem.clippingLevel); + + start=cputime; + tStart=tic; + + error2=0.001^2; + coeffFrames = zeros(SMALL.Problem.p, SMALL.Problem.n); + + + + for i = 1:SMALL.Problem.n + + idx = find(SMALL.Problem.M(:,i)); + if size(idx,1)==SMALL.Problem.m + continue + end + Dict = SMALL.Problem.B(idx,:); + wDict = 1./sqrt(diag(Dict'*Dict)); + + SMALL.Problem.A = Dict*diag(wDict); + + SMALL.Problem.b1 = SMALL.Problem.b(idx,i); + + + + % set solver parameters + + SMALL.solver(idxSolver).param=struct(... + 'epsilon', error2*size(idx,1),... + 'maxatoms', 128, ... + 'profile', 'off'); + + % Find solution + + SMALL.solver(idxSolver)=SMALL_solve(SMALL.Problem, SMALL.solver(idxSolver)); + + % Refine solution with additional constraints for declipping scenario + + if (SMALL.solver(idxSolver).add_constraints) + SMALL.solver(idxSolver)=CVX_add_const_Audio_declipping(... + SMALL.Problem, SMALL.solver(idxSolver), i); + end + + %% + coeffFrames(:,i) = wDict .* SMALL.solver(idxSolver).solution; + + + end + + %% Set reconstruction function + + SMALL.Problem.reconstruct=@(x) AudioDeclipping_reconstruct(x, SMALL.Problem); + reconstructed=SMALL.Problem.reconstruct(coeffFrames); + SMALL.Problem = rmfield(SMALL.Problem, 'reconstruct'); + tElapsed=toc(tStart); + + SMALL.solver(idxSolver).time = cputime - start; + fprintf('Solver %s finished task in %2f seconds (cpu time). \n', ... + SMALL.solver(idxSolver).name, SMALL.solver(idxSolver).time); + fprintf('Solver %s finished task in %2f seconds (tic-toc time). \n', ... + SMALL.solver(idxSolver).name, tElapsed); + + + + %% Plot results + + xClipped = SMALL.Problem.clipped; + xClean = SMALL.Problem.original; + xEst1 = reconstructed.audioAllSamples; + xEst2 = reconstructed.audioOnlyClipped; + fs = SMALL.Problem.fs; + + figure + hold on + plot(xClipped,'r') + plot(xClean) + plot(xEst2,'--g') + plot([1;length(xClipped)],[1;1]*[-1,1]*max(abs(xClipped)),':r') + legend('Clipped','True solution','Estimate') +end + +% % Normalized and save sounds +% normX = 1.1*max(abs([xEst1(:);xEst2(:);xClean(:)])); +% L = min([length(xEst2),length(xEst1),length(xClean),length(xEst1),length(xClipped)]); +% xEst1 = xEst1(1:L)/normX; +% xEst2 = xEst2(1:L)/normX; +% xClipped = xClipped(1:L)/normX; +% xClean = xClean(1:L)/normX; +% wavwrite(xEst1,fs,[expParam.destDir 'xEst1.wav']); +% wavwrite(xEst2,fs,[expParam.destDir 'xEst2.wav']); +% wavwrite(xClipped,fs,[expParam.destDir 'xClipped.wav']); +% wavwrite(xClean,fs,[expParam.destDir 'xClean.wav']);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/CVX_add_const_Audio_declipping.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,85 @@ +function solver=CVX_add_const_Audio_declipping(Problem, solver, idxFrame) + +%% CVX additional constrains + % Clipping level: take the analysis window into account + % clipping level detection + + signal = Problem.b1; + signalFull = Problem.b(:,idxFrame); + Dict = Problem.A; + DictFull = Problem.B; + Clipped = ~Problem.M(:,idxFrame); + W=1./sqrt(diag(Dict'*Dict)); + + idxCoeff = find(solver.solution~=0); + + solution = solver.solution; + + wa = Problem.wa(Problem.windowSize); % analysis window + + + clippingLevelEst = max(abs(signal./wa(~Clipped)')); + + idxPos = find(signalFull>=0 & Clipped); + idxNeg = find(signalFull<0 & Clipped); + + DictPos=DictFull(idxPos,:); + DictNeg=DictFull(idxNeg,:); + + + wa_pos = wa(idxPos); + wa_neg = wa(idxNeg); + b_ineq_pos = wa_pos(:)*clippingLevelEst; + b_ineq_neg = -wa_neg(:)*clippingLevelEst; + if isfield(Problem,'Upper_Limit') && ~isempty(Problem.Upper_Limit) + b_ineq_pos_upper_limit = wa_pos(:)*Problem.Upper_Limit*clippingLevelEst; + b_ineq_neg_upper_limit = -wa_neg(:)*Problem.Upper_Limit*clippingLevelEst; + else + b_ineq_pos_upper_limit = Inf; + b_ineq_neg_upper_limit = -Inf; + end + + + j = length(idxCoeff); + + if isinf(b_ineq_pos_upper_limit) + %% CVX code + cvx_begin + cvx_quiet(true) + variable solution(j) + minimize(norm(Dict(:,idxCoeff)*solution-signal)) + subject to + DictPos(:,idxCoeff)*(W(idxCoeff).*solution) >= b_ineq_pos + DictNeg(:,idxCoeff)*(W(idxCoeff).*solution) <= b_ineq_neg + cvx_end + if cvx_optval>1e3 + cvx_begin + cvx_quiet(true) + variable solution(j) + minimize(norm(Dict(:,idxCoeff)*solution-xObs)) + cvx_end + end + else + %% CVX code + cvx_begin + cvx_quiet(true) + variable solution(j) + minimize(norm(Dict(:,idxCoeff)*solution-signal)) + subject to + DictPos(:,idxCoeff)*(W(idxCoeff).*solution) >= b_ineq_pos + DictNeg(:,idxCoeff)*(W(idxCoeff).*solution) <= b_ineq_neg + DictPos(:,idxCoeff)*(W(idxCoeff).*solution) <= b_ineq_pos_upper_limit + DictNeg(:,idxCoeff)*(W(idxCoeff).*solution) >= b_ineq_neg_upper_limit + cvx_end + if cvx_optval>1e3 + cvx_begin + cvx_quiet(true) + variable solution(j) + minimize(norm(Dict(:,idxCoeff)*solution-xObs)) + cvx_end + end + end + + solver.solution(idxCoeff) = solution; + + \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/make.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,41 @@ +function make +%MAKE Build the OMPBox package. +% MAKE compiles all OMPBox MEX functions, using Matlab's default MEX +% compiler. If the MEX compiler has not been set-up before, please run +% +% mex -setup +% +% before using this MAKE file. + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% August 2009 + + +% detect platform + +compstr = computer; +is64bit = strcmp(compstr(end-1:end),'64'); + + +% compilation parameters + +compile_params = cell(0); +if (is64bit) + compile_params{1} = '-largeArrayDims'; +end + + +% Compile files % + +ompsources = {'mexutils.c','ompcoreGabor.c','omputils.c','myblas.c','ompprof.c'}; + +disp('Compiling ompmex...'); +mex('ompmexGabor.c', ompsources{:},compile_params{:}); + +disp('Compiling omp2mex...'); +mex('omp2mexGabor.c',ompsources{:},compile_params{:}); +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/mexutils.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,79 @@ +/************************************************************************** + * + * File name: mexutils.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 15.8.2009 + * + *************************************************************************/ + +#include "mexutils.h" +#include <math.h> + + + +/* verify that the mxArray contains a double matrix */ + +void checkmatrix(const mxArray *param, char *fname, char *pname) +{ + char errmsg[100]; + sprintf(errmsg, "%.15s requires that %.25s be a double matrix.", fname, pname); + if (!mxIsDouble(param) || mxIsComplex(param) || mxGetNumberOfDimensions(param)>2) { + mexErrMsgTxt(errmsg); + } +} + + +/* verify that the mxArray contains a 1-D double vector */ + +void checkvector(const mxArray *param, char *fname, char *pname) +{ + char errmsg[100]; + sprintf(errmsg, "%.15s requires that %.25s be a double vector.", fname, pname); + if (!mxIsDouble(param) || mxIsComplex(param) || mxGetNumberOfDimensions(param)>2 || (mxGetM(param)!=1 && mxGetN(param)!=1)) { + mexErrMsgTxt(errmsg); + } +} + + +/* verify that the mxArray contains a double scalar */ + +void checkscalar(const mxArray *param, char *fname, char *pname) +{ + char errmsg[100]; + sprintf(errmsg, "%.15s requires that %.25s be a double scalar.", fname, pname); + if (!mxIsDouble(param) || mxIsComplex(param) || mxGetNumberOfDimensions(param)>2 || + mxGetM(param)!=1 || mxGetN(param)!=1) + { + mexErrMsgTxt(errmsg); + } +} + + +/* verify that the mxArray contains a sparse matrix */ + +void checksparse(const mxArray *param, char *fname, char *pname) +{ + char errmsg[100]; + sprintf(errmsg, "%.15s requires that %.25s be sparse.", fname, pname); + if (!mxIsSparse(param)) { + mexErrMsgTxt(errmsg); + } +} + + +/* verify that the mxArray contains a 1-dimensional cell array */ + +void checkcell_1d(const mxArray *param, char *fname, char *pname) +{ + char errmsg[100]; + sprintf(errmsg, "%.15s requires that %.25s be a 1-D cell array.", fname, pname); + if (!mxIsCell(param) || mxGetNumberOfDimensions(param)>2 || (mxGetM(param)!=1 && mxGetN(param)!=1)) { + mexErrMsgTxt(errmsg); + } +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/mexutils.h Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,103 @@ +/************************************************************************** + * + * File name: mexutils.h + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + * Utility functions for MEX files. + * + *************************************************************************/ + + +#ifndef __MEX_UTILS_H__ +#define __MEX_UTILS_H__ + +#include "mex.h" + + + +/************************************************************************** + * Function checkmatrix: + * + * Verify that the specified mxArray is real, of type double, and has + * no more than two dimensions. If not, an error message is printed + * and the mex file terminates. + * + * Parameters: + * param - the mxArray to be checked + * fname - the name of the function where the error occured (15 characters or less) + * pname - the name of the parameter (25 characters or less) + * + **************************************************************************/ +void checkmatrix(const mxArray *param, char *fname, char *pname); + + +/************************************************************************** + * Function checkvector: + * + * Verify that the specified mxArray is 1-D, real, and of type double. The + * vector may be a column or row vector. Otherwise, an error message is + * printed and the mex file terminates. + * + * Parameters: + * param - the mxArray to be checked + * fname - the name of the function where the error occured (15 characters or less) + * pname - the name of the parameter (25 characters or less) + * + **************************************************************************/ +void checkvector(const mxArray *param, char *fname, char *pname); + + +/************************************************************************** + * Function checkscalar: + * + * Verify that the specified mxArray represents a real double scalar value. + * If not, an error message is printed and the mex file terminates. + * + * Parameters: + * param - the mxArray to be checked + * fname - the name of the function where the error occured (15 characters or less) + * pname - the name of the parameter (25 characters or less) + * + **************************************************************************/ +void checkscalar(const mxArray *param, char *fname, char *pname); + + +/************************************************************************** + * Function checksparse: + * + * Verify that the specified mxArray contains a sparse matrix. If not, + * an error message is printed and the mex file terminates. + * + * Parameters: + * param - the mxArray to be checked + * fname - the name of the function where the error occured (15 characters or less) + * pname - the name of the parameter (25 characters or less) + * + **************************************************************************/ +void checksparse(const mxArray *param, char *fname, char *pname); + + +/************************************************************************** + * Function checkcell_1d: + * + * Verify that the specified mxArray is a 1-D cell array. The cell array + * may be arranged as either a column or a row. If not, an error message + * is printed and the mex file terminates. + * + * Parameters: + * param - the mxArray to be checked + * fname - the name of the function where the error occured (15 characters or less) + * pname - the name of the parameter (25 characters or less) + * + **************************************************************************/ +void checkcell_1d(const mxArray *param, char *fname, char *pname); + + +#endif +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/myblas.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,673 @@ +/************************************************************************** + * + * File name: myblas.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Version: 1.1 + * Last updated: 13.8.2009 + * + *************************************************************************/ + + +#include "myblas.h" +#include <ctype.h> + + +/* find maximum of absolute values */ + +mwIndex maxabs(double c[], mwSize m) +{ + mwIndex maxid=0, k; + double absval, maxval = SQR(*c); /* use square which is quicker than absolute value */ + + for (k=1; k<m; ++k) { + absval = SQR(c[k]); + if (absval > maxval) { + maxval = absval; + maxid = k; + } + } + return maxid; +} + + +/* compute y := alpha*x + y */ + +void vec_sum(double alpha, double x[], double y[], mwSize n) +{ + mwIndex i; + + for (i=0; i<n; ++i) { + y[i] += alpha*x[i]; + } +} + +/* compute y := alpha*x .* y */ + +void vec_smult(double alpha, double x[], double y[], mwSize n) +{ + mwIndex i; + + for (i=0; i<n; ++i) { + y[i] *= alpha*x[i]; + } +} + +/* compute y := alpha*A*x */ + +void mat_vec(double alpha, double A[], double x[], double y[], mwSize n, mwSize m) +{ + mwIndex i, j, i_n; + double *Ax; + + Ax = mxCalloc(n,sizeof(double)); + + for (i=0; i<m; ++i) { + i_n = i*n; + for (j=0; j<n; ++j) { + Ax[j] += A[i_n+j] * x[i]; + } + } + + for (j=0; j<n; ++j) { + y[j] = alpha*Ax[j]; + } + + mxFree(Ax); +} + + +/* compute y := alpha*A'*x */ + +void matT_vec(double alpha, double A[], double x[], double y[], mwSize n, mwSize m) +{ + mwIndex i, j, n_i; + double sum0, sum1, sum2, sum3; + + for (j=0; j<m; ++j) { + y[j] = 0; + } + + /* use loop unrolling to accelerate computation */ + + for (i=0; i<m; ++i) { + n_i = n*i; + sum0 = sum1 = sum2 = sum3 = 0; + for (j=0; j+4<n; j+=4) { + sum0 += A[n_i+j]*x[j]; + sum1 += A[n_i+j+1]*x[j+1]; + sum2 += A[n_i+j+2]*x[j+2]; + sum3 += A[n_i+j+3]*x[j+3]; + } + y[i] += alpha * ((sum0 + sum1) + (sum2 + sum3)); + while (j<n) { + y[i] += alpha*A[n_i+j]*x[j]; + j++; + } + } +} + + +/* compute y := alpha*A*x */ + +void mat_sp_vec(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double x[], double y[], mwSize n, mwSize m) +{ + + mwIndex i, j, j1, j2; + + for (i=0; i<n; ++i) { + y[i] = 0; + } + + j2 = jc[0]; + for (i=0; i<m; ++i) { + j1 = j2; j2 = jc[i+1]; + for (j=j1; j<j2; ++j) { + y[ir[j]] += alpha * pr[j] * x[i]; + } + } + +} + + +/* compute y := alpha*A'*x */ + +void matT_sp_vec(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double x[], double y[], mwSize n, mwSize m) +{ + + mwIndex i, j, j1, j2; + + for (i=0; i<m; ++i) { + y[i] = 0; + } + + j2 = jc[0]; + for (i=0; i<m; ++i) { + j1 = j2; j2 = jc[i+1]; + for (j=j1; j<j2; ++j) { + y[i] += alpha * pr[j] * x[ir[j]]; + } + } + +} + + +/* compute y := alpha*A*x */ + +void mat_vec_sp(double alpha, double A[], double pr[], mwIndex ir[], mwIndex jc[], double y[], mwSize n, mwSize m) +{ + + mwIndex i, j, j_n, k, kend; + + for (i=0; i<n; ++i) { + y[i] = 0; + } + + kend = jc[1]; + if (kend==0) { /* x is empty */ + return; + } + + for (k=0; k<kend; ++k) { + j = ir[k]; + j_n = j*n; + for (i=0; i<n; ++i) { + y[i] += alpha * A[i+j_n] * pr[k]; + } + } + +} + + +/* compute y := alpha*A'*x */ + +void matT_vec_sp(double alpha, double A[], double pr[], mwIndex ir[], mwIndex jc[], double y[], mwSize n, mwSize m) +{ + + mwIndex i, j, j_n, k, kend; + + for (i=0; i<m; ++i) { + y[i] = 0; + } + + kend = jc[1]; + if (kend==0) { /* x is empty */ + return; + } + + for (j=0; j<m; ++j) { + j_n = j*n; + for (k=0; k<kend; ++k) { + i = ir[k]; + y[j] += alpha * A[i+j_n] * pr[k]; + } + } + +} + + +/* compute y := alpha*A*x */ + +void mat_sp_vec_sp(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double prx[], mwIndex irx[], mwIndex jcx[], double y[], mwSize n, mwSize m) +{ + + mwIndex i, j, k, kend, j1, j2; + + for (i=0; i<n; ++i) { + y[i] = 0; + } + + kend = jcx[1]; + if (kend==0) { /* x is empty */ + return; + } + + for (k=0; k<kend; ++k) { + i = irx[k]; + j1 = jc[i]; j2 = jc[i+1]; + for (j=j1; j<j2; ++j) { + y[ir[j]] += alpha * pr[j] * prx[k]; + } + } + +} + + +/* compute y := alpha*A'*x */ + +void matT_sp_vec_sp(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double prx[], mwIndex irx[], mwIndex jcx[], double y[], mwSize n, mwSize m) +{ + + mwIndex i, j, k, jend, kend, jadd, kadd, delta; + + for (i=0; i<m; ++i) { + y[i] = 0; + } + + kend = jcx[1]; + if (kend==0) { /* x is empty */ + return; + } + + for (i=0; i<m; ++i) { + j = jc[i]; + jend = jc[i+1]; + k = 0; + while (j<jend && k<kend) { + + delta = ir[j] - irx[k]; + + if (delta) { /* if indices differ - increment the smaller one */ + jadd = delta<0; + kadd = 1-jadd; + j += jadd; + k += kadd; + } + + else { /* indices are equal - add to result and increment both */ + y[i] += alpha * pr[j] * prx[k]; + j++; k++; + } + } + } + +} + + +/* matrix-matrix multiplication */ + +void mat_mat(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k) +{ + mwIndex i1, i2, i3, iX, iA, i2_n; + double b; + + for (i1=0; i1<n*k; i1++) { + X[i1] = 0; + } + + for (i2=0; i2<m; ++i2) { + i2_n = i2*n; + iX = 0; + for (i3=0; i3<k; ++i3) { + iA = i2_n; + b = B[i2+i3*m]; + for (i1=0; i1<n; ++i1) { + X[iX++] += A[iA++]*b; + } + } + } + + for (i1=0; i1<n*k; i1++) { + X[i1] *= alpha; + } +} + + +/* matrix-transpose-matrix multiplication */ + +void matT_mat(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k) +{ + mwIndex i1, i2, i3, iX, iA, i2_n; + double *x, sum0, sum1, sum2, sum3; + + for (i2=0; i2<m; ++i2) { + for (i3=0; i3<k; ++i3) { + sum0 = sum1 = sum2 = sum3 = 0; + for (i1=0; i1+4<n; i1+=4) { + sum0 += A[i1+0+i2*n]*B[i1+0+i3*n]; + sum1 += A[i1+1+i2*n]*B[i1+1+i3*n]; + sum2 += A[i1+2+i2*n]*B[i1+2+i3*n]; + sum3 += A[i1+3+i2*n]*B[i1+3+i3*n]; + } + X[i2+i3*m] = (sum0+sum1) + (sum2+sum3); + while(i1<n) { + X[i2+i3*m] += A[i1+i2*n]*B[i1+i3*n]; + i1++; + } + } + } + + for (i1=0; i1<m*k; i1++) { + X[i1] *= alpha; + } +} + + +/* tensor-matrix product */ + +void tens_mat(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k, mwSize l) +{ + mwIndex i1, i2, i3, i4, i2_n, nml; + double b; + + nml = n*m*l; + for (i1=0; i1<nml; ++i1) { + X[i1] = 0; + } + + for (i2=0; i2<m; ++i2) { + i2_n = i2*n; + for (i3=0; i3<k; ++i3) { + for (i4=0; i4<l; ++i4) { + b = B[i4+i3*l]; + for (i1=0; i1<n; ++i1) { + X[i1 + i2_n + i4*n*m] += A[i1 + i2_n + i3*n*m] * b; + } + } + } + } + + for (i1=0; i1<nml; ++i1) { + X[i1] *= alpha; + } +} + + +/* tensor-matrix-transpose product */ + +void tens_matT(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k, mwSize l) +{ + mwIndex i1, i2, i3, i4, i2_n, nml; + double b; + + nml = n*m*l; + for (i1=0; i1<nml; ++i1) { + X[i1] = 0; + } + + for (i2=0; i2<m; ++i2) { + i2_n = i2*n; + for (i4=0; i4<l; ++i4) { + for (i3=0; i3<k; ++i3) { + b = B[i3+i4*k]; + for (i1=0; i1<n; ++i1) { + X[i1 + i2_n + i4*n*m] += A[i1 + i2_n + i3*n*m] * b; + } + } + } + } + + for (i1=0; i1<nml; ++i1) { + X[i1] *= alpha; + } +} + + +/* dot product */ + +double dotprod(double a[], double b[], mwSize n) +{ + double sum = 0; + mwIndex i; + for (i=0; i<n; ++i) + sum += a[i]*b[i]; + return sum; +} + + +/* find maximum of vector */ + +mwIndex maxpos(double c[], mwSize m) +{ + mwIndex maxid=0, k; + double val, maxval = *c; + + for (k=1; k<m; ++k) { + val = c[k]; + if (val > maxval) { + maxval = val; + maxid = k; + } + } + return maxid; +} + + +/* solve L*x = b */ + +void backsubst_L(double L[], double b[], double x[], mwSize n, mwSize k) +{ + mwIndex i, j; + double rhs; + + for (i=0; i<k; ++i) { + rhs = b[i]; + for (j=0; j<i; ++j) { + rhs -= L[j*n+i]*x[j]; + } + x[i] = rhs/L[i*n+i]; + } +} + + +/* solve L'*x = b */ + +void backsubst_Lt(double L[], double b[], double x[], mwSize n, mwSize k) +{ + mwIndex i, j; + double rhs; + + for (i=k; i>=1; --i) { + rhs = b[i-1]; + for (j=i; j<k; ++j) { + rhs -= L[(i-1)*n+j]*x[j]; + } + x[i-1] = rhs/L[(i-1)*n+i-1]; + } +} + + +/* solve U*x = b */ + +void backsubst_U(double U[], double b[], double x[], mwSize n, mwSize k) +{ + mwIndex i, j; + double rhs; + + for (i=k; i>=1; --i) { + rhs = b[i-1]; + for (j=i; j<k; ++j) { + rhs -= U[j*n+i-1]*x[j]; + } + x[i-1] = rhs/U[(i-1)*n+i-1]; + } +} + + +/* solve U'*x = b */ + +void backsubst_Ut(double U[], double b[], double x[], mwSize n, mwSize k) +{ + mwIndex i, j; + double rhs; + + for (i=0; i<k; ++i) { + rhs = b[i]; + for (j=0; j<i; ++j) { + rhs -= U[i*n+j]*x[j]; + } + x[i] = rhs/U[i*n+i]; + } +} + + +/* back substitution solver */ + +void backsubst(char ul, double A[], double b[], double x[], mwSize n, mwSize k) +{ + if (tolower(ul) == 'u') { + backsubst_U(A, b, x, n, k); + } + else if (tolower(ul) == 'l') { + backsubst_L(A, b, x, n, k); + } + else { + mexErrMsgTxt("Invalid triangular matrix type: must be ''U'' or ''L''"); + } +} + + +/* solve equation set using cholesky decomposition */ + +void cholsolve(char ul, double A[], double b[], double x[], mwSize n, mwSize k) +{ + double *tmp; + + tmp = mxMalloc(k*sizeof(double)); + + if (tolower(ul) == 'l') { + backsubst_L(A, b, tmp, n, k); + backsubst_Lt(A, tmp, x, n, k); + } + else if (tolower(ul) == 'u') { + backsubst_Ut(A, b, tmp, n, k); + backsubst_U(A, tmp, x, n, k); + } + else { + mexErrMsgTxt("Invalid triangular matrix type: must be either ''U'' or ''L''"); + } + + mxFree(tmp); +} + + +/* perform a permutation assignment y := x(ind(1:k)) */ + +void vec_assign(double y[], double x[], mwIndex ind[], mwSize k) +{ + mwIndex i; + + for (i=0; i<k; ++i) + y[i] = x[ind[i]]; +} + + +/* matrix transpose */ + +void transpose(double X[], double Y[], mwSize n, mwSize m) +{ + mwIndex i, j, i_m, j_n; + + if (n<m) { + for (j=0; j<m; ++j) { + j_n = j*n; + for (i=0; i<n; ++i) { + Y[j+i*m] = X[i+j_n]; + } + } + } + else { + for (i=0; i<n; ++i) { + i_m = i*m; + for (j=0; j<m; ++j) { + Y[j+i_m] = X[i+j*n]; + } + } + } +} + + +/* print contents of matrix */ + +void printmat(double A[], int n, int m, char* matname) +{ + int i, j; + mexPrintf("\n%s = \n\n", matname); + + if (n*m==0) { + mexPrintf(" Empty matrix: %d-by-%d\n\n", n, m); + return; + } + + for (i=0; i<n; ++i) { + for (j=0; j<m; ++j) + mexPrintf(" %lf", A[j*n+i]); + mexPrintf("\n"); + } + mexPrintf("\n"); +} + + +/* print contents of sparse matrix */ + +void printspmat(mxArray *a, char* matname) +{ + mwIndex *aJc = mxGetJc(a); + mwIndex *aIr = mxGetIr(a); + double *aPr = mxGetPr(a); + + int i; + + mexPrintf("\n%s = \n\n", matname); + + for (i=0; i<aJc[1]; ++i) + printf(" (%d,1) = %lf\n", aIr[i]+1,aPr[i]); + + mexPrintf("\n"); +} + + + +/* matrix multiplication using Winograd's algorithm */ + +/* +void mat_mat2(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k) +{ + + mwIndex i1, i2, i3, iX, iA, i2_n; + double b, *AA, *BB; + + AA = mxCalloc(n,sizeof(double)); + BB = mxCalloc(k,sizeof(double)); + + for (i1=0; i1<n*k; i1++) { + X[i1] = 0; + } + + for (i1=0; i1<n; ++i1) { + for (i2=0; i2<m/2; ++i2) { + AA[i1] += A[i1+2*i2*n]*A[i1+(2*i2+1)*n]; + } + } + + for (i2=0; i2<k; ++i2) { + for (i1=0; i1<m/2; ++i1) { + BB[i2] += B[2*i1+i2*m]*B[2*i1+1+i2*m]; + } + } + + for (i2=0; i2<k; ++i2) { + for (i3=0; i3<m/2; ++i3) { + for (i1=0; i1<n; ++i1) { + X[i1+i2*n] += (A[i1+(2*i3)*n]+B[2*i3+1+i2*m])*(A[i1+(2*i3+1)*n]+B[2*i3+i2*m]); + } + } + } + + if (m%2) { + for (i2=0; i2<k; ++i2) { + for (i1=0; i1<n; ++i1) { + X[i1+i2*n] += A[i1+(m-1)*n]*B[m-1+i2*m]; + } + } + } + + for (i2=0; i2<k; ++i2) { + for (i1=0; i1<n; ++i1) { + X[i1+i2*n] -= (AA[i1] + BB[i2]); + X[i1+i2*n] *= alpha; + } + } + + mxFree(AA); + mxFree(BB); +} +*/ + + + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/myblas.h Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,511 @@ +/************************************************************************** + * + * File name: myblas.h + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Version: 1.1 + * Last updated: 17.8.2009 + * + * A collection of basic linear algebra functions, in the spirit of the + * BLAS/LAPACK libraries. + * + *************************************************************************/ + + + +#ifndef __MY_BLAS_H__ +#define __MY_BLAS_H__ + + +#include "mex.h" +#include <math.h> + + + +/************************************************************************** + * Squared value. + **************************************************************************/ +#define SQR(X) ((X)*(X)) + + + +/************************************************************************** + * Matrix-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A*x + * + * Parameters: + * A - matrix of size n X m + * x - vector of length m + * y - output vector of length n + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void mat_vec(double alpha, double A[], double x[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Matrix-transpose-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A'*x + * + * Parameters: + * A - matrix of size n X m + * x - vector of length n + * y - output vector of length m + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void matT_vec(double alpha, double A[], double x[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Sparse-matrix-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A*x + * + * where A is a sparse matrix. + * + * Parameters: + * pr,ir,jc - sparse representation of the matrix A, of size n x m + * x - vector of length m + * y - output vector of length n + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void mat_sp_vec(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double x[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Sparse-matrix-transpose-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A'*x + * + * where A is a sparse matrix. + * + * Parameters: + * pr,ir,jc - sparse representation of the matrix A, of size n x m + * x - vector of length m + * y - output vector of length n + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void matT_sp_vec(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double x[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Matrix-sparse-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A*x + * + * where A is a matrix and x is a sparse vector. + * + * Parameters: + * A - matrix of size n X m + * pr,ir,jc - sparse representation of the vector x, of length m + * y - output vector of length n + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void mat_vec_sp(double alpha, double A[], double pr[], mwIndex ir[], mwIndex jc[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Matrix-transpose-sparse-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A'*x + * + * where A is a matrix and x is a sparse vector. + * + * Parameters: + * A - matrix of size n X m + * pr,ir,jc - sparse representation of the vector x, of length n + * y - output vector of length m + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void matT_vec_sp(double alpha, double A[], double pr[], mwIndex ir[], mwIndex jc[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Sparse-matrix-sparse-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A*x + * + * where A is a sparse matrix and x is a sparse vector. + * + * Parameters: + * pr,ir,jc - sparse representation of the matrix A, of size n x m + * prx,irx,jcx - sparse representation of the vector x (of length m) + * y - output vector of length n + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void mat_sp_vec_sp(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double prx[], mwIndex irx[], mwIndex jcx[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Sparse-matrix-transpose-sparse-vector multiplication. + * + * Computes an operation of the form: + * + * y := alpha*A'*x + * + * where A is a sparse matrix and x is a sparse vector. + * + * Importnant note: this function is provided for completeness, but is NOT efficient. + * If possible, convert x to non-sparse representation and use matT_vec_sp instead. + * + * Parameters: + * pr,ir,jc - sparse representation of the matrix A, of size n x m + * prx,irx,jcx - sparse representation of the vector x (of length n) + * y - output vector of length n + * alpha - real constant + * n, m - dimensions of A + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void matT_sp_vec_sp(double alpha, double pr[], mwIndex ir[], mwIndex jc[], double prx[], mwIndex irx[], mwIndex jcx[], double y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Matrix-matrix multiplication. + * + * Computes an operation of the form: + * + * X := alpha*A*B + * + * Parameters: + * A - matrix of size n X m + * B - matrix of size m X k + * X - output matrix of size n X k + * alpha - real constant + * n, m, k - dimensions of A, B + * + * Note: This function re-writes the contents of X. + * + **************************************************************************/ +void mat_mat(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k); + + + +/************************************************************************** + * Matrix-transpose-matrix multiplication. + * + * Computes an operation of the form: + * + * X := alpha*A*B + * + * Parameters: + * A - matrix of size n X m + * B - matrix of size m X k + * X - output matrix of size n X k + * alpha - real constant + * n, m, k - dimensions of A, B + * + * Note: This function re-writes the contents of X. + * + **************************************************************************/ +void matT_mat(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k); + + + +/************************************************************************** + * Tensor-matrix multiplication. + * + * This function accepts a 3-D tensor A of size n X m X k + * and a 2-D matrix B of size l X k. + * The function computes the 3-D tensor X of size n X m X l, where + * + * X(i,j,:) = B*A(i,j,:) + * + * for all i,j. + * + * Parameters: + * A - tensor of size n X m X k + * B - matrix of size l X k + * X - output tensor of size n X m X l + * alpha - real constant + * n, m, k, l - dimensions of A, B + * + * Note: This function re-writes the contents of X. + * + **************************************************************************/ +void tens_mat(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k, mwSize l); + + + +/************************************************************************** + * Tensor-matrix-transpose multiplication. + * + * This function accepts a 3-D tensor A of size n X m X k + * and a 2-D matrix B of size k X l. + * The function computes the 3-D tensor X of size n X m X l, where + * + * X(i,j,:) = B'*A(i,j,:) + * + * for all i,j. + * + * Parameters: + * A - tensor of size n X m X k + * B - matrix of size k X l + * X - output tensor of size n X m X l + * alpha - real constant + * n, m, k, l - dimensions of A, B + * + * Note: This function re-writes the contents of X. + * + **************************************************************************/ +void tens_matT(double alpha, double A[], double B[], double X[], mwSize n, mwSize m, mwSize k, mwSize l); + + + +/************************************************************************** + * Vector-vector sum. + * + * Computes an operation of the form: + * + * y := alpha*x + y + * + * Parameters: + * x - vector of length n + * y - output vector of length n + * alpha - real constant + * n - length of x,y + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ +void vec_sum(double alpha, double x[], double y[], mwSize n); + +/************************************************************************** + * Vector-vector scalar multiply. + * + * Computes an operation of the form: + * + * y := alpha* x.*y + * + * Parameters: + * x - vector of length n + * y - output vector of length n + * alpha - real constant + * n - length of x,y + * + * Note: This function re-writes the contents of y. + * + **************************************************************************/ + + +void vec_smult(double alpha, double x[], double y[], mwSize n); + + +/************************************************************************** + * Triangular back substitution. + * + * Solve the set of linear equations + * + * T*x = b + * + * where T is lower or upper triangular. + * + * Parameters: + * ul - 'U' for upper triangular, 'L' for lower triangular + * A - matrix of size n x m containing T + * b - vector of length k + * x - output vector of length k + * n - size of first dimension of A + * k - the size of the equation set, k<=n,m + * + * Note: + * The matrix A can be of any size n X m, as long as n,m >= k. + * Only the lower/upper triangle of the submatrix A(1:k,1:k) defines the + * matrix T (depending on the parameter ul). + * + **************************************************************************/ +void backsubst(char ul, double A[], double b[], double x[], mwSize n, mwSize k); + + + +/************************************************************************** + * Solve a set of equations using a Cholesky decomposition. + * + * Solve the set of linear equations + * + * M*x = b + * + * where M is positive definite with a known Cholesky decomposition: + * either M=L*L' (L lower triangular) or M=U'*U (U upper triangular). + * + * Parameters: + * ul - 'U' for upper triangular, 'L' for lower triangular decomposition + * A - matrix of size n x m with the Cholesky decomposition of M + * b - vector of length k + * x - output vector of length k + * n - size of first dimension of A + * k - the size of the equation set, k<=n,m + * + * Note: + * The matrix A can be of any size n X m, as long as n,m >= k. + * Only the lower/upper triangle of the submatrix A(1:k,1:k) is used as + * the Cholesky decomposition of M (depending on the parameter ul). + * + **************************************************************************/ +void cholsolve(char ul, double A[], double b[], double x[], mwSize n, mwSize k); + + + +/************************************************************************** + * Maximum absolute value. + * + * Returns the index of the coefficient with maximal absolute value in a vector. + * + * Parameters: + * x - vector of length n + * n - length of x + * + **************************************************************************/ +mwIndex maxabs(double x[], mwSize n); + + + +/************************************************************************** + * Maximum vector element. + * + * Returns the index of the maximal coefficient in a vector. + * + * Parameters: + * x - vector of length n + * n - length of x + * + **************************************************************************/ +mwIndex maxpos(double x[], mwSize n); + + + +/************************************************************************** + * Vector-vector dot product. + * + * Computes an operation of the form: + * + * c = a'*b + * + * Parameters: + * a, b - vectors of length n + * n - length of a,b + * + * Returns: The dot product c. + * + **************************************************************************/ +double dotprod(double a[], double b[], mwSize n); + + + +/************************************************************************** + * Indexed vector assignment. + * + * Perform a permutation assignment of the form + * + * y = x(ind) + * + * where ind is an array of indices to x. + * + * Parameters: + * y - output vector of length k + * x - input vector of arbitrary length + * ind - array of indices into x (indices begin at 0) + * k - length of the array ind + * + **************************************************************************/ +void vec_assign(double y[], double x[], mwIndex ind[], mwSize k); + + + +/************************************************************************** + * Matrix transpose. + * + * Computes Y := X' + * + * Parameters: + * X - input matrix of size n X m + * Y - output matrix of size m X n + * n, m - dimensions of X + * + **************************************************************************/ +void transpose(double X[], double Y[], mwSize n, mwSize m); + + + +/************************************************************************** + * Print a matrix. + * + * Parameters: + * A - matrix of size n X m + * n, m - dimensions of A + * matname - name of matrix to display + * + **************************************************************************/ +void printmat(double A[], int n, int m, char* matname); + + + +/************************************************************************** + * Print a sparse matrix. + * + * Parameters: + * A - sparse matrix of type double + * matname - name of matrix to display + * + **************************************************************************/ +void printspmat(mxArray *A, char* matname); + + +#endif +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omp2Gabor.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,223 @@ +function gamma = omp2Gabor(varargin) +%% omp2Gabor Error-constrained Orthogonal Matching Pursuit. +% +% This file is part of SMALLbox [2] and it is adaptation of Ron +% Rubenstein omp solver [1] for Gabor dictionary as defined in +% Audio Inpainting by Adler et al [3]. The dictionary is presented as +% DCT+DST and solver pics two atoms per iteration (given the frequency one +% from DCT and one from DST). For more information look in [3]. +% +% GAMMA = OMP2(D,X,G,EPSILON) solves the optimization problem +% +% min |GAMMA|_0 s.t. |X - D*GAMMA|_2 <= EPSILON +% gamma +% +% for each of the signals in X, using Batch Orthogonal Matching Pursuit. +% Here, D is a dictionary with normalized columns, X is a matrix +% containing column signals, EPSILON is the error target for each signal, +% and G is the Gramm matrix D'*D. The output GAMMA is a matrix containing +% the sparse representations as its columns. +% +% GAMMA = OMP2(D,X,[],EPSILON) performs the same operation, but without +% the matrix G, using OMP-Cholesky. This call produces the same output as +% Batch-OMP, but is significantly slower. Using this syntax is only +% recommended when available memory is too small to store G. +% +% GAMMA = OMP2(DtX,XtX,G,EPSILON) is the fastest implementation of OMP2, +% but also requires the most memory. Here, DtX stores the projections +% D'*X, and XtX is a row vector containing the squared norms of the +% signals, sum(X.*X). In this case Batch-OMP is used, but without having +% to compute D'*X and XtX in advance, which slightly improves runtime. +% Note that in general, the call +% +% GAMMA = OMP2(D'*X, sum(X.*X), G, EPSILON); +% +% will be faster than the call +% +% GAMMA = OMP2(D,X,G,EPSILON); +% +% due to optimized matrix multiplications in Matlab. However, when the +% entire matrix D'*X cannot be stored in memory, one of the other two +% versions can be used. Both compute D'*X for just one signal at a time, +% and thus require much less memory. +% +% GAMMA = OMP2(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies additional +% parameters for OMP2. Available parameters are: +% +% 'gammamode' - Specifies the representation mode for GAMMA. Can be +% either 'full' or 'sparse', corresponding to a full or +% sparse matrix, respectively. By default, GAMMA is +% returned as a sparse matrix. +% 'maxatoms' - Limits the number of atoms in the representation of each +% signal. If specified, the number of atoms in each +% representation does not exceed this number, even if the +% error target is not met. Specifying maxatoms<0 implies +% no limit (default). +% 'messages' - Specifies whether progress messages should be displayed. +% When positive, this is the number of seconds between +% status prints. When negative, indicates that no messages +% should be displayed (this is the default). +% 'checkdict' - Specifies whether dictionary normalization should be +% verified. When set to 'on' (default) the dictionary +% atoms are verified to be of unit L2-norm. Setting this +% parameter to 'off' disables verification and accelerates +% function performance. Note that an unnormalized +% dictionary will produce invalid results. +% 'profile' - Can be either 'on' or 'off'. When 'on', profiling +% information is displayed at the end of the funciton +% execution. +% +% +% Summary of OMP2 versions: +% +% version | speed | memory +% ------------------------------------------------------------- +% OMP2(DtX,XtX,G,EPSILON) | very fast | very large +% OMP2(D,X,G,EPSILON) | fast | moderate +% OMP2(D,X,[],EPSILON) | very slow | small +% ------------------------------------------------------------- +% +% +% References: +% [1] M. Elad, R. Rubinstein, and M. Zibulevsky, "Efficient Implementation +% of the K-SVD Algorithm using Batch Orthogonal Matching Pursuit", +% Technical Report - CS, Technion, April 2008. +% +% See also OMP. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2009 + +% +% Centre for Digital Music, Queen Mary, University of London. +% This file copyright 2011 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. +%% + +% default options + +sparse_gamma = 1; +msgdelta = -1; +maxatoms = -1; +checkdict = 1; +profile = 0; + + +% determine number of parameters + +paramnum = 1; +while (paramnum<=nargin && ~ischar(varargin{paramnum})) + paramnum = paramnum+1; +end +paramnum = paramnum-1; + + +% parse options + +for i = paramnum+1:2:length(varargin) + paramname = varargin{i}; + paramval = varargin{i+1}; + + switch lower(paramname) + + case 'gammamode' + if (strcmpi(paramval,'sparse')) + sparse_gamma = 1; + elseif (strcmpi(paramval,'full')) + sparse_gamma = 0; + else + error('Invalid GAMMA mode'); + end + + case 'maxatoms' + maxatoms = paramval; + + case 'messages' + msgdelta = paramval; + + case 'checkdict' + if (strcmpi(paramval,'on')) + checkdict = 1; + elseif (strcmpi(paramval,'off')) + checkdict = 0; + else + error('Invalid checkdict option'); + end + + case 'profile' + if (strcmpi(paramval,'on')) + profile = 1; + elseif (strcmpi(paramval,'off')) + profile = 0; + else + error('Invalid profile mode'); + end + + otherwise + error(['Unknown option: ' paramname]); + end + +end + + +% determine call type + +if (paramnum==4) + + n1 = size(varargin{1},1); + n2 = size(varargin{2},1); + n3 = size(varargin{3},1); + + if ( (n1>1 && n2==1) || (n1==1 && n2==1 && n3==1) ) % DtX,XtX,G,EPSILON + + DtX = varargin{1}; + XtX = varargin{2}; + G = varargin{3}; + epsilon = varargin{4}; + D = []; + X = []; + + else % D,X,G,EPSILON + + D = varargin{1}; + X = varargin{2}; + G = varargin{3}; + epsilon = varargin{4}; + DtX = []; + XtX = []; + + end + +else + error('Invalid number of parameters'); +end + +G=[]; + +% verify dictionary normalization + +if (checkdict) + if (isempty(G)) + atomnorms = sum(D.*D); + else + atomnorms = diag(G); + end + if (any(abs(atomnorms-1) > 1e-2)) + error('Dictionary columns must be normalized to unit length'); + end +end + + +% omp + +gamma = omp2mexGabor(D,X,DtX,XtX,G,epsilon,sparse_gamma,msgdelta,maxatoms,profile);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omp2mex.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,156 @@ +/************************************************************************** + * + * File name: omp2mex.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + *************************************************************************/ + +#include "ompcore.h" +#include "omputils.h" +#include "mexutils.h" + + +/* Input Arguments */ + +#define IN_D prhs[0] +#define IN_X prhs[1] +#define IN_DtX prhs[2] +#define IN_XtX prhs[3] +#define IN_G prhs[4] +#define IN_EPS prhs[5] +#define IN_SPARSE_G prhs[6] +#define IN_MSGDELTA prhs[7] +#define IN_MAXATOMS prhs[8] +#define IN_PROFILE prhs[9] + + +/* Output Arguments */ + +#define GAMMA_OUT plhs[0] + + +/***************************************************************************************/ + + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) + +{ + double *D, *x, *DtX, *XtX, *G, eps, msgdelta; + int gmode, maxatoms, profile; + mwSize m, n, L; /* D is n x m , X is n x L, DtX is m x L */ + + + /* check parameters */ + + checkmatrix(IN_D, "OMP2", "D"); + checkmatrix(IN_X, "OMP2", "X"); + checkmatrix(IN_DtX, "OMP2", "DtX"); + checkmatrix(IN_XtX, "OMP2", "XtX"); + checkmatrix(IN_G, "OMP2", "G"); + + checkscalar(IN_EPS, "OMP2", "EPSILON"); + checkscalar(IN_SPARSE_G, "OMP2", "sparse_g"); + checkscalar(IN_MSGDELTA, "OMP2", "msgdelta"); + checkscalar(IN_MAXATOMS, "OMP2", "maxatoms"); + checkscalar(IN_PROFILE, "OMP2", "profile"); + + + /* get parameters */ + + x = D = DtX = XtX = G = 0; + + if (!mxIsEmpty(IN_D)) + D = mxGetPr(IN_D); + + if (!mxIsEmpty(IN_X)) + x = mxGetPr(IN_X); + + if (!mxIsEmpty(IN_DtX)) + DtX = mxGetPr(IN_DtX); + + if (!mxIsEmpty(IN_XtX)) + XtX = mxGetPr(IN_XtX); + + if (!mxIsEmpty(IN_G)) + G = mxGetPr(IN_G); + + eps = mxGetScalar(IN_EPS); + if ((int)(mxGetScalar(IN_SPARSE_G)+1e-2)) { + gmode = SPARSE_GAMMA; + } + else { + gmode = FULL_GAMMA; + } + msgdelta = mxGetScalar(IN_MSGDELTA); + if (mxGetScalar(IN_MAXATOMS) < -1e-5) { + maxatoms = -1; + } + else { + maxatoms = (int)(mxGetScalar(IN_MAXATOMS)+1e-2); + } + profile = (int)(mxGetScalar(IN_PROFILE)+1e-2); + + + /* check sizes */ + + if (D && x) { + n = mxGetM(IN_D); + m = mxGetN(IN_D); + L = mxGetN(IN_X); + + if (mxGetM(IN_X) != n) { + mexErrMsgTxt("D and X have incompatible sizes."); + } + + if (G) { + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("D and G have incompatible sizes."); + } + } + } + + else if (DtX && XtX) { + m = mxGetM(IN_DtX); + L = mxGetN(IN_DtX); + + /* set n to an arbitrary value that is at least the max possible number of selected atoms */ + + if (maxatoms>0) { + n = maxatoms; + } + else { + n = m; + } + + if ( !(mxGetM(IN_XtX)==L && mxGetN(IN_XtX)==1) && !(mxGetM(IN_XtX)==1 && mxGetN(IN_XtX)==L) ) { + mexErrMsgTxt("DtX and XtX have incompatible sizes."); + } + + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("DtX and G have incompatible sizes."); + } + } + + else { + mexErrMsgTxt("Either D and X, or DtX and XtX, must be specified."); + } + + + /* Do OMP! */ + + GAMMA_OUT = ompcore(D, x, DtX, XtX, G, n, m, L, maxatoms, eps, gmode, profile, msgdelta, 1); + + return; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omp2mex.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,23 @@ +%This is the Matlab interface to the OMP2 MEX implementation. +%The function is not for independent use, only through omp2.m. + + +%OMP2MEX Matlab interface to the OMP2 MEX implementation. +% GAMMA = OMP2MEX(D,X,DtX,XtX,G,EPSILON,SPARSE_G,MSGDELTA,MAXATOMS,PROFILE) +% invokes the OMP2 MEX function according to the specified parameters. Not +% all the parameters are required. Those among D, X, DtX, XtX and G which +% are not specified should be passed as []. +% +% EPSILON - the target error. +% SPARSE_G - returns a sparse GAMMA when nonzero, full GAMMA when zero. +% MSGDELTA - the delay in secs between messages. Zero means no messages. +% MAXATOMS - the max number of atoms per signal, negative for no max. +% PROFILE - nonzero means that profiling information should be printed. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2009
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omp2mexGabor.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,156 @@ +/************************************************************************** + * + * File name: omp2mex.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + *************************************************************************/ + +#include "ompcoreGabor.h" +#include "omputils.h" +#include "mexutils.h" + + +/* Input Arguments */ + +#define IN_D prhs[0] +#define IN_X prhs[1] +#define IN_DtX prhs[2] +#define IN_XtX prhs[3] +#define IN_G prhs[4] +#define IN_EPS prhs[5] +#define IN_SPARSE_G prhs[6] +#define IN_MSGDELTA prhs[7] +#define IN_MAXATOMS prhs[8] +#define IN_PROFILE prhs[9] + + +/* Output Arguments */ + +#define GAMMA_OUT plhs[0] + + +/***************************************************************************************/ + + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) + +{ + double *D, *x, *DtX, *XtX, *G, eps, msgdelta; + int gmode, maxatoms, profile; + mwSize m, n, L; /* D is n x m , X is n x L, DtX is m x L */ + + + /* check parameters */ + + checkmatrix(IN_D, "OMP2", "D"); + checkmatrix(IN_X, "OMP2", "X"); + checkmatrix(IN_DtX, "OMP2", "DtX"); + checkmatrix(IN_XtX, "OMP2", "XtX"); + checkmatrix(IN_G, "OMP2", "G"); + + checkscalar(IN_EPS, "OMP2", "EPSILON"); + checkscalar(IN_SPARSE_G, "OMP2", "sparse_g"); + checkscalar(IN_MSGDELTA, "OMP2", "msgdelta"); + checkscalar(IN_MAXATOMS, "OMP2", "maxatoms"); + checkscalar(IN_PROFILE, "OMP2", "profile"); + + + /* get parameters */ + + x = D = DtX = XtX = G = 0; + + if (!mxIsEmpty(IN_D)) + D = mxGetPr(IN_D); + + if (!mxIsEmpty(IN_X)) + x = mxGetPr(IN_X); + + if (!mxIsEmpty(IN_DtX)) + DtX = mxGetPr(IN_DtX); + + if (!mxIsEmpty(IN_XtX)) + XtX = mxGetPr(IN_XtX); + + if (!mxIsEmpty(IN_G)) + G = mxGetPr(IN_G); + + eps = mxGetScalar(IN_EPS); + if ((int)(mxGetScalar(IN_SPARSE_G)+1e-2)) { + gmode = SPARSE_GAMMA; + } + else { + gmode = FULL_GAMMA; + } + msgdelta = mxGetScalar(IN_MSGDELTA); + if (mxGetScalar(IN_MAXATOMS) < -1e-5) { + maxatoms = -1; + } + else { + maxatoms = (int)(mxGetScalar(IN_MAXATOMS)+1e-2); + } + profile = (int)(mxGetScalar(IN_PROFILE)+1e-2); + + + /* check sizes */ + + if (D && x) { + n = mxGetM(IN_D); + m = mxGetN(IN_D); + L = mxGetN(IN_X); + + if (mxGetM(IN_X) != n) { + mexErrMsgTxt("D and X have incompatible sizes."); + } + + if (G) { + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("D and G have incompatible sizes."); + } + } + } + + else if (DtX && XtX) { + m = mxGetM(IN_DtX); + L = mxGetN(IN_DtX); + + /* set n to an arbitrary value that is at least the max possible number of selected atoms */ + + if (maxatoms>0) { + n = maxatoms; + } + else { + n = m; + } + + if ( !(mxGetM(IN_XtX)==L && mxGetN(IN_XtX)==1) && !(mxGetM(IN_XtX)==1 && mxGetN(IN_XtX)==L) ) { + mexErrMsgTxt("DtX and XtX have incompatible sizes."); + } + + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("DtX and G have incompatible sizes."); + } + } + + else { + mexErrMsgTxt("Either D and X, or DtX and XtX, must be specified."); + } + + + /* Do OMP! */ + + GAMMA_OUT = ompcoreGabor(D, x, DtX, XtX, G, n, m, L, maxatoms, eps, gmode, profile, msgdelta, 1); + + return; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omp2mexGabor.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,23 @@ +%This is the Matlab interface to the OMP2 MEX implementation. +%The function is not for independent use, only through omp2.m. + + +%OMP2MEX Matlab interface to the OMP2 MEX implementation. +% GAMMA = OMP2MEXGABOR(D,X,DtX,XtX,G,EPSILON,SPARSE_G,MSGDELTA,MAXATOMS,PROFILE) +% invokes the OMP2 MEX function according to the specified parameters. Not +% all the parameters are required. Those among D, X, DtX, XtX and G which +% are not specified should be passed as []. +% +% EPSILON - the target error. +% SPARSE_G - returns a sparse GAMMA when nonzero, full GAMMA when zero. +% MSGDELTA - the delay in secs between messages. Zero means no messages. +% MAXATOMS - the max number of atoms per signal, negative for no max. +% PROFILE - nonzero means that profiling information should be printed. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2009
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompGabor.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,180 @@ +function gamma = omp(varargin) +%OMP Sparsity-constrained Orthogonal Matching Pursuit. +% GAMMA = OMP(D,X,G,T) solves the optimization problem +% +% min |X - D*GAMMA|_2 s.t. |GAMMA|_0 <= T +% gamma +% +% for each of the signals in X, using Batch Orthogonal Matching Pursuit. +% Here, D is a dictionary with normalized columns, X is a matrix +% containing column signals, T is the # of non-zeros in each signal +% representation, and G is the Gramm matrix D'*D. The output GAMMA is a +% matrix containing the sparse representations as its columns. +% +% GAMMA = OMP(D,X,[],T) performs the same operation, but without the +% matrix G, using OMP-Cholesky. This call produces the same output as +% Batch-OMP, but is significantly slower. Using this syntax is only +% recommended when available memory is too small to store G. +% +% GAMMA = OMP(DtX,G,T) is the fastest implementation of OMP, but also +% requires the most memory. Here, DtX stores the projections D'*X. In this +% case Batch-OMP is used, but without having to compute D'*X in advance, +% which slightly improves runtime. Note that in general, the call +% +% GAMMA = OMP(D'*X,G,T); +% +% will be faster than the call +% +% GAMMA = OMP(D,X,G,T); +% +% due to optimized matrix multiplications in Matlab. However, when the +% entire matrix D'*X cannot be stored in memory, one of the other two +% versions can be used. Both compute D'*X for just one signal at a time, +% and thus require much less memory. +% +% GAMMA = OMP(...,PARAM1,VAL1,PARAM2,VAL2,...) specifies additional +% parameters for OMP. Available parameters are: +% +% 'gammamode' - Specifies the representation mode for GAMMA. Can be +% either 'full' or 'sparse', corresponding to a full or +% sparse matrix, respectively. By default, GAMMA is +% returned as a sparse matrix. +% 'messages' - Specifies whether progress messages should be displayed. +% When positive, this is the number of seconds between +% status prints. When negative, indicates that no messages +% should be displayed (this is the default). +% 'checkdict' - Specifies whether dictionary normalization should be +% verified. When set to 'on' (default) the dictionary +% atoms are verified to be of unit L2-norm. Setting this +% parameter to 'off' disables verification and accelerates +% function performance. Note that an unnormalized +% dictionary will produce invalid results. +% 'profile' - Can be either 'on' or 'off'. When 'on', profiling +% information is displayed at the end of the funciton +% execution. +% +% +% Summary of OMP versions: +% +% version | speed | memory +% -------------------------------------------------- +% OMP(DtX,G,T) | very fast | very large +% OMP(D,X,G,T) | fast | moderate +% OMP(D,X,[],T) | very slow | small +% -------------------------------------------------- +% +% +% References: +% [1] M. Elad, R. Rubinstein, and M. Zibulevsky, "Efficient Implementation +% of the K-SVD Algorithm using Batch Orthogonal Matching Pursuit", +% Technical Report - CS, Technion, April 2008. +% +% See also OMP2. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2009 + + +% default options + +sparse_gamma = 1; +msgdelta = -1; +checkdict = 1; +profile = 0; + + +% determine number of parameters + +paramnum = 1; +while (paramnum<=nargin && ~ischar(varargin{paramnum})) + paramnum = paramnum+1; +end +paramnum = paramnum-1; + + +% parse options + +for i = paramnum+1:2:length(varargin) + paramname = varargin{i}; + paramval = varargin{i+1}; + + switch lower(paramname) + + case 'gammamode' + if (strcmpi(paramval,'sparse')) + sparse_gamma = 1; + elseif (strcmpi(paramval,'full')) + sparse_gamma = 0; + else + error('Invalid GAMMA mode'); + end + + case 'messages' + msgdelta = paramval; + + case 'checkdict' + if (strcmpi(paramval,'on')) + checkdict = 1; + elseif (strcmpi(paramval,'off')) + checkdict = 0; + else + error('Invalid checkdict option'); + end + + case 'profile' + if (strcmpi(paramval,'on')) + profile = 1; + elseif (strcmpi(paramval,'off')) + profile = 0; + else + error('Invalid profile mode'); + end + + otherwise + error(['Unknown option: ' paramname]); + end + +end + + +% determine call type + +if (paramnum==3) + DtX = varargin{1}; + G = varargin{2}; + T = varargin{3}; + D = []; + X = []; +elseif (paramnum==4) + D = varargin{1}; + X = varargin{2}; + G = varargin{3}; + T = varargin{4}; + DtX = []; +else + error('Invalid number of parameters'); +end + + +% verify dictionary normalization + +if (checkdict) + if (isempty(G)) + atomnorms = sum(D.*D); + else + atomnorms = diag(G); + end + if (any(abs(atomnorms-1) > 1e-2)) + error('Dictionary columns must be normalized to unit length'); + end +end + + +% omp + +gamma = ompmexGabor(D,X,DtX,G,T,sparse_gamma,msgdelta,profile);
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompcore.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,409 @@ +/************************************************************************** + * + * File name: ompcore.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 25.8.2009 + * + *************************************************************************/ + + +#include "ompcore.h" +#include "omputils.h" +#include "ompprof.h" +#include "myblas.h" +#include <math.h> +#include <string.h> + + + +/****************************************************************************** + * * + * Batch-OMP Implementation * + * * + ******************************************************************************/ + +mxArray* ompcore(double D[], double x[], double DtX[], double XtX[], double G[], mwSize n, mwSize m, mwSize L, + int T, double eps, int gamma_mode, int profile, double msg_delta, int erroromp) +{ + + profdata pd; + mxArray *Gamma; + mwIndex i, j, signum, pos, *ind, *gammaIr, *gammaJc, gamma_count; + mwSize allocated_coefs, allocated_cols; + int DtX_specified, XtX_specified, batchomp, standardomp, *selected_atoms; + double *alpha, *r, *Lchol, *c, *Gsub, *Dsub, sum, *gammaPr, *tempvec1, *tempvec2; + double eps2, resnorm, delta, deltaprev, secs_remain; + int mins_remain, hrs_remain; + clock_t lastprint_time, starttime; + + + + /*** status flags ***/ + + DtX_specified = (DtX!=0); /* indicates whether D'*x was provided */ + XtX_specified = (XtX!=0); /* indicates whether sum(x.*x) was provided */ + + standardomp = (G==0); /* batch-omp or standard omp are selected depending on availability of G */ + batchomp = !standardomp; + + + + /*** allocate output matrix ***/ + + + if (gamma_mode == FULL_GAMMA) { + + /* allocate full matrix of size m X L */ + + Gamma = mxCreateDoubleMatrix(m, L, mxREAL); + gammaPr = mxGetPr(Gamma); + gammaIr = 0; + gammaJc = 0; + } + else { + + /* allocate sparse matrix with room for allocated_coefs nonzeros */ + + /* for error-omp, begin with L*sqrt(n)/2 allocated nonzeros, otherwise allocate L*T nonzeros */ + allocated_coefs = erroromp ? (mwSize)(ceil(L*sqrt((double)n)/2.0) + 1.01) : L*T; + Gamma = mxCreateSparse(m, L, allocated_coefs, mxREAL); + gammaPr = mxGetPr(Gamma); + gammaIr = mxGetIr(Gamma); + gammaJc = mxGetJc(Gamma); + gamma_count = 0; + gammaJc[0] = 0; + } + + + /*** helper arrays ***/ + + alpha = (double*)mxMalloc(m*sizeof(double)); /* contains D'*residual */ + ind = (mwIndex*)mxMalloc(n*sizeof(mwIndex)); /* indices of selected atoms */ + selected_atoms = (int*)mxMalloc(m*sizeof(int)); /* binary array with 1's for selected atoms */ + c = (double*)mxMalloc(n*sizeof(double)); /* orthogonal projection result */ + + /* current number of columns in Dsub / Gsub / Lchol */ + allocated_cols = erroromp ? (mwSize)(ceil(sqrt((double)n)/2.0) + 1.01) : T; + + /* Cholesky decomposition of D_I'*D_I */ + Lchol = (double*)mxMalloc(n*allocated_cols*sizeof(double)); + + /* temporary vectors for various computations */ + tempvec1 = (double*)mxMalloc(m*sizeof(double)); + tempvec2 = (double*)mxMalloc(m*sizeof(double)); + + if (batchomp) { + /* matrix containing G(:,ind) - the columns of G corresponding to the selected atoms, in order of selection */ + Gsub = (double*)mxMalloc(m*allocated_cols*sizeof(double)); + } + else { + /* matrix containing D(:,ind) - the selected atoms from D, in order of selection */ + Dsub = (double*)mxMalloc(n*allocated_cols*sizeof(double)); + + /* stores the residual */ + r = (double*)mxMalloc(n*sizeof(double)); + } + + if (!DtX_specified) { + /* contains D'*x for the current signal */ + DtX = (double*)mxMalloc(m*sizeof(double)); + } + + + + /*** initializations for error omp ***/ + + if (erroromp) { + eps2 = eps*eps; /* compute eps^2 */ + if (T<0 || T>n) { /* unspecified max atom num - set max atoms to n */ + T = n; + } + } + + + + /*** initialize timers ***/ + + initprofdata(&pd); /* initialize profiling counters */ + starttime = clock(); /* record starting time for eta computations */ + lastprint_time = starttime; /* time of last status display */ + + + + /********************** perform omp for each signal **********************/ + + + + for (signum=0; signum<L; ++signum) { + + + /* initialize residual norm and deltaprev for error-omp */ + + if (erroromp) { + if (XtX_specified) { + resnorm = XtX[signum]; + } + else { + resnorm = dotprod(x+n*signum, x+n*signum, n); + addproftime(&pd, XtX_TIME); + } + deltaprev = 0; /* delta tracks the value of gamma'*G*gamma */ + } + else { + /* ignore residual norm stopping criterion */ + eps2 = 0; + resnorm = 1; + } + + + if (resnorm>eps2 && T>0) { + + /* compute DtX */ + + if (!DtX_specified) { + matT_vec(1, D, x+n*signum, DtX, n, m); + addproftime(&pd, DtX_TIME); + } + + + /* initialize alpha := DtX */ + + memcpy(alpha, DtX + m*signum*DtX_specified, m*sizeof(double)); + + + /* mark all atoms as unselected */ + + for (i=0; i<m; ++i) { + selected_atoms[i] = 0; + } + + } + + + /* main loop */ + + i=0; + while (resnorm>eps2 && i<T) { + + /* index of next atom */ + + pos = maxabs(alpha, m); + addproftime(&pd, MAXABS_TIME); + + + /* stop criterion: selected same atom twice, or inner product too small */ + + if (selected_atoms[pos] || alpha[pos]*alpha[pos]<1e-14) { + break; + } + + + /* mark selected atom */ + + ind[i] = pos; + selected_atoms[pos] = 1; + + + /* matrix reallocation */ + + if (erroromp && i>=allocated_cols) { + + allocated_cols = (mwSize)(ceil(allocated_cols*MAT_INC_FACTOR) + 1.01); + + Lchol = (double*)mxRealloc(Lchol,n*allocated_cols*sizeof(double)); + + batchomp ? (Gsub = (double*)mxRealloc(Gsub,m*allocated_cols*sizeof(double))) : + (Dsub = (double*)mxRealloc(Dsub,n*allocated_cols*sizeof(double))) ; + } + + + /* append column to Gsub or Dsub */ + + if (batchomp) { + memcpy(Gsub+i*m, G+pos*m, m*sizeof(double)); + } + else { + memcpy(Dsub+i*n, D+pos*n, n*sizeof(double)); + } + + + /*** Cholesky update ***/ + + if (i==0) { + *Lchol = 1; + } + else { + + /* incremental Cholesky decomposition: compute next row of Lchol */ + + if (standardomp) { + matT_vec(1, Dsub, D+n*pos, tempvec1, n, i); /* compute tempvec1 := Dsub'*d where d is new atom */ + addproftime(&pd, DtD_TIME); + } + else { + vec_assign(tempvec1, Gsub+i*m, ind, i); /* extract tempvec1 := Gsub(ind,i) */ + } + backsubst('L', Lchol, tempvec1, tempvec2, n, i); /* compute tempvec2 = Lchol \ tempvec1 */ + for (j=0; j<i; ++j) { /* write tempvec2 to end of Lchol */ + Lchol[j*n+i] = tempvec2[j]; + } + + /* compute Lchol(i,i) */ + sum = 0; + for (j=0; j<i; ++j) { /* compute sum of squares of last row without Lchol(i,i) */ + sum += SQR(Lchol[j*n+i]); + } + if ( (1-sum) <= 1e-14 ) { /* Lchol(i,i) is zero => selected atoms are dependent */ + break; + } + Lchol[i*n+i] = sqrt(1-sum); + } + + addproftime(&pd, LCHOL_TIME); + + i++; + + + /* perform orthogonal projection and compute sparse coefficients */ + + vec_assign(tempvec1, DtX + m*signum*DtX_specified, ind, i); /* extract tempvec1 = DtX(ind) */ + cholsolve('L', Lchol, tempvec1, c, n, i); /* solve LL'c = tempvec1 for c */ + addproftime(&pd, COMPCOEF_TIME); + + + /* update alpha = D'*residual */ + + if (standardomp) { + mat_vec(-1, Dsub, c, r, n, i); /* compute r := -Dsub*c */ + vec_sum(1, x+n*signum, r, n); /* compute r := x+r */ + + + /*memcpy(r, x+n*signum, n*sizeof(double)); /* assign r := x */ + /*mat_vec1(-1, Dsub, c, 1, r, n, i); /* compute r := r-Dsub*c */ + + addproftime(&pd, COMPRES_TIME); + matT_vec(1, D, r, alpha, n, m); /* compute alpha := D'*r */ + addproftime(&pd, DtR_TIME); + + /* update residual norm */ + if (erroromp) { + resnorm = dotprod(r, r, n); + addproftime(&pd, UPDATE_RESNORM_TIME); + } + } + else { + mat_vec(1, Gsub, c, tempvec1, m, i); /* compute tempvec1 := Gsub*c */ + memcpy(alpha, DtX + m*signum*DtX_specified, m*sizeof(double)); /* set alpha = D'*x */ + vec_sum(-1, tempvec1, alpha, m); /* compute alpha := alpha - tempvec1 */ + addproftime(&pd, UPDATE_DtR_TIME); + + /* update residual norm */ + if (erroromp) { + vec_assign(tempvec2, tempvec1, ind, i); /* assign tempvec2 := tempvec1(ind) */ + delta = dotprod(c,tempvec2,i); /* compute c'*tempvec2 */ + resnorm = resnorm - delta + deltaprev; /* residual norm update */ + deltaprev = delta; + addproftime(&pd, UPDATE_RESNORM_TIME); + } + } + } + + + /*** generate output vector gamma ***/ + + if (gamma_mode == FULL_GAMMA) { /* write the coefs in c to their correct positions in gamma */ + for (j=0; j<i; ++j) { + gammaPr[m*signum + ind[j]] = c[j]; + } + } + else { + /* sort the coefs by index before writing them to gamma */ + quicksort(ind,c,i); + addproftime(&pd, INDEXSORT_TIME); + + /* gamma is full - reallocate */ + if (gamma_count+i >= allocated_coefs) { + + while(gamma_count+i >= allocated_coefs) { + allocated_coefs = (mwSize)(ceil(GAMMA_INC_FACTOR*allocated_coefs) + 1.01); + } + + mxSetNzmax(Gamma, allocated_coefs); + mxSetPr(Gamma, mxRealloc(gammaPr, allocated_coefs*sizeof(double))); + mxSetIr(Gamma, mxRealloc(gammaIr, allocated_coefs*sizeof(mwIndex))); + + gammaPr = mxGetPr(Gamma); + gammaIr = mxGetIr(Gamma); + } + + /* append coefs to gamma and update the indices */ + for (j=0; j<i; ++j) { + gammaPr[gamma_count] = c[j]; + gammaIr[gamma_count] = ind[j]; + gamma_count++; + } + gammaJc[signum+1] = gammaJc[signum] + i; + } + + + + /*** display status messages ***/ + + if (msg_delta>0 && (clock()-lastprint_time)/(double)CLOCKS_PER_SEC >= msg_delta) + { + lastprint_time = clock(); + + /* estimated remainig time */ + secs2hms( ((L-signum-1)/(double)(signum+1)) * ((lastprint_time-starttime)/(double)CLOCKS_PER_SEC) , + &hrs_remain, &mins_remain, &secs_remain); + + mexPrintf("omp: signal %d / %d, estimated remaining time: %02d:%02d:%05.2f\n", + signum+1, L, hrs_remain, mins_remain, secs_remain); + mexEvalString("drawnow;"); + } + + } + + /* end omp */ + + + + /*** print final messages ***/ + + if (msg_delta>0) { + mexPrintf("omp: signal %d / %d\n", signum, L); + } + + if (profile) { + printprofinfo(&pd, erroromp, batchomp, L); + } + + + + /* free memory */ + + if (!DtX_specified) { + mxFree(DtX); + } + if (standardomp) { + mxFree(r); + mxFree(Dsub); + } + else { + mxFree(Gsub); + } + mxFree(tempvec2); + mxFree(tempvec1); + mxFree(Lchol); + mxFree(c); + mxFree(selected_atoms); + mxFree(ind); + mxFree(alpha); + + return Gamma; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompcore.h Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,80 @@ +/************************************************************************** + * + * File name: ompcore.h + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + * Contains the core implementation of Batch-OMP / OMP-Cholesky. + * + *************************************************************************/ + + +#ifndef __OMP_CORE_H__ +#define __OMP_CORE_H__ + + +#include "mex.h" + + + +/************************************************************************** + * Perform Batch-OMP or OMP-Cholesky on a specified set of signals, using + * either a fixed number of atoms or an error bound. + * + * Parameters (not all required): + * + * D - the dictionary, of size n X m + * x - the signals, of size n X L + * DtX - D'*x, of size m X L + * XtX - squared norms of the signals in x, sum(x.*x), of length L + * G - D'*D, of size m X m + * T - target sparsity, or maximal number of atoms for error-based OMP + * eps - target residual norm for error-based OMP + * gamma_mode - one of the constants FULL_GAMMA or SPARSE_GAMMA + * profile - if non-zero, profiling info is printed + * msg_delta - positive: the # of seconds between status prints, otherwise: nothing is printed + * erroromp - if nonzero indicates error-based OMP, otherwise fixed sparsity OMP + * + * Usage: + * + * The function can be called using different parameters, and will have + * different complexity depending on the parameters specified. Arrays which + * are not specified should be passed as null (0). When G is specified, + * Batch-OMP is performed. Otherwise, OMP-Cholesky is performed. + * + * Fixed-sparsity usage: + * --------------------- + * Either DtX, or D and x, must be specified. Specifying DtX is more efficient. + * XtX does not need to be specified. + * When D and x are specified, G is not required. However, not providing G + * will significantly degrade efficiency. + * The number of atoms must be specified in T. The value of eps is ignored. + * Finally, set erroromp to 0. + * + * Error-OMP usage: + * ---------------- + * Either DtX and Xtx, or D and x, must be specified. Specifying DtX and XtX + * is more efficient. + * When D and x are specified, G is not required. However, not providing G + * will significantly degrade efficiency. + * The target error must be specified in eps. A hard limit on the number + * of atoms can also be specified via the parameter T. Otherwise, T should + * be negative. Finally, set erroromp to nonzero. + * + * + * Returns: + * An mxArray containing the sparse representations of the signals in x + * (allocated using the appropriate mxCreateXXX() function). + * The array is either full or sparse, depending on gamma_mode. + * + **************************************************************************/ +mxArray* ompcore(double D[], double x[], double DtX[], double XtX[], double G[], mwSize n, mwSize m, mwSize L, + int T, double eps, int gamma_mode, int profile, double msg_delta, int erroromp); + + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompcoreGabor.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,465 @@ +/************************************************************************** + * + * File name: ompcoreGabor.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 25.8.2009 + * + * Modified by Ivan damnjanovic July 2011 + * Takes to atoms per iteration. It should be used for Gabor dictionaries + * as specified in + * "Audio Inpainting" Amir Adler, Valentin Emiya, Maria G. Jafari, + * Michael Elad, Remi Gribonval and Mark D. Plumbley + * Draft version: March 6, 2011 + * + *************************************************************************/ + + +#include "ompcoreGabor.h" +#include "omputils.h" +#include "ompprof.h" +#include "myblas.h" +#include <math.h> +#include <string.h> + + + +/****************************************************************************** + * * + * Batch-OMP Implementation * + * * + ******************************************************************************/ + +mxArray* ompcoreGabor(double D[], double x[], double DtX[], double XtX[], double G[], mwSize n, mwSize m, mwSize L, + int T, double eps, int gamma_mode, int profile, double msg_delta, int erroromp) +{ + + profdata pd; + mxArray *Gamma; + mwIndex i, j, k, signum, pos, *ind, *gammaIr, *gammaJc, gamma_count; + mwSize allocated_coefs, allocated_cols; + int DtX_specified, XtX_specified, batchomp, standardomp, *selected_atoms; + double *proj, *proj1, *proj2, *D1, *D2, *D1D2, *n12, *alpha, *beta, *error; + double *r, *Lchol, *c, *Gsub, *Dsub, sum, *gammaPr, *tempvec1, *tempvec2; + double eps2, resnorm, delta, deltaprev, secs_remain; + int mins_remain, hrs_remain; + clock_t lastprint_time, starttime; + + + + /*** status flags ***/ + + DtX_specified = (DtX!=0); /* indicates whether D'*x was provided */ + XtX_specified = (XtX!=0); /* indicates whether sum(x.*x) was provided */ + + standardomp = (G==0); /* batch-omp or standard omp are selected depending on availability of G */ + batchomp = !standardomp; + + + + /*** allocate output matrix ***/ + + + if (gamma_mode == FULL_GAMMA) { + + /* allocate full matrix of size m X L */ + + Gamma = mxCreateDoubleMatrix(m, L, mxREAL); + gammaPr = mxGetPr(Gamma); + gammaIr = 0; + gammaJc = 0; + } + else { + + /* allocate sparse matrix with room for allocated_coefs nonzeros */ + + /* for error-omp, begin with L*sqrt(n)/2 allocated nonzeros, otherwise allocate L*T nonzeros */ + allocated_coefs = erroromp ? (mwSize)(ceil(L*sqrt((double)n)/2.0) + 1.01) : L*T; + Gamma = mxCreateSparse(m, L, allocated_coefs, mxREAL); + gammaPr = mxGetPr(Gamma); + gammaIr = mxGetIr(Gamma); + gammaJc = mxGetJc(Gamma); + gamma_count = 0; + gammaJc[0] = 0; + } + + + /*** helper arrays ***/ + /* Ivan Damnjanovic July 2011*/ + proj = (double*)mxMalloc(m*sizeof(double)); + proj1 = (double*)mxMalloc(m/2*sizeof(double)); + proj2 = (double*)mxMalloc(m/2*sizeof(double)); + D1 = (double*)mxMalloc(n*m/2*sizeof(double)); + D2 = (double*)mxMalloc(n*m/2*sizeof(double)); + memcpy(D1, D , n*m/2*sizeof(double)); + memcpy(D2, D+n*m/2, n*m/2*sizeof(double)); + + D1D2 = (double*)mxMalloc(m/2*sizeof(double)); + n12 = (double*)mxMalloc(m/2*sizeof(double)); + + vec_smult(1,D2, D1, n*m/2); + + for (i=0; i<m/2; i++) { + D1D2[i]=0; + n12[i]=0; + for (j=0; j<n; j++) { + D1D2[i] += D1[i*n+j]; + } + n12[i]=1/(1-D1D2[i]*D1D2[i]); + } + + memcpy(D1, D , n*m/2*sizeof(double)); + + alpha = (double*)mxMalloc(m/2*sizeof(double)); /* contains D'*residual */ + beta = (double*)mxMalloc(m/2*sizeof(double)); + error = (double*)mxMalloc(m/2*sizeof(double)); + + ind = (mwIndex*)mxMalloc(m*sizeof(mwIndex)); /* indices of selected atoms */ + selected_atoms = (int*)mxMalloc(m*sizeof(int)); /* binary array with 1's for selected atoms */ + c = (double*)mxMalloc(n*sizeof(double)); /* orthogonal projection result */ + + /* current number of columns in Dsub / Gsub / Lchol */ + allocated_cols = erroromp ? (mwSize)(ceil(sqrt((double)n)/2.0) + 1.01) : T; + + /* Cholesky decomposition of D_I'*D_I */ + Lchol = (double*)mxMalloc(n*allocated_cols*sizeof(double)); + + /* temporary vectors for various computations */ + tempvec1 = (double*)mxMalloc(m*sizeof(double)); + tempvec2 = (double*)mxMalloc(m*sizeof(double)); + + if (batchomp) { + /* matrix containing G(:,ind) - the columns of G corresponding to the selected atoms, in order of selection */ + Gsub = (double*)mxMalloc(m*allocated_cols*sizeof(double)); + } + else { + /* matrix containing D(:,ind) - the selected atoms from D, in order of selection */ + Dsub = (double*)mxMalloc(n*allocated_cols*sizeof(double)); + + /* stores the residual */ + r = (double*)mxMalloc(n*sizeof(double)); + } + + if (!DtX_specified) { + /* contains D'*x for the current signal */ + DtX = (double*)mxMalloc(m*sizeof(double)); + } + + + + /*** initializations for error omp ***/ + + if (erroromp) { + eps2 = eps*eps; /* compute eps^2 */ + if (T<0 || T>n) { /* unspecified max atom num - set max atoms to n */ + T = n; + } + } + + + + /*** initialize timers ***/ + + initprofdata(&pd); /* initialize profiling counters */ + starttime = clock(); /* record starting time for eta computations */ + lastprint_time = starttime; /* time of last status display */ + + + + /********************** perform omp for each signal **********************/ + + + + for (signum=0; signum<L; ++signum) { + + + /* initialize residual norm and deltaprev for error-omp */ + + if (erroromp) { + if (XtX_specified) { + resnorm = XtX[signum]; + } + else { + resnorm = dotprod(x+n*signum, x+n*signum, n); + addproftime(&pd, XtX_TIME); + } + deltaprev = 0; /* delta tracks the value of gamma'*G*gamma */ + } + else { + /* ignore residual norm stopping criterion */ + eps2 = 0; + resnorm = 1; + } + + + if (resnorm>eps2 && T>0) { + + /* compute DtX */ + + if (!DtX_specified) { + matT_vec(1, D, x+n*signum, DtX, n, m); + addproftime(&pd, DtX_TIME); + memcpy(r , x+n*signum, n*sizeof(double)); + } + + + /* initialize projections to D1 and D2 := DtX */ + + memcpy(proj, DtX + m*signum*DtX_specified, m*sizeof(double)); + + + /* mark all atoms as unselected */ + + for (i=0; i<m; ++i) { + selected_atoms[i] = 0; + } + + } + + + /* main loop */ + + i=0; + while (resnorm>eps2 && i<T) { + + /* index of next atom */ + memcpy(proj1, proj, m/2*sizeof(double)); + memcpy(proj2, proj + m/2, m/2*sizeof(double)); + for (k=0; k<m/2; k++){ + alpha[k] = (proj1[k] - D1D2[k]*proj2[k])*n12[k]; + beta[k] = (proj2[k] - D1D2[k]*proj1[k])*n12[k]; + } + for (k=0; k<m/2; k++){ + error[k]=0; + for (j=0; j<n; j++){ + error[k]+= (abs(r[j])-D1[k*n+j]*alpha[k]-D2[k*n+j]*beta[k])*(abs(r[j])-D1[k*n+j]*alpha[k]-D2[k*n+j]*beta[k]); + } + } + pos = maxabs(error, m/2); + addproftime(&pd, MAXABS_TIME); + + + /* stop criterion: selected same atom twice, or inner product too small */ + + if (selected_atoms[pos] || alpha[pos]*alpha[pos]<1e-14) { + break; + } + + for (k=0;k<2;k++){ + /* mark selected atom */ + + ind[i] = pos+k*m/2; + selected_atoms[pos+k*m/2] = 1; + + + /* matrix reallocation */ + + if (erroromp && i>=allocated_cols) { + + allocated_cols = (mwSize)(ceil(allocated_cols*MAT_INC_FACTOR) + 1.01); + + Lchol = (double*)mxRealloc(Lchol,n*allocated_cols*sizeof(double)); + + batchomp ? (Gsub = (double*)mxRealloc(Gsub,m*allocated_cols*sizeof(double))) : + (Dsub = (double*)mxRealloc(Dsub,n*allocated_cols*sizeof(double))) ; + } + + + /* append column to Gsub or Dsub */ + + if (batchomp) { + memcpy(Gsub+i*m, G+(pos+k*m/2)*m, m*sizeof(double)); + } + else { + memcpy(Dsub+(i)*n, D+(pos+k*m/2)*n, n*sizeof(double)); + } + + + /*** Cholesky update ***/ + + if (i==0) { + *Lchol = 1; + } + else { + + /* incremental Cholesky decomposition: compute next row of Lchol */ + + if (standardomp) { + matT_vec(1, Dsub, D+n*(pos+k*m/2), tempvec1, n, i); /* compute tempvec1 := Dsub'*d where d is new atom */ + addproftime(&pd, DtD_TIME); + } + else { + vec_assign(tempvec1, Gsub+i*m, ind, i); /* extract tempvec1 := Gsub(ind,i) */ + } + backsubst('L', Lchol, tempvec1, tempvec2, n, i); /* compute tempvec2 = Lchol \ tempvec1 */ + for (j=0; j<i; ++j) { /* write tempvec2 to end of Lchol */ + Lchol[j*n+i] = tempvec2[j]; + } + + /* compute Lchol(i,i) */ + sum = 0; + for (j=0; j<i; ++j) { /* compute sum of squares of last row without Lchol(i,i) */ + sum += SQR(Lchol[j*n+i]); + } + if ( (1-sum) <= 1e-14 ) { /* Lchol(i,i) is zero => selected atoms are dependent */ + break; + } + Lchol[i*n+i] = sqrt(1-sum); + } + + addproftime(&pd, LCHOL_TIME); + + i++; + + } + /* perform orthogonal projection and compute sparse coefficients */ + + vec_assign(tempvec1, DtX + m*signum*DtX_specified, ind, i); /* extract tempvec1 = DtX(ind) */ + cholsolve('L', Lchol, tempvec1, c, n, i); /* solve LL'c = tempvec1 for c */ + addproftime(&pd, COMPCOEF_TIME); + + + /* update alpha = D'*residual */ + + if (standardomp) { + mat_vec(-1, Dsub, c, r, n, i); /* compute r := -Dsub*c */ + vec_sum(1, x+n*signum, r, n); /* compute r := x+r */ + + + /*memcpy(r, x+n*signum, n*sizeof(double)); /* assign r := x */ + /*mat_vec1(-1, Dsub, c, 1, r, n, i); /* compute r := r-Dsub*c */ + + addproftime(&pd, COMPRES_TIME); + matT_vec(1, D, r, proj, n, m); /* compute proj := D'*r */ + addproftime(&pd, DtR_TIME); + + /* update residual norm */ + if (erroromp) { + resnorm = dotprod(r, r, n); + addproftime(&pd, UPDATE_RESNORM_TIME); + } + } + else { + mat_vec(1, Gsub, c, tempvec1, m, i); /* compute tempvec1 := Gsub*c */ + memcpy(proj, DtX + m*signum*DtX_specified, m*sizeof(double)); /* set proj = D'*x */ + vec_sum(-1, tempvec1, proj, m); /* compute proj := proj - tempvec1 */ + addproftime(&pd, UPDATE_DtR_TIME); + + /* update residual norm */ + if (erroromp) { + vec_assign(tempvec2, tempvec1, ind, i); /* assign tempvec2 := tempvec1(ind) */ + delta = dotprod(c,tempvec2,i); /* compute c'*tempvec2 */ + resnorm = resnorm - delta + deltaprev; /* residual norm update */ + deltaprev = delta; + addproftime(&pd, UPDATE_RESNORM_TIME); + } + } + } + + + /*** generate output vector gamma ***/ + + if (gamma_mode == FULL_GAMMA) { /* write the coefs in c to their correct positions in gamma */ + for (j=0; j<i; ++j) { + gammaPr[m*signum + ind[j]] = c[j]; + } + } + else { + /* sort the coefs by index before writing them to gamma */ + quicksort(ind,c,i); + addproftime(&pd, INDEXSORT_TIME); + + /* gamma is full - reallocate */ + if (gamma_count+i >= allocated_coefs) { + + while(gamma_count+i >= allocated_coefs) { + allocated_coefs = (mwSize)(ceil(GAMMA_INC_FACTOR*allocated_coefs) + 1.01); + } + + mxSetNzmax(Gamma, allocated_coefs); + mxSetPr(Gamma, mxRealloc(gammaPr, allocated_coefs*sizeof(double))); + mxSetIr(Gamma, mxRealloc(gammaIr, allocated_coefs*sizeof(mwIndex))); + + gammaPr = mxGetPr(Gamma); + gammaIr = mxGetIr(Gamma); + } + + /* append coefs to gamma and update the indices */ + for (j=0; j<i; ++j) { + gammaPr[gamma_count] = c[j]; + gammaIr[gamma_count] = ind[j]; + gamma_count++; + } + gammaJc[signum+1] = gammaJc[signum] + i; + } + + + + /*** display status messages ***/ + + if (msg_delta>0 && (clock()-lastprint_time)/(double)CLOCKS_PER_SEC >= msg_delta) + { + lastprint_time = clock(); + + /* estimated remainig time */ + secs2hms( ((L-signum-1)/(double)(signum+1)) * ((lastprint_time-starttime)/(double)CLOCKS_PER_SEC) , + &hrs_remain, &mins_remain, &secs_remain); + + mexPrintf("omp: signal %d / %d, estimated remaining time: %02d:%02d:%05.2f\n", + signum+1, L, hrs_remain, mins_remain, secs_remain); + mexEvalString("drawnow;"); + } + + } + + /* end omp */ + + + + /*** print final messages ***/ + + if (msg_delta>0) { + mexPrintf("omp: signal %d / %d\n", signum, L); + } + + if (profile) { + printprofinfo(&pd, erroromp, batchomp, L); + } + + + + /* free memory */ + + if (!DtX_specified) { + mxFree(DtX); + } + if (standardomp) { + mxFree(r); + mxFree(Dsub); + } + else { + mxFree(Gsub); + } + mxFree(tempvec2); + mxFree(tempvec1); + mxFree(Lchol); + mxFree(c); + mxFree(selected_atoms); + mxFree(ind); + mxFree(proj); + mxFree(proj1); + mxFree(proj2); + mxFree(D1); + mxFree(D2); + mxFree(D1D2); + mxFree(n12); + mxFree(alpha); + mxFree(beta); + mxFree(error); + + return Gamma; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompcoreGabor.h Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,80 @@ +/************************************************************************** + * + * File name: ompcore.h + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + * Contains the core implementation of Batch-OMP / OMP-Cholesky. + * + *************************************************************************/ + + +#ifndef __OMP_CORE_H__ +#define __OMP_CORE_H__ + + +#include "mex.h" + + + +/************************************************************************** + * Perform Batch-OMP or OMP-Cholesky on a specified set of signals, using + * either a fixed number of atoms or an error bound. + * + * Parameters (not all required): + * + * D - the dictionary, of size n X m + * x - the signals, of size n X L + * DtX - D'*x, of size m X L + * XtX - squared norms of the signals in x, sum(x.*x), of length L + * G - D'*D, of size m X m + * T - target sparsity, or maximal number of atoms for error-based OMP + * eps - target residual norm for error-based OMP + * gamma_mode - one of the constants FULL_GAMMA or SPARSE_GAMMA + * profile - if non-zero, profiling info is printed + * msg_delta - positive: the # of seconds between status prints, otherwise: nothing is printed + * erroromp - if nonzero indicates error-based OMP, otherwise fixed sparsity OMP + * + * Usage: + * + * The function can be called using different parameters, and will have + * different complexity depending on the parameters specified. Arrays which + * are not specified should be passed as null (0). When G is specified, + * Batch-OMP is performed. Otherwise, OMP-Cholesky is performed. + * + * Fixed-sparsity usage: + * --------------------- + * Either DtX, or D and x, must be specified. Specifying DtX is more efficient. + * XtX does not need to be specified. + * When D and x are specified, G is not required. However, not providing G + * will significantly degrade efficiency. + * The number of atoms must be specified in T. The value of eps is ignored. + * Finally, set erroromp to 0. + * + * Error-OMP usage: + * ---------------- + * Either DtX and Xtx, or D and x, must be specified. Specifying DtX and XtX + * is more efficient. + * When D and x are specified, G is not required. However, not providing G + * will significantly degrade efficiency. + * The target error must be specified in eps. A hard limit on the number + * of atoms can also be specified via the parameter T. Otherwise, T should + * be negative. Finally, set erroromp to nonzero. + * + * + * Returns: + * An mxArray containing the sparse representations of the signals in x + * (allocated using the appropriate mxCreateXXX() function). + * The array is either full or sparse, depending on gamma_mode. + * + **************************************************************************/ +mxArray* ompcoreGabor(double D[], double x[], double DtX[], double XtX[], double G[], mwSize n, mwSize m, mwSize L, + int T, double eps, int gamma_mode, int profile, double msg_delta, int erroromp); + + +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompmex.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,133 @@ +/************************************************************************** + * + * File name: ompmex.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + *************************************************************************/ + +#include "ompcore.h" +#include "omputils.h" +#include "mexutils.h" + + +/* Input Arguments */ + +#define IN_D prhs[0] +#define IN_X prhs[1] +#define IN_DtX prhs[2] +#define IN_G prhs[3] +#define IN_T prhs[4] +#define IN_SPARSE_G prhs[5] +#define IN_MSGDELTA prhs[6] +#define IN_PROFILE prhs[7] + + +/* Output Arguments */ + +#define GAMMA_OUT plhs[0] + + +/***************************************************************************************/ + + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) + +{ + double *D, *x, *DtX, *G, msgdelta; + int gmode, profile, T; + mwSize m, n, L; /* D is n x m , X is n x L, DtX is m x L */ + + + /* check parameters */ + + checkmatrix(IN_D, "OMP", "D"); + checkmatrix(IN_X, "OMP", "X"); + checkmatrix(IN_DtX, "OMP", "DtX"); + checkmatrix(IN_G, "OMP", "G"); + + checkscalar(IN_T, "OMP", "T"); + checkscalar(IN_SPARSE_G, "OMP", "sparse_g"); + checkscalar(IN_MSGDELTA, "OMP", "msgdelta"); + checkscalar(IN_PROFILE, "OMP", "profile"); + + + /* get parameters */ + + x = D = DtX = G = 0; + + if (!mxIsEmpty(IN_D)) + D = mxGetPr(IN_D); + + if (!mxIsEmpty(IN_X)) + x = mxGetPr(IN_X); + + if (!mxIsEmpty(IN_DtX)) + DtX = mxGetPr(IN_DtX); + + if (!mxIsEmpty(IN_G)) + G = mxGetPr(IN_G); + + T = (int)(mxGetScalar(IN_T)+1e-2); + if ((int)(mxGetScalar(IN_SPARSE_G)+1e-2)) { + gmode = SPARSE_GAMMA; + } + else { + gmode = FULL_GAMMA; + } + msgdelta = mxGetScalar(IN_MSGDELTA); + profile = (int)(mxGetScalar(IN_PROFILE)+1e-2); + + + /* check sizes */ + + if (D && x) { + n = mxGetM(IN_D); + m = mxGetN(IN_D); + L = mxGetN(IN_X); + + if (mxGetM(IN_X) != n) { + mexErrMsgTxt("D and X have incompatible sizes."); + } + + if (G) { + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("D and G have incompatible sizes."); + } + } + } + + else if (DtX) { + m = mxGetM(IN_DtX); + L = mxGetN(IN_DtX); + + n = T; /* arbitrary - it is enough to assume signal length is T */ + + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("DtX and G have incompatible sizes."); + } + } + + else { + mexErrMsgTxt("Either D and X, or DtX, must be specified."); + } + + + /* Do OMP! */ + + GAMMA_OUT = ompcore(D, x, DtX, 0, G, n, m, L, T, 0, gmode, profile, msgdelta, 0); + + return; +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompmex.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,22 @@ +%This is the Matlab interface to the OMP MEX implementation. +%The function is not for independent use, only through omp.m. + + +%OMPMEX Matlab interface to the OMP MEX implementation. +% GAMMA = OMPMEX(D,X,DtX,G,L,SPARSE_G,MSGDELTA,PROFILE) invokes the OMP +% MEX function according to the specified parameters. Not all the +% parameters are required. Those among D, X, DtX and G which are not +% specified should be passed as []. +% +% L - the target sparsity. +% SPARSE_G - returns a sparse GAMMA when nonzero, full GAMMA when zero. +% MSGDELTA - the delay in secs between messages. Zero means no messages. +% PROFILE - nonzero means that profiling information should be printed. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2009
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompmexGabor.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,133 @@ +/************************************************************************** + * + * File name: ompmex.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + *************************************************************************/ + +#include "ompcoreGabor.h" +#include "omputils.h" +#include "mexutils.h" + + +/* Input Arguments */ + +#define IN_D prhs[0] +#define IN_X prhs[1] +#define IN_DtX prhs[2] +#define IN_G prhs[3] +#define IN_T prhs[4] +#define IN_SPARSE_G prhs[5] +#define IN_MSGDELTA prhs[6] +#define IN_PROFILE prhs[7] + + +/* Output Arguments */ + +#define GAMMA_OUT plhs[0] + + +/***************************************************************************************/ + + +void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) + +{ + double *D, *x, *DtX, *G, msgdelta; + int gmode, profile, T; + mwSize m, n, L; /* D is n x m , X is n x L, DtX is m x L */ + + + /* check parameters */ + + checkmatrix(IN_D, "OMP", "D"); + checkmatrix(IN_X, "OMP", "X"); + checkmatrix(IN_DtX, "OMP", "DtX"); + checkmatrix(IN_G, "OMP", "G"); + + checkscalar(IN_T, "OMP", "T"); + checkscalar(IN_SPARSE_G, "OMP", "sparse_g"); + checkscalar(IN_MSGDELTA, "OMP", "msgdelta"); + checkscalar(IN_PROFILE, "OMP", "profile"); + + + /* get parameters */ + + x = D = DtX = G = 0; + + if (!mxIsEmpty(IN_D)) + D = mxGetPr(IN_D); + + if (!mxIsEmpty(IN_X)) + x = mxGetPr(IN_X); + + if (!mxIsEmpty(IN_DtX)) + DtX = mxGetPr(IN_DtX); + + if (!mxIsEmpty(IN_G)) + G = mxGetPr(IN_G); + + T = (int)(mxGetScalar(IN_T)+1e-2); + if ((int)(mxGetScalar(IN_SPARSE_G)+1e-2)) { + gmode = SPARSE_GAMMA; + } + else { + gmode = FULL_GAMMA; + } + msgdelta = mxGetScalar(IN_MSGDELTA); + profile = (int)(mxGetScalar(IN_PROFILE)+1e-2); + + + /* check sizes */ + + if (D && x) { + n = mxGetM(IN_D); + m = mxGetN(IN_D); + L = mxGetN(IN_X); + + if (mxGetM(IN_X) != n) { + mexErrMsgTxt("D and X have incompatible sizes."); + } + + if (G) { + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("D and G have incompatible sizes."); + } + } + } + + else if (DtX) { + m = mxGetM(IN_DtX); + L = mxGetN(IN_DtX); + + n = T; /* arbitrary - it is enough to assume signal length is T */ + + if (mxGetN(IN_G)!=mxGetM(IN_G)) { + mexErrMsgTxt("G must be a square matrix."); + } + if (mxGetN(IN_G) != m) { + mexErrMsgTxt("DtX and G have incompatible sizes."); + } + } + + else { + mexErrMsgTxt("Either D and X, or DtX, must be specified."); + } + + + /* Do OMP! */ + + GAMMA_OUT = ompcoreGabor(D, x, DtX, 0, G, n, m, L, T, 0, gmode, profile, msgdelta, 0); + + return; +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompmexGabor.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,22 @@ +%This is the Matlab interface to the OMP MEX implementation. +%The function is not for independent use, only through omp.m. + + +%OMPMEX Matlab interface to the OMP MEX implementation. +% GAMMA = OMPMEXGABOR(D,X,DtX,G,L,SPARSE_G,MSGDELTA,PROFILE) invokes the OMP +% MEX function according to the specified parameters. Not all the +% parameters are required. Those among D, X, DtX and G which are not +% specified should be passed as []. +% +% L - the target sparsity. +% SPARSE_G - returns a sparse GAMMA when nonzero, full GAMMA when zero. +% MSGDELTA - the delay in secs between messages. Zero means no messages. +% PROFILE - nonzero means that profiling information should be printed. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2009
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompprof.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,113 @@ +/************************************************************************** + * + * File name: ompprof.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 11.4.2009 + * + *************************************************************************/ + + +#include "ompprof.h" + + +/* initialize profiling information */ + +void initprofdata(profdata *pd) +{ + pd->DtX_time = 0; + pd->XtX_time = 0; + pd->DtR_time = 0; + pd->maxabs_time = 0; + pd->DtD_time = 0; + pd->Lchol_time = 0; + pd->compcoef_time = 0; + pd->update_DtR_time = 0; + pd->update_resnorm_time = 0; + pd->compres_time = 0; + pd->indexsort_time = 0; + + pd->DtX_time_counted = 0; + pd->XtX_time_counted = 0; + pd->DtR_time_counted = 0; + pd->DtD_time_counted = 0; + pd->update_DtR_time_counted = 0; + pd->resnorm_time_counted = 0; + pd->compres_time_counted = 0; + pd->indexsort_time_counted = 0; + + pd->prevtime = clock(); +} + + +/* add elapsed time to profiling data according to specified computation */ + +void addproftime(profdata *pd, int comptype) +{ + switch(comptype) { + case DtX_TIME: pd->DtX_time += clock()-pd->prevtime; pd->DtX_time_counted = 1; break; + case XtX_TIME: pd->XtX_time += clock()-pd->prevtime; pd->XtX_time_counted = 1; break; + case DtR_TIME: pd->DtR_time += clock()-pd->prevtime; pd->DtR_time_counted = 1; break; + case DtD_TIME: pd->DtD_time += clock()-pd->prevtime; pd->DtD_time_counted = 1; break; + case COMPRES_TIME: pd->compres_time += clock()-pd->prevtime; pd->compres_time_counted = 1; break; + case UPDATE_DtR_TIME: pd->update_DtR_time += clock()-pd->prevtime; pd->update_DtR_time_counted = 1; break; + case UPDATE_RESNORM_TIME: pd->update_resnorm_time += clock()-pd->prevtime; pd->resnorm_time_counted = 1; break; + case INDEXSORT_TIME: pd->indexsort_time += clock()-pd->prevtime; pd->indexsort_time_counted = 1; break; + case MAXABS_TIME: pd->maxabs_time += clock()-pd->prevtime; break; + case LCHOL_TIME: pd->Lchol_time += clock()-pd->prevtime; break; + case COMPCOEF_TIME: pd->compcoef_time += clock()-pd->prevtime; break; + } + pd->prevtime = clock(); +} + + +/* print profiling info */ + +void printprofinfo(profdata *pd, int erroromp, int batchomp, int signum) +{ + clock_t tottime; + + tottime = pd->DtX_time + pd->XtX_time + pd->DtR_time + pd->DtD_time + pd->compres_time + pd->maxabs_time + + pd->Lchol_time + pd->compcoef_time + pd->update_DtR_time + pd->update_resnorm_time + pd->indexsort_time; + + mexPrintf("\n\n***** Profiling information for %s *****\n\n", erroromp? "OMP2" : "OMP"); + + mexPrintf("OMP mode: %s\n\n", batchomp? "Batch-OMP" : "OMP-Cholesky"); + + mexPrintf("Total signals processed: %d\n\n", signum); + + if (pd->DtX_time_counted) { + mexPrintf("Compute DtX time: %7.3lf seconds\n", pd->DtX_time/(double)CLOCKS_PER_SEC); + } + if (pd->XtX_time_counted) { + mexPrintf("Compute XtX time: %7.3lf seconds\n", pd->XtX_time/(double)CLOCKS_PER_SEC); + } + mexPrintf("Max abs time: %7.3lf seconds\n", pd->maxabs_time/(double)CLOCKS_PER_SEC); + if (pd->DtD_time_counted) { + mexPrintf("Compute DtD time: %7.3lf seconds\n", pd->DtD_time/(double)CLOCKS_PER_SEC); + } + mexPrintf("Lchol update time: %7.3lf seconds\n", pd->Lchol_time/(double)CLOCKS_PER_SEC); + mexPrintf("Compute coef time: %7.3lf seconds\n", pd->compcoef_time/(double)CLOCKS_PER_SEC); + if (pd->compres_time_counted) { + mexPrintf("Compute R time: %7.3lf seconds\n", pd->compres_time/(double)CLOCKS_PER_SEC); + } + if (pd->DtR_time_counted) { + mexPrintf("Compute DtR time: %7.3lf seconds\n", pd->DtR_time/(double)CLOCKS_PER_SEC); + } + if (pd->update_DtR_time_counted) { + mexPrintf("Update DtR time: %7.3lf seconds\n", pd->update_DtR_time/(double)CLOCKS_PER_SEC); + } + if (pd->resnorm_time_counted) { + mexPrintf("Update resnorm time: %7.3lf seconds\n", pd->update_resnorm_time/(double)CLOCKS_PER_SEC); + } + if (pd->indexsort_time_counted) { + mexPrintf("Index sort time: %7.3lf seconds\n", pd->indexsort_time/(double)CLOCKS_PER_SEC); + } + mexPrintf("---------------------------------------\n"); + mexPrintf("Total time: %7.3lf seconds\n\n", tottime/(double)CLOCKS_PER_SEC); +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/ompprof.h Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,106 @@ +/************************************************************************** + * + * File name: ompprof.h + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + * Collection of definitions and functions for profiling the OMP method. + * + *************************************************************************/ + + +#ifndef __OMP_PROF_H__ +#define __OMP_PROF_H__ + +#include "mex.h" +#include <time.h> + + + +/************************************************************************** + * + * Constants and data types. + * + **************************************************************************/ + + +/* constants denoting the various parts of the algorithm */ + +enum { DtX_TIME, XtX_TIME, DtR_TIME, MAXABS_TIME, DtD_TIME, LCHOL_TIME, COMPCOEF_TIME, + UPDATE_DtR_TIME, UPDATE_RESNORM_TIME, COMPRES_TIME, INDEXSORT_TIME }; + + + +/* profiling data container with counters for each part of the algorithm */ + +typedef struct profdata +{ + clock_t prevtime; /* the time when last initialization/call to addproftime() was performed */ + + clock_t DtX_time; + clock_t XtX_time; + clock_t DtR_time; + clock_t maxabs_time; + clock_t DtD_time; + clock_t Lchol_time; + clock_t compcoef_time; + clock_t update_DtR_time; + clock_t update_resnorm_time; + clock_t compres_time; + clock_t indexsort_time; + + /* flags indicating whether profiling data was gathered */ + int DtX_time_counted; + int XtX_time_counted; + int DtR_time_counted; + int DtD_time_counted; + int update_DtR_time_counted; + int resnorm_time_counted; + int compres_time_counted; + int indexsort_time_counted; + +} profdata; + + + +/************************************************************************** + * + * Initialize a profdata structure, zero all counters, and start its timer. + * + **************************************************************************/ +void initprofdata(profdata *pd); + + +/************************************************************************** + * + * Add elapsed time from last call to addproftime(), or from initialization + * of profdata, to the counter specified by comptype. comptype must be one + * of the constants in the enumeration above. + * + **************************************************************************/ +void addproftime(profdata *pd, int comptype); + + +/************************************************************************** + * + * Print the current contents of the counters in profdata. + * + * Parameters: + * pd - the profdata to print + * erroromp - indicates whether error-based (nonzero) or sparsity-based (zero) + * omp was performed. + * batchomp - indicates whether batch-omp (nonzero) or omp-cholesky (zero) + * omp was performed. + * signum - number of signals processed by omp + * + **************************************************************************/ +void printprofinfo(profdata *pd, int erroromp, int batchomp, int signum); + + +#endif +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omputils.c Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,89 @@ +/************************************************************************** + * + * File name: omputils.c + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + *************************************************************************/ + +#include "omputils.h" +#include <math.h> + + +const char FULL_GAMMA_STR[] = "full"; +const char SPARSE_GAMMA_STR[] = "sparse"; + + +/* convert seconds to hours, minutes and seconds */ + +void secs2hms(double sectot, int *hrs, int *mins, double *secs) +{ + *hrs = (int)(floor(sectot/3600)+1e-2); + sectot = sectot - 3600*(*hrs); + *mins = (int)(floor(sectot/60)+1e-2); + *secs = sectot - 60*(*mins); +} + + +/* quicksort, public-domain C implementation by Darel Rex Finley. */ +/* modification: sorts the array data[] as well, according to the values in the array vals[] */ + +#define MAX_LEVELS 300 + +void quicksort(mwIndex vals[], double data[], mwIndex n) { + + long piv, beg[MAX_LEVELS], end[MAX_LEVELS], i=0, L, R, swap ; + double datapiv; + + beg[0]=0; + end[0]=n; + + while (i>=0) { + + L=beg[i]; + R=end[i]-1; + + if (L<R) { + + piv=vals[L]; + datapiv=data[L]; + + while (L<R) + { + while (vals[R]>=piv && L<R) + R--; + if (L<R) { + vals[L]=vals[R]; + data[L++]=data[R]; + } + + while (vals[L]<=piv && L<R) + L++; + if (L<R) { + vals[R]=vals[L]; + data[R--]=data[L]; + } + } + + vals[L]=piv; + data[L]=datapiv; + + beg[i+1]=L+1; + end[i+1]=end[i]; + end[i++]=L; + + if (end[i]-beg[i] > end[i-1]-beg[i-1]) { + swap=beg[i]; beg[i]=beg[i-1]; beg[i-1]=swap; + swap=end[i]; end[i]=end[i-1]; end[i-1]=swap; + } + } + else { + i--; + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/omputils.h Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,77 @@ +/************************************************************************** + * + * File name: omputils.h + * + * Ron Rubinstein + * Computer Science Department + * Technion, Haifa 32000 Israel + * ronrubin@cs + * + * Last Updated: 18.8.2009 + * + * Utility definitions and functions for the OMP library. + * + *************************************************************************/ + + +#ifndef __OMP_UTILS_H__ +#define __OMP_UTILS_H__ + +#include "mex.h" + + +/* constants for the representation mode of gamma */ + +extern const char FULL_GAMMA_STR[]; /* "full" */ +extern const char SPARSE_GAMMA_STR[]; /* "sparse" */ + + +#define FULL_GAMMA 1 +#define SPARSE_GAMMA 2 +#define INVALID_MODE 3 + + + +/************************************************************************** + * Memory management for OMP2. + * + * GAMMA_INC_FACTOR: + * The matrix GAMMA is allocated with sqrt(n)/2 coefficients per signal, + * for a total of nzmax = L*sqrt(n)/2 nonzeros. Whenever GAMMA needs to be + * increased, it is increased by a factor of GAMMA_INC_FACTOR. + * + * MAT_INC_FACTOR: + * The matrices Lchol, Gsub and Dsub are allocated with sqrt(n)/2 + * columns each. If additional columns are needed, this number is + * increased by a factor of MAT_INC_FACTOR. + **************************************************************************/ + +#define GAMMA_INC_FACTOR (1.4) +#define MAT_INC_FACTOR (1.6) + + + +/************************************************************************** + * Convert number of seconds to hour, minute and second representation. + * + * Parameters: + * sectot - total number of seconds + * hrs, mins, secs - output hours (whole) and minutes (whole) and seconds + * + **************************************************************************/ +void secs2hms(double sectot, int *hrs, int *mins, double *secs); + + + +/************************************************************************** + * QuickSort - public-domain C implementation by Darel Rex Finley. + * + * Modified to sort both the array vals[] and the array data[] according + * to the values in the array vals[]. + * + **************************************************************************/ +void quicksort(mwIndex vals[], double data[], mwIndex n); + + +#endif +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/solvers/SMALL_ompGabor/printf.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,26 @@ +function str = printf(varargin) +%PRINTF Print formatted text to screen. +% PRINTF(FMT,VAL1,VAL2,...) formats the data in VAL1,VAL2,... according to +% the format string FMT, and prints the result to the screen. +% +% The call to PRINTF(FMT,VAL1,VAL2,...) simply invokes the call +% DISP(SPRINTF(FMT,VAL1,VAL2,...)). For a complete description of the +% format string options see function SPRINTF. +% +% STR = PRINTF(...) also returns the formatted string. + + +% Ron Rubinstein +% Computer Science Department +% Technion, Haifa 32000 Israel +% ronrubin@cs +% +% April 2008 + + +if (nargout>0) + str = sprintf(varargin{:}); + disp(str); +else + disp(sprintf(varargin{:})); +end
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Experiments/DeclippingExperiment/declipOneSoundExperiment.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,123 @@ +function declipOneSoundExperiment(expParam) +% A simple experiment to declip a signal. +% +% Usage: declipOneSoundExperiment(expParam) +% +% +% Inputs: +% - expParam is an optional structure where the user can define +% the experiment parameters. +% - expParam.clippingLevel: clipping level between 0 and 1. +% - expParam.filename: file to be tested. +% - expParam.destDir: path to store the results. +% - expParam.solver: solver with its parameters +% - expParam.destDir: path to store the results. +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +if ~isdeployed + close all + addpath('../../Problems/'); + addpath('../../Solvers/'); + addpath('../../Utils/'); + addpath('../../Utils/dictionaries/'); + addpath('../../Utils/evaluation/'); +% addpath('../../Utils/TCPIP_SocketCom/'); +% javaaddpath('../../Utils/TCPIP_SocketCom'); + dbstop if error +end + +%% Set parameters +if nargin<1 + expParam = []; +end +if ~isfield(expParam,'filename') + expParam.filename = 'male01_8kHz.wav'; +end +if ~isfield(expParam,'clippingLevel') + expParam.clippingLevel = 0.6; +end + +% Solver +if ~isfield(expParam,'solver') + warning('AITB:N','Frame length=256 is used to have faster computations. Recommended frame length is 512 at 8kHz.'); + warning('AITB:overlap','Overlap factor=2 is used to have faster computations. Recommended value: 4.'); + + expParam.solver.name = 'OMP-G'; + expParam.solver.function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solver.param.N = 512; % frame length + expParam.solver.param.N = 256; % frame length + expParam.solver.param.inpaintFrame = @inpaintFrame_consOMP_Gabor; % solver function + expParam.solver.param.OMPerr = 0.001; + expParam.solver.param.sparsityDegree = expParam.solver.param.N/4; + expParam.solver.param.D_fun = @Gabor_Dictionary; % Dictionary (function handle) + expParam.solver.param.OLA_frameOverlapFactor = 4; + expParam.solver.param.OLA_frameOverlapFactor = 2; + expParam.solver.param.redundancyFactor = 2; % Dictionary redundancy + expParam.solver.param.wd = @wRect; % Weighting window for dictionary atoms + expParam.solver.param.wa = @wRect; % Analysis window + expParam.solver.param.OLA_ws = @wSine; % Synthesis window + expParam.solver.param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solver.param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet +end +if ~isfield(expParam,'destDir'), + expParam.destDir = '../../tmp/declipOneSound/'; +end +if ~exist(expParam.destDir,'dir') + mkdir(expParam.destDir) +end + +%% Read test signal +[x fs] = wavread(expParam.filename); + +%% Generate the problem +[problemData, solutionData] = generateDeclippingProblem(x,expParam.clippingLevel); + +%% Declip with solver +fprintf('\nDeclipping\n') +% [xEst1 xEst2] = inpaintSignal_IndependentProcessingOfFrames(problemData,param); +solverParam = expParam.solver.param; +[xEst1 xEst2] = expParam.solver.function(problemData,solverParam); + +%% Compute and display SNR performance +L = length(xEst1); +N = expParam.solver.param.N; +[SNRAll, SNRmiss] = SNRInpaintingPerformance(... + solutionData.xClean(N:L-N),problemData.x(N:L-N),... + xEst2(N:L-N),problemData.IMiss(N:L-N)); +fprintf('SNR on missing samples:\n'); +fprintf('Clipped: %g dB\n',SNRmiss(1)); +fprintf('Estimate: %g dB\n',SNRmiss(2)); + + +% Plot results +xClipped = problemData.x; +xClean = solutionData.xClean; +figure +hold on +plot(xClipped,'r') +plot(xClean) +plot(xEst2,'--g') +plot([1;length(xClipped)],[1;1]*[-1,1]*max(abs(xClipped)),':r') +legend('Clipped','True solution','Estimate') + +% Normalized and save sounds +normX = 1.1*max(abs([xEst1(:);xEst2(:);xClean(:)])); +L = min([length(xEst2),length(xEst1),length(xClean),length(xEst1),length(xClipped)]); +xEst1 = xEst1(1:L)/normX; +xEst2 = xEst2(1:L)/normX; +xClipped = xClipped(1:L)/normX; +xClean = xClean(1:L)/normX; +wavwrite(xEst1,fs,[expParam.destDir 'xEst1.wav']); +wavwrite(xEst2,fs,[expParam.destDir 'xEst2.wav']); +wavwrite(xClipped,fs,[expParam.destDir 'xClipped.wav']); +wavwrite(xClean,fs,[expParam.destDir 'xClean.wav']); + + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Experiments/DeclippingExperiment/declipOneSoundExperiment.m~ Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,123 @@ +function declipOneSoundExperiment(expParam) +% A simple experiment to declip a signal. +% +% Usage: declipOneSoundExperiment(expParam) +% +% +% Inputs: +% - expParam is an optional structure where the user can define +% the experiment parameters. +% - expParam.clippingLevel: clipping level between 0 and 1. +% - expParam.filename: file to be tested. +% - expParam.destDir: path to store the results. +% - expParam.solver: solver with its parameters +% - expParam.destDir: path to store the results. +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +if ~isdeployed + close all + addpath('../../Problems/'); + addpath('../../Solvers/'); + addpath('../../Utils/'); + addpath('../../Utils/dictionaries/'); + addpath('../../Utils/evaluation/'); +% addpath('../../Utils/TCPIP_SocketCom/'); +% javaaddpath('../../Utils/TCPIP_SocketCom'); + dbstop if error +end + +%% Set parameters +if nargin<1 + expParam = []; +end +if ~isfield(expParam,'filename') + expParam.filename = 'male01_8kHz.wav'; +end +if ~isfield(expParam,'clippingLevel') + expParam.clippingLevel = 0.6; +end + +% Solver +if ~isfield(expParam,'solver') + warning('AITB:N','Frame length=256 is used to have faster computations. Recommended frame length is 512 at 8kHz.'); + warning('AITB:overlap','Overlap factor=2 is used to have faster computations. Recommended value: 4.'); + + expParam.solver.name = 'OMP-G'; + expParam.solver.function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solver.param.N = 512; % frame length + expParam.solver.param.N = 256; % frame length + expParam.solver.param.inpaintFrame = @inpaintFrame_OMP_Gabor; % solver function + expParam.solver.param.OMPerr = 0.001; + expParam.solver.param.sparsityDegree = expParam.solver.param.N/4; + expParam.solver.param.D_fun = @Gabor_Dictionary; % Dictionary (function handle) + expParam.solver.param.OLA_frameOverlapFactor = 4; + expParam.solver.param.OLA_frameOverlapFactor = 2; + expParam.solver.param.redundancyFactor = 2; % Dictionary redundancy + expParam.solver.param.wd = @wRect; % Weighting window for dictionary atoms + expParam.solver.param.wa = @wRect; % Analysis window + expParam.solver.param.OLA_ws = @wSine; % Synthesis window + expParam.solver.param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solver.param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet +end +if ~isfield(expParam,'destDir'), + expParam.destDir = '../../tmp/declipOneSound/'; +end +if ~exist(expParam.destDir,'dir') + mkdir(expParam.destDir) +end + +%% Read test signal +[x fs] = wavread(expParam.filename); + +%% Generate the problem +[problemData, solutionData] = generateDeclippingProblem(x,expParam.clippingLevel); + +%% Declip with solver +fprintf('\nDeclipping\n') +% [xEst1 xEst2] = inpaintSignal_IndependentProcessingOfFrames(problemData,param); +solverParam = expParam.solver.param; +[xEst1 xEst2] = expParam.solver.function(problemData,solverParam); + +%% Compute and display SNR performance +L = length(xEst1); +N = expParam.solver.param.N; +[SNRAll, SNRmiss] = SNRInpaintingPerformance(... + solutionData.xClean(N:L-N),problemData.x(N:L-N),... + xEst2(N:L-N),problemData.IMiss(N:L-N)); +fprintf('SNR on missing samples:\n'); +fprintf('Clipped: %g dB\n',SNRmiss(1)); +fprintf('Estimate: %g dB\n',SNRmiss(2)); + + +% Plot results +xClipped = problemData.x; +xClean = solutionData.xClean; +figure +hold on +plot(xClipped,'r') +plot(xClean) +plot(xEst2,'--g') +plot([1;length(xClipped)],[1;1]*[-1,1]*max(abs(xClipped)),':r') +legend('Clipped','True solution','Estimate') + +% Normalized and save sounds +normX = 1.1*max(abs([xEst1(:);xEst2(:);xClean(:)])); +L = min([length(xEst2),length(xEst1),length(xClean),length(xEst1),length(xClipped)]); +xEst1 = xEst1(1:L)/normX; +xEst2 = xEst2(1:L)/normX; +xClipped = xClipped(1:L)/normX; +xClean = xClean(1:L)/normX; +wavwrite(xEst1,fs,[expParam.destDir 'xEst1.wav']); +wavwrite(xEst2,fs,[expParam.destDir 'xEst2.wav']); +wavwrite(xClipped,fs,[expParam.destDir 'xClipped.wav']); +wavwrite(xClean,fs,[expParam.destDir 'xClean.wav']); + + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Experiments/DeclippingExperiment/declippingExperiment.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,211 @@ +function declippingExperiment(expParam) +% Declip several sounds with different clipping levels, using several +% solvers. +% +% Usage: declippingExperiment(expParam) +% +% +% Inputs: +% - expParam is an optional structure where the user can define +% the experiment parameters. +% - expParam.clippingScale: clipping values to test, as a vector +% of real numbers in ]0,1[. +% - expParam.soundDir: path to sound directory. All the .wav files +% in this directory will be tested. +% - expParam.destDir: path to store the results. +% - expParam.solvers: list of solvers with their parameters +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +if ~isdeployed + addpath('../../Problems/'); + addpath('../../Solvers/'); + addpath('../../Utils/'); + addpath('../../Utils/dictionaries/'); + addpath('../../Utils/evaluation/'); +% addpath('../../Utils/TCPIP_SocketCom/'); +% javaaddpath('../../Utils/TCPIP_SocketCom'); + dbstop if error + close all +end + +if nargin<1 + expParam = []; +end +if ~isfield(expParam,'clippingScale'), + expParam.clippingScale = 0.4:0.2:0.8; +end +if ~isfield(expParam,'soundDir'), + expParam.soundDir = '../../Data/testSpeech8kHz_from16kHz/'; + expParam.soundDir = '../../Data/shortTest/'; + warning('AITB:soundDir','soundDir has only one sound to have faster computations. Recommended soundDir: ../../Data/testSpeech8kHz_from16kHz/'); +end +if ~isfield(expParam,'destDir'), + expParam.destDir = '../../tmp/declip/'; +end + +%% Set parameters + +if ~isfield(expParam,'solvers'), + % Choose the solver methods you would like to test: OMP, L1, Janssen + warning('AITB:N','Frame length=256 is used to have faster computations. Recommended frame length is 512 at 8kHz.'); + warning('AITB:overlap','Overlap factor=2 is used to have faster computations. Recommended value: 4.'); + nSolver = 0; + + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'OMP-C'; + expParam.solvers(nSolver).function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solvers(nSolver).param.N = 512; % frame length + expParam.solvers(nSolver).param.N = 256; % frame length + expParam.solvers(nSolver).param.inpaintFrame = @inpaintFrame_OMP; % solver function + expParam.solvers(nSolver).param.OMPerr = 0.001; + expParam.solvers(nSolver).param.sparsityDegree = expParam.solvers(nSolver).param.N/4; + expParam.solvers(nSolver).param.D_fun = @DCT_Dictionary; % Dictionary (function handle) + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 4; + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 2; + expParam.solvers(nSolver).param.redundancyFactor = 2; % Dictionary redundancy + expParam.solvers(nSolver).param.wd = @wRect; % Weighting window for dictionary atoms + expParam.solvers(nSolver).param.wa = @wRect; % Analysis window + expParam.solvers(nSolver).param.OLA_ws = @wSine; % Synthesis window + expParam.solvers(nSolver).param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solvers(nSolver).param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet + + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'consOMP-C'; + expParam.solvers(nSolver).function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solvers(nSolver).param.N = 512; % frame length + expParam.solvers(nSolver).param.N = 256; % frame length + expParam.solvers(nSolver).param.inpaintFrame = @inpaintFrame_consOMP; % solver function + expParam.solvers(nSolver).param.OMPerr = 0.001; + expParam.solvers(nSolver).param.sparsityDegree = expParam.solvers(nSolver).param.N/4; + expParam.solvers(nSolver).param.D_fun = @DCT_Dictionary; % Dictionary (function handle) + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 4; + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 2; + expParam.solvers(nSolver).param.redundancyFactor = 2; % Dictionary redundancy + expParam.solvers(nSolver).param.wd = @wRect; % Weighting window for dictionary atoms + expParam.solvers(nSolver).param.wa = @wRect; % Analysis window + expParam.solvers(nSolver).param.OLA_ws = @wSine; % Synthesis window + expParam.solvers(nSolver).param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solvers(nSolver).param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet + + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'OMP-G'; + expParam.solvers(nSolver).function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solvers(nSolver).param.N = 512; % frame length + expParam.solvers(nSolver).param.N = 256; % frame length + expParam.solvers(nSolver).param.inpaintFrame = @inpaintFrame_OMP_Gabor; % solver function + expParam.solvers(nSolver).param.OMPerr = 0.001; + expParam.solvers(nSolver).param.sparsityDegree = expParam.solvers(nSolver).param.N/4; + expParam.solvers(nSolver).param.D_fun = @Gabor_Dictionary; % Dictionary (function handle) + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 4; + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 2; + expParam.solvers(nSolver).param.redundancyFactor = 2; % Dictionary redundancy + expParam.solvers(nSolver).param.wd = @wRect; % Weighting window for dictionary atoms + expParam.solvers(nSolver).param.wa = @wRect; % Analysis window + expParam.solvers(nSolver).param.OLA_ws = @wSine; % Synthesis window + expParam.solvers(nSolver).param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solvers(nSolver).param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet + + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'consOMP-G'; + expParam.solvers(nSolver).function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solvers(nSolver).param.N = 512; % frame length + expParam.solvers(nSolver).param.N = 256; % frame length + expParam.solvers(nSolver).param.inpaintFrame = @inpaintFrame_consOMP_Gabor; % solver function + expParam.solvers(nSolver).param.OMPerr = 0.001; + expParam.solvers(nSolver).param.sparsityDegree = expParam.solvers(nSolver).param.N/4; + expParam.solvers(nSolver).param.D_fun = @Gabor_Dictionary; % Dictionary (function handle) + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 4; + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 2 + expParam.solvers(nSolver).param.redundancyFactor = 2; % Dictionary redundancy + expParam.solvers(nSolver).param.wd = @wRect; % Weighting window for dictionary atoms + expParam.solvers(nSolver).param.wa = @wRect; % Analysis window + expParam.solvers(nSolver).param.OLA_ws = @wSine; % Synthesis window + expParam.solvers(nSolver).param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solvers(nSolver).param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet + + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'Janssen'; + expParam.solvers(nSolver).function = @inpaintSignal_IndependentProcessingOfFrames; + expParam.solvers(nSolver).param.inpaintFrame = @inpaintFrame_janssenInterpolation; % solver function + expParam.solvers(nSolver).param.N = 512; % frame length + expParam.solvers(nSolver).param.N = 256; + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 4; + expParam.solvers(nSolver).param.OLA_frameOverlapFactor = 2 + expParam.solvers(nSolver).param.wa = @wRect; % Analysis window + expParam.solvers(nSolver).param.OLA_ws = @wSine; % Synthesis window + expParam.solvers(nSolver).param.SKIP_CLEAN_FRAMES = true; % do not process frames where there is no missing samples + expParam.solvers(nSolver).param.MULTITHREAD_FRAME_PROCESSING = false; % not implemented yet +end + +SNRClip = zeros(0,0,0); +fprintf('Folder %s\n',expParam.soundDir); +if ~exist(expParam.destDir,'dir') + mkdir(expParam.destDir) +end +soundFiles = dir([expParam.soundDir '*.wav']); + +for kf = 1:length(soundFiles) + soundfile = [expParam.soundDir soundFiles(kf).name]; + fprintf(' File %s\n',soundfile); + %% Read test signal + [x fs] = wavread(soundfile); + + for kClip = 1:length(expParam.clippingScale) + clippingLevel = expParam.clippingScale(kClip); + fprintf(' Clip level %g\n',clippingLevel); + + %% Generate the problem + [problemData, solutionData] = generateDeclippingProblem(x,clippingLevel); + + for nSolver = 1:length(expParam.solvers) + %% Declip with solver + solverParam = expParam.solvers(nSolver).param; + [xEst1 xEst2] = expParam.solvers(nSolver).function(problemData,solverParam); + + %% compute performance + L = length(xEst1); + N = solverParam.N; + [SNRAll, SNRmiss] = ... + SNRInpaintingPerformance(... + solutionData.xClean(N:L-N),... + problemData.x(N:L-N),... + xEst2(N:L-N),... + problemData.IMiss(N:L-N)); + SNRClip(kf,kClip,nSolver) = SNRmiss(2); + + % normalize and save both the reference and the estimates! + normX = 1.1*max(abs([xEst1(:);xEst2(:);solutionData.xClean(:)])); + + L = min([length(xEst2),length(xEst1),length(solutionData.xClean),length(problemData.x)]); + xEst1 = xEst1(1:L)/normX; + xEst2 = xEst2(1:L)/normX; + xClipped = problemData.x(1:L)/normX; + xClean = solutionData.xClean(1:L)/normX; + wavwrite(xEst1,fs,sprintf('%s%s%s%g.wav',expParam.destDir,soundFiles(kf).name(1:end-4),'Est1',clippingLevel)); + wavwrite(xEst2,fs,sprintf('%s%s%s%g.wav',expParam.destDir,soundFiles(kf).name(1:end-4),'Est2',clippingLevel)); + wavwrite(xClipped,fs,sprintf('%s%s%s%g.wav',expParam.destDir,soundFiles(kf).name(1:end-4),'Clipped',clippingLevel)); + wavwrite(xClean,fs,sprintf('%s%s%s%g.wav',expParam.destDir,soundFiles(kf).name(1:end-4),'Ref',clippingLevel)); + + fprintf('\n'); + clear a xEst1 xEst2 xClipped xClean IClipped + save([expParam.destDir 'clippingExp.mat']); + end + end +end + +%% Plot results +averageSNR = squeeze(mean(SNRClip,1)); +disp(averageSNR) +figure, +plot(averageSNR) +legend(arrayfun(@(x)x.name,expParam.solvers,'UniformOutput',false)); +xlabel('Clipping level') +ylabel('SNR') +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Experiments/MissingSampleTopologyExperiment/MissingSampleTopologyExperiment.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,223 @@ +function MissingSampleTopologyExperiment(expParam) +% For a total number of missing samples C in a frame, create several +% configuration of B holes with length A, where A*B=C (i.e. the total +% number of missing samples is constant). Test several values of C, several +% solvers. For each C, test all possible combination of (A,B) such that +% A*B=C. +% Note that for each combination (A,B), a number of frames are tested at +% random and SNR results are then averaged. +% +% Usage: MissingSampleTopologyExperiment(expParam) +% +% +% Inputs: +% - expParam is an optional structure where the user can define +% the experiment parameters. +% - expParam.soundDir: path to sound directory. All the .wav files +% in this directory will be tested at random. +% - expParam.destDir: path to store the results. +% - expParam.N: frame length +% - expParam.NFramesPerHoleSize: number of frames to use for each +% testing configuration (A,B). Results are then averaged. +% - expParam.totalMissSamplesList: list of all tested values C for +% the total number of missing samples in a frame +% - expParam.solvers: list of solvers with their parameters +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +if ~isdeployed + addpath('../../Problems/'); + addpath('../../Solvers/'); + addpath('../../Utils/'); + addpath('../../Utils/dictionaries/'); + addpath('../../Utils/evaluation/'); +% addpath('../../Utils/TCPIP_SocketCom/'); +% javaaddpath('../../Utils/TCPIP_SocketCom'); + dbstop if error + close all +end + +%% Set parameters +if nargin<1 + expParam = []; +end +% Path to audio files +if ~isfield(expParam,'soundDir'), + expParam.soundDir = '../../Data/testSpeech8kHz_from16kHz/'; +end +if ~isfield(expParam,'destDir'), + expParam.destDir = '../../tmp/missSampTopoExp/'; +end +if ~exist(expParam.destDir,'dir') + mkdir(expParam.destDir) +end + + +% frame length +if ~isfield(expParam,'N'), + expParam.N = 512; + expParam.N = 256; + warning('AITB:N','Frame length=256 is used to have faster computations. Recommended frame length is 512 at 8kHz.'); +end + +% Number of random frames to test +if ~isfield(expParam,'NFramesPerHoleSize'), + expParam.NFramesPerHoleSize = 20; + warning('AITB:NFrames','expParam.NFramesPerHoleSize = 20 is used to have faster computations. Recommended value: several hundreds.'); +end + +% Number of missing samples: which numbers to test? +if ~isfield(expParam,'totalMissSamplesList') + expParam.totalMissSamplesList = [12,36,60,120,180,240]; + expParam.totalMissSamplesList = [12,36]; + warning('AITB:Miss','expParam.totalMissSamplesList = [12,36] is used to have faster computations. Recommended list: expParam.totalMissSamplesList = [12,36,60,120,180,240].'); +end + +% Choose the solver methods you would like to test: OMP, L1, Janssen +if ~isfield(expParam,'solvers'), + nSolver = 0; + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'OMP-G'; + expParam.solvers(nSolver).inpaintFrame = @inpaintFrame_OMP_Gabor; % solver function + expParam.solvers(nSolver).param.N = expParam.N; % frame length + expParam.solvers(nSolver).param.OMPerr = 0.001; + expParam.solvers(nSolver).param.sparsityDegree = expParam.solvers(nSolver).param.N/4; + expParam.solvers(nSolver).param.D_fun = @Gabor_Dictionary; % Dictionary (function handle) + expParam.solvers(nSolver).param.redundancyFactor = 2; % Dictionary redundancy + expParam.solvers(nSolver).param.wa = @wRect; % Analysis window + + nSolver = nSolver+1; + expParam.solvers(nSolver).name = 'Janssen'; + expParam.solvers(nSolver).inpaintFrame = @inpaintFrame_janssenInterpolation; % solver function + expParam.solvers(nSolver).param.N = expParam.N; % frame length +end + + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +soundDir = expParam.soundDir; +wavFiles = dir([soundDir '*.wav']); +wavFiles = arrayfun(@(x)[soundDir x.name],wavFiles,'UniformOutput',false); + +%% Draw a list of random frames +% Choose an audio file at random +frameParam.kFrameFile = randi(length(wavFiles),expParam.NFramesPerHoleSize); + +% For each audio file, find maximum mean energy among all frames +[dum fs] = wavread([soundDir wavFiles{1}],'size'); +Ne = round(512/16000*fs); +E2m = zeros(length(wavFiles),1); +for kf = 1:length(wavFiles) + x=wavread(wavFiles{kf}); + xm = filter(ones(Ne,1)/Ne,1,abs(x.^2)); + E2m(kf) = 10*log10(max(xm)); +end + +% Choose the location of a frame at random, with a minimum energy +maxDiffE2m = 10; +frameParam.kFrameBegin = NaN(expParam.NFramesPerHoleSize,1); +for kf = 1:expParam.NFramesPerHoleSize + siz = wavread(wavFiles{frameParam.kFrameFile(kf)},'size'); + while true + frameParam.kFrameBegin(kf) = randi(siz(1)-expParam.N+1); + x = wavread(wavFiles{frameParam.kFrameFile(kf)},[0,expParam.N-1]+frameParam.kFrameBegin(kf)); + E2m0 = 10*log10(mean(abs(x.^2))); + if E2m(frameParam.kFrameFile(kf))-E2m0 <= maxDiffE2m + break + end + end +end + +%% Test each number of missing samples +PerfRes = cell(length(expParam.totalMissSamplesList),length(expParam.solvers)); +factorsToTest = cell(length(expParam.totalMissSamplesList),length(expParam.solvers)); +outputFile = [expParam.destDir 'missSampTopoExp.mat']; +for kSolver = 1:length(expParam.solvers) + fprintf('\n ------ Solver: %s ------\n\n',... + expParam.solvers(kSolver).name); + for kMiss = 1:length(expParam.totalMissSamplesList) + NMissSamples = expParam.totalMissSamplesList(kMiss); + factorsToTest{kMiss} = allFactors(NMissSamples); + PerfRes{kMiss,kSolver} = zeros([length(factorsToTest{kMiss}),expParam.NFramesPerHoleSize]); + for kFactor = 1:length(factorsToTest{kMiss}) + holeSize = factorsToTest{kMiss}(kFactor); + NHoles = NMissSamples/holeSize; + fprintf('%d %d-length holes (%d missing samples = %.1f%%)\n',... + NHoles,holeSize,NMissSamples,NMissSamples/expParam.N*100) + problemParameters.holeSize = holeSize; + problemParameters.NHoles = NHoles; + for kFrame = 1:expParam.NFramesPerHoleSize + %% load audio frame + xFrame = wavread(... + wavFiles{frameParam.kFrameFile(kFrame)},... + frameParam.kFrameBegin(kFrame)+[0,expParam.N-1]); + + %% generate problem + [problemData, solutionData] = ... + generateMissingGroupsProblem(xFrame,problemParameters); + + %% solve problem + xEst = ... + expParam.solvers(kSolver).inpaintFrame(... + problemData,... + expParam.solvers(kSolver).param); + + %% compute and store performance + [SNRAll, SNRmiss] = ... + SNRInpaintingPerformance(... + solutionData.xClean,... + problemData.x,... + xEst,... + problemData.IMiss); + PerfRes{kMiss,kSolver}(kFactor,kFrame) = SNRmiss(2); + + end + end + save(outputFile,'PerfRes','expParam'); + end +end + +figure +Nrows = floor(sqrt(length(expParam.solvers))); +Ncols = ceil(sqrt(length(expParam.solvers))/Nrows); +cmap = lines; +for kSolver = 1:length(expParam.solvers) + subplot(Nrows,Ncols,kSolver) + hold on,grid on + for kMiss = 1:length(expParam.totalMissSamplesList) + plot(factorsToTest{kMiss},mean(PerfRes{kMiss,kSolver},2),... + 'color',cmap(kMiss,:)); + end + title(expParam.solvers(kSolver).name) +end +return + +function m = allFactors(n) +% Find the list of all factors (not only prime factors) + +primeFactors = factor(n); + +degrees = zeros(size(primeFactors)); + +for k=1:length(degrees) + degrees(k) = sum(primeFactors==primeFactors(k)); +end + +[primeFactors, I] = unique(primeFactors); +degrees = degrees(I); + +D = (0:degrees(1)).'; +for k=2:length(degrees) + Dk = ones(size(D,1),1)*(0:degrees(k)); + D = [repmat(D,degrees(k)+1,1),Dk(:)]; +end + +m = unique(sort(prod((ones(size(D,1),1)*primeFactors).^D,2))); + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Problems/generateDeclippingProblem.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,124 @@ +function [problemData, solutionData] = generateDeclippingProblem(x,clippingLevel,GR) +% +% +% Usage: +% +% +% Inputs: +% - +% - +% - +% - +% - +% - +% - +% - +% +% Outputs: +% - +% - +% - +% - +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% Generate a clipping problem: normalize and clip a signal. +% +% Usage: +% [problemData, solutionData] = makeClippedSignal(x,clippingLevel,GR) +% +% Inputs: +% - x: input signal (may be multichannel) +% - clippingLevel: clipping level, between 0 and 1 +% - GR (default: false): flag to generate an optional graphical display +% +% Outputs: +% - problemData.x: clipped signal +% - problemData.IMiss: boolean vector (same size as problemData.x) that indexes clipped +% samples +% - problemData.clipSizes: size of the clipped segments (not necessary +% for solving the problem) +% - solutionData.xClean: clean signal (input signal after normalization +% +% Note that the input signal is normalized to 0.9999 (-1 is not allowed in +% wav files) to provide problemData.x and solutionData.xClean. + +if nargin<3 || isempty(GR) + GR = false; +end + +%% Normalization +xMax = 0.9999; +solutionData.xClean = x/max(abs(x(:)))*xMax; +clippingLevel = clippingLevel*xMax; + +%% Clipping (hard threshold) +problemData.x = min(max(solutionData.xClean,-clippingLevel),clippingLevel); +problemData.IMiss = abs(problemData.x)>=clippingLevel; % related indices + +%% Size of the clipped segments +problemData.clipSizes = diff(problemData.IMiss); +if problemData.clipSizes(find(problemData.clipSizes,1,'first'))==-1,problemData.clipSizes = [1;problemData.clipSizes]; end +if problemData.clipSizes(find(problemData.clipSizes,1,'last'))==1,problemData.clipSizes = [problemData.clipSizes;-1]; end +problemData.clipSizes = diff(find(problemData.clipSizes)); +problemData.clipSizes = problemData.clipSizes(1:2:end); + +%% Optional graphical display +if GR + + % Plot histogram of the sizes of the clipped segments + if ~isempty(problemData.clipSizes) + figure + hist(problemData.clipSizes,1:max(problemData.clipSizes)) + title('Size of missing segments') + xlabel('Size'),ylabel('# of segments') + end + + t = (0:length(solutionData.xClean)-1); % time scale in samples + + % Plot original and clipped signals + figure + plot(t,solutionData.xClean,'',t,problemData.x,'') + legend('original','clipped') + + % Scatter plot between original and clipped signals + figure + plot(solutionData.xClean,problemData.x,'.') + xlabel('Original signal'),ylabel('Clipped signal') + + % Spectrograms + N = 512; + w = hann(N); + fs = 1; + NOverlap = round(.8*N); + nfft = 2^nextpow2(N)*2*2; + figure + subplot(3,3,[1,4]) + spectrogram(solutionData.xClean,w,NOverlap,nfft,fs,'yaxis') + title('Original') + xlim(t([1,end])) + cl = get(gca,'clim'); + set(gca,'clim',cl); + subplot(3,3,[1,4]+1) + spectrogram(problemData.x,w,NOverlap,nfft,fs,'yaxis') + title('Clipped') + set(gca,'clim',cl); + subplot(3,3,[1,4]+2) + spectrogram(solutionData.xClean-problemData.x,w,NOverlap,nfft,fs,'yaxis') + title('Error (=original-clipped)') + set(gca,'clim',cl); + subplot(3,3,7) + plot(t,solutionData.xClean,'');xlim(t([1,end])) + subplot(3,3,8) + plot(t,solutionData.xClean,'',t,problemData.x,'');xlim(t([1,end])) + subplot(3,3,9) + plot(t,solutionData.xClean-problemData.x,'');xlim(t([1,end])) +end + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Problems/generateMissingGroupsProblem.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,126 @@ +function [problemData, solutionData] = generateMissingGroupsProblem(xFrame,problemParameters) +% +% +% Usage: +% +% +% Inputs: +% - +% - +% - +% - +% - +% - +% - +% - +% +% Outputs: +% - +% - +% - +% - +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +% Generate a clipping problem: normalize and clip a signal. +% +% Usage: +% [problemData, solutionData] = makeClippedSignal(x,clippingLevel,GR) +% +% Inputs: +% - x: input signal (may be multichannel) +% - clippingLevel: clipping level, between 0 and 1 +% - GR (default: false): flag to generate an optional graphical display +% +% Outputs: +% - problemData.xClipped: clipped signal +% - problemData.IClipped: boolean vector (same size as problemData.xClipped) that indexes clipped +% samples +% - problemData.clipSizes: size of the clipped segments (not necessary +% for solving the problem) +% - solutionData.xClean: clean signal (input signal after normalization +% +% Note that the input signal is normalized to 0.9999 (-1 is not allowed in +% wav files) to provide problemData.xClipped and solutionData.xClean. + +%function [xFrame,xFrameObs,Imiss] = aux_getFrame(xFrame,holeSize,NHoles)%,param,frameParam,kFrame) + +N = length(xFrame); % frame length + +% Load frame +% xFrame = wavread(param.wavFiles{frameParam.kFrameFile(kFrame)},frameParam.kFrameBegin(kFrame)+[0,N-1]); + +% Window +%xFrame = xFrame.*param.wa(N).'; + +% Normalize +xFrame = xFrame/max(abs(xFrame)); + +% Build random measurement matrix with NHoles of length holeSize +[M IMiss] = makeRandomMeasurementMatrix(N,problemParameters.NHoles,problemParameters.holeSize); +xFrameObs = xFrame; +xFrameObs(IMiss) = 0; + +problemData.x = xFrameObs; +problemData.IMiss = IMiss; +solutionData.xClean = xFrame; +return + + +function [M Im] = makeRandomMeasurementMatrix(N,NMissingBlocks,blockSize) +% [M Im] = makeRandomMeasurementMatrix(N,NMissingBlocks,blockSize) +% Create a random measurement matrix M where NMissingBlocks blocks with +% size blockSize each are randomly inserted. The boolean vector Im +% indicates the location of the NMissingBlocks*blockSize missing +% samples. +% If the number of missing samples is large, there may be very few solutions +% so that after a few failing attempts, the results is generated in a deterministic +% way (groups separated by one sample). This happens for example when the number of +% missing samples is close to half the frame length, for isolated samples (blockSize=1). + +nTry = 1; +while true + try + Im = false(N,1); + + possibleStart = 1:N-blockSize+1; + + for k=1:NMissingBlocks + if isempty(possibleStart) + error('makeRandomMeasurementMatrix:tooMuchMissingSamples',... + 'Too much missing segments'); + end + I = ceil(rand*(length(possibleStart)-1)); + I = possibleStart(I); + Im(I+(0:blockSize-1)) = true; + possibleStart(possibleStart>=I-blockSize & possibleStart<=I+blockSize) = []; + end + break + catch + fprintf('makeRandomMeasurementMatrix:retry (%d)\n',nTry); + nTry = nTry+1; + if nTry>10 + Im = [true(blockSize,NMissingBlocks);false(1,NMissingBlocks)]; + Im = Im(:); + while length(Im)<N + N0 = sum(~Im); + I0 = find(~Im,randi(N0),'first'); + I0 = I0(end); + Im = [Im(1:I0);false;Im(I0+1:end)]; + end + Im = circshift(Im,randi(N)); + break; + end + end +end +M = eye(N); +M(Im,:) = []; + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Solvers/inpaintFrame_OMP.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,77 @@ +function y = inpaintFrame_OMP(problemData,param) +% Inpainting method based on OMP +% +% Usage: y = inpaintFrame_OMP(problemData,param) +% +% +% Inputs: +% - problemData.x: observed signal to be inpainted +% - problemData.Imiss: Indices of clean samples +% - param.D - the dictionary matrix (optional if param.D_fun is set) +% - param.D_fun - a function handle that generates the dictionary +% matrix param.D if param.D is not given. See, e.g., DCT_Dictionary.m and Gabor_Dictionary.m +% - param.wa - Analysis window +% +% Outputs: +% - y: estimated frame +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Michael Elad, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% ======================================================== +% To do next: use a faster implementation of OMP + +%% Load data and parameters + +x = problemData.x; +IObs = find(~problemData.IMiss); +p.N = length(x); + E2 = param.OMPerr^2; + E2M=E2*length(IObs); + + wa = param.wa(param.N); + + +%% Build and normalized dictionary +% build the dictionary matrix if only the dictionary generation function is given +if ~isfield(param,'D') + param.D = param.D_fun(param); +end +Dict=param.D(IObs,:); +W=1./sqrt(diag(Dict'*Dict)); +Dict=Dict*diag(W); +xObs=x(IObs); + +%% OMP iterations +residual=xObs; +maxNumCoef = param.sparsityDegree; +indx = []; +currResNorm2 = E2M*2; % set a value above the threshold in order to have/force at least one loop executed +j = 0; +while currResNorm2>E2M && j < maxNumCoef, + j = j+1; + proj=Dict'*residual; + [dum pos] = max(abs(proj)); + indx(j)=pos; + + a=pinv(Dict(:,indx(1:j)))*xObs; + + residual=xObs-Dict(:,indx(1:j))*a; + currResNorm2=sum(residual.^2); +end + +%% Frame Reconstruction +indx(length(a)+1:end) = []; + +Coeff = sparse(size(param.D,2),1); +if (~isempty(indx)) + Coeff(indx) = a; + Coeff = W.*Coeff; +end +y = param.D*Coeff; + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Solvers/inpaintFrame_OMP_Gabor.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,93 @@ +function [y , Coeff]= inpaintFrame_OMP_Gabor(problemData,param) +% Inpainting method based on OMP using the Gabor dictionary +% generated by Gabor_Dictionary.m. The method jointly selects +% cosine and sine atoms at the same frequency +% +% Usage: y = inpaintFrame_OMP_Gabor(problemData,param) +% +% +% Inputs: +% - problemData.x: observed signal to be inpainted +% - problemData.Imiss: Indices of clean samples +% - param.D - the dictionary matrix (optional if param.D_fun is set) +% - param.D_fun - a function handle that generates the dictionary +% matrix param.D if param.D is not given. See Gabor_Dictionary.m +% - param.wa - Analysis window +% +% Outputs: +% - y: estimated frame +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Michael Elad, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% ======================================================== +% To do next: use a faster implementation of OMP + + +%% Load data and parameters + + +x = problemData.x; +IObs = find(~problemData.IMiss); +p.N = length(x); +E2 = param.OMPerr^2; +E2M=E2*length(IObs); +wa = param.wa(param.N); + +%% Build and normalized dictionary +% build the dictionary matrix if only the dictionary generation function is given +if ~isfield(param,'D') + param.D = param.D_fun(param); +end +Dict=param.D(IObs,:); +W=1./sqrt(diag(Dict'*Dict)); +Dict=Dict*diag(W); +Dict1 = Dict(:,1:end/2); +Dict2 = Dict(:,end/2+1:end); +Dict1Dict2 = sum(Dict1.*Dict2); +n12 = 1./(1-Dict1Dict2.^2); +xObs=x(IObs); + +%% OMP iterations +residual=xObs; +maxNumCoef = param.sparsityDegree; +indx = []; +% currResNorm2 = sum(residual.^2); +currResNorm2 = E2M*2; % set a value above the threshold in order to have/force at least one loop executed +j = 0; +while currResNorm2>E2M && j < maxNumCoef, + j = j+1; + proj=residual'*Dict; + proj1 = proj(1:end/2); + proj2 = proj(end/2+1:end); + + alpha_j = (proj1-Dict1Dict2.*proj2).*n12; + beta_j = (proj2-Dict1Dict2.*proj1).*n12; + + err_j = sum(abs(repmat(residual,1,size(Dict1,2))-Dict1*sparse(diag(alpha_j))-Dict2*sparse(diag(beta_j))).^2); + [dum pos] = min(err_j); + + indx(end+1)=pos; + indx(end+1)=pos+size(Dict1,2); + a=pinv(Dict(:,indx(1:2*j)))*xObs; + residual=xObs-Dict(:,indx(1:2*j))*a; + currResNorm2=sum(residual.^2); +end; + +%% Frame Reconstruction +indx(length(a)+1:end) = []; + +Coeff = sparse(size(param.D,2),1); +if (~isempty(indx)) + Coeff(indx) = a; + Coeff = W.*Coeff; +end +y = param.D*Coeff; + +return + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Solvers/inpaintFrame_consOMP.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,144 @@ +function y = inpaintFrame_consOMP(problemData,param) +% Inpainting method based on OMP with a constraint +% on the amplitude of the reconstructed samples an optional constraint +% on the maximum value of the clipped samples +% +% Usage: y = inpaintFrame_consOMP(problemData,param) +% +% +% Inputs: +% - problemData.x: observed signal to be inpainted +% - problemData.Imiss: Indices of clean samples +% - param.D - the dictionary matrix (optional if param.D_fun is set) +% - param.D_fun - a function handle that generates the dictionary +% matrix param.D if param.D is not given. See, e.g., DCT_Dictionary.m and Gabor_Dictionary.m +% - param.wa - Analysis window +% - param.Upper_Limit - if present and non-empty this fiels +% indicates that an upper limit constraint is active and its +% integer value is such that +% +% Outputs: +% - y: estimated frame +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Michael Elad, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% ======================================================== + +%% Load data and parameters + +x = problemData.x; +IObs = find(~problemData.IMiss); +p.N = length(x); +E2 = param.OMPerr^2; +E2M=E2*length(IObs); +wa = param.wa(param.N); + +% build the dictionary matrix if only the dictionary generation function is given +if ~isfield(param,'D') + param.D = param.D_fun(param); +end + + +% clipping level detection +clippingLevelEst = max(abs(x(:)./wa(:))); + +IMiss = true(length(x),1); +IMiss(IObs) = false; +IMissPos = find(x>=0 & IMiss); +IMissNeg = find(x<0 & IMiss); + +DictPos=param.D(IMissPos,:); +DictNeg=param.D(IMissNeg,:); + +% Clipping level: take the analysis window into account +wa_pos = wa(IMissPos); +wa_neg = wa(IMissNeg); +b_ineq_pos = wa_pos(:)*clippingLevelEst; +b_ineq_neg = -wa_neg(:)*clippingLevelEst; +if isfield(param,'Upper_Limit') && ~isempty(param.Upper_Limit) + b_ineq_pos_upper_limit = wa_pos(:)*param.Upper_Limit*clippingLevelEst; + b_ineq_neg_upper_limit = -wa_neg(:)*param.Upper_Limit*clippingLevelEst; +else + b_ineq_pos_upper_limit = Inf; + b_ineq_neg_upper_limit = -Inf; +end + +%% +Dict=param.D(IObs,:); +W=1./sqrt(diag(Dict'*Dict)); +Dict=Dict*diag(W); +xObs=x(IObs); + +residual=xObs; +maxNumCoef = param.sparsityDegree; +indx = []; +currResNorm2 = E2M*2; % set a value above the threshold in order to have/force at least one loop executed +j = 0; +while currResNorm2>E2M && j < maxNumCoef, + j = j+1; + proj=Dict'*residual; + [dum pos] = max(abs(proj)); + indx(j)=pos; + a=pinv(Dict(:,indx(1:j)))*xObs; + residual=xObs-Dict(:,indx(1:j))*a; + currResNorm2=sum(residual.^2); +end; + + +if isinf(b_ineq_pos_upper_limit) + %% CVX code + cvx_begin + cvx_quiet(true) + variable a(j) + %minimize( sum(square(xObs-Dict*a))) + minimize(norm(Dict(:,indx)*a-xObs)) + subject to + DictPos(:,indx)*(W(indx).*a) >= b_ineq_pos + DictNeg(:,indx)*(W(indx).*a) <= b_ineq_neg + cvx_end + if cvx_optval>1e3 + cvx_begin + cvx_quiet(true) + variable a(j) + minimize(norm(Dict(:,indx)*a-xObs)) + cvx_end + end +else + %% CVX code + cvx_begin + cvx_quiet(true) + variable a(j) + %minimize( sum(square(xObs-Dict*a))) + minimize(norm(Dict(:,indx)*a-xObs)) + subject to + DictPos(:,indx)*(W(indx).*a) >= b_ineq_pos + DictNeg(:,indx)*(W(indx).*a) <= b_ineq_neg + DictPos(:,indx)*(W(indx).*a) <= b_ineq_pos_upper_limit + DictNeg(:,indx)*(W(indx).*a) >= b_ineq_neg_upper_limit + cvx_end + if cvx_optval>1e3 + cvx_begin + cvx_quiet(true) + variable a(j) + minimize(norm(Dict(:,indx)*a-xObs)) + cvx_end + end +end + +%% Frame Reconstruction +indx(length(a)+1:end) = []; + +Coeff = sparse(size(param.D,2),1); +if (~isempty(indx)) + Coeff(indx) = a; + Coeff = W.*Coeff; +end +y = param.D*Coeff; + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Solvers/inpaintFrame_consOMP_Gabor.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,160 @@ +function y = inpaintFrame_consOMP_Gabor(problemData,param) +% Inpainting method based on OMP with a constraint +% on the amplitude of the reconstructed samples an optional constraint +% on the maximum value of the clipped samples, and using the Gabor dictionary +% generated by Gabor_Dictionary.m. The method jointly selects +% cosine and sine atoms at the same frequency. +% +% Usage: y = inpaintFrame_consOMP_Gabor(problemData,param) +% +% +% Inputs: +% - problemData.x: observed signal to be inpainted +% - problemData.Imiss: Indices of clean samples +% - param.D - the dictionary matrix (optional if param.D_fun is set) +% - param.D_fun - a function handle that generates the dictionary +% matrix param.D if param.D is not given. See Gabor_Dictionary.m +% - param.wa - Analysis window +% - param.Upper_Limit - if present and non-empty this fiels +% indicates that an upper limit constraint is active and its +% integer value is such that +% +% Outputs: +% - y: estimated frame +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Michael Elad, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + + + + +x = problemData.x; +IObs = find(~problemData.IMiss); +p.N = length(x); +E2 = param.OMPerr^2; +E2M=E2*length(IObs); +wa = param.wa(param.N); + +% build the dictionary matrix if only the dictionary generation function is given +if ~isfield(param,'D') + param.D = param.D_fun(param); +end + + +% clipping level detection +clippingLevelEst = max(abs(x(:)./wa(:))); +IMiss = true(length(x),1); +IMiss(IObs) = false; +IMissPos = find(x>=0 & IMiss); +IMissNeg = find(x<0 & IMiss); + +DictPos=param.D(IMissPos,:); +DictNeg=param.D(IMissNeg,:); + +% Clipping level: take the analysis window into account +wa_pos = wa(IMissPos); +wa_neg = wa(IMissNeg); +b_ineq_pos = wa_pos(:)*clippingLevelEst; +b_ineq_neg = -wa_neg(:)*clippingLevelEst; +if isfield(param,'Upper_Limit') && ~isempty(param.Upper_Limit) + b_ineq_pos_upper_limit = wa_pos(:)*param.Upper_Limit*clippingLevelEst; + b_ineq_neg_upper_limit = -wa_neg(:)*param.Upper_Limit*clippingLevelEst; +else + b_ineq_pos_upper_limit = Inf; + b_ineq_neg_upper_limit = -Inf; +end + +%% +Dict=param.D(IObs,:); +W=1./sqrt(diag(Dict'*Dict)); +Dict=Dict*diag(W); +Dict1 = Dict(:,1:end/2); +Dict2 = Dict(:,end/2+1:end); +Dict1Dict2 = sum(Dict1.*Dict2); +n12 = 1./(1-Dict1Dict2.^2); +xObs=x(IObs); +%K = size(param.D,2); + +residual=xObs; +maxNumCoef = param.sparsityDegree; +indx = []; +% currResNorm2 = sum(residual.^2); +currResNorm2 = E2M*2; % set a value above the threshold in order to have/force at least one loop executed +j = 0; +while currResNorm2>E2M && j < maxNumCoef, + j = j+1; + proj=residual'*Dict; + proj1 = proj(1:end/2); + proj2 = proj(end/2+1:end); + + alpha_j = (proj1-Dict1Dict2.*proj2).*n12; + beta_j = (proj2-Dict1Dict2.*proj1).*n12; + + err_j = sum(abs(repmat(residual,1,size(Dict1,2))-Dict1*sparse(diag(alpha_j))-Dict2*sparse(diag(beta_j))).^2); + [dum pos] = min(err_j); + + indx(end+1)=pos; + indx(end+1)=pos+size(Dict1,2); + a=pinv(Dict(:,indx(1:2*j)))*xObs; + residual=xObs-Dict(:,indx(1:2*j))*a; + currResNorm2=sum(residual.^2); +end; + +%% Constrained reestimation of the non-zero coefficients +j = length(indx); +if isinf(b_ineq_pos_upper_limit) + %% CVX code + cvx_begin + cvx_quiet(true) + variable a(j) + minimize(norm(Dict(:,indx)*a-xObs)) + subject to + DictPos(:,indx)*(W(indx).*a) >= b_ineq_pos + DictNeg(:,indx)*(W(indx).*a) <= b_ineq_neg + cvx_end + if cvx_optval>1e3 + cvx_begin + cvx_quiet(true) + variable a(j) + minimize(norm(Dict(:,indx)*a-xObs)) + cvx_end + end +else + %% CVX code + cvx_begin + cvx_quiet(true) + variable a(j) + minimize(norm(Dict(:,indx)*a-xObs)) + subject to + DictPos(:,indx)*(W(indx).*a) >= b_ineq_pos + DictNeg(:,indx)*(W(indx).*a) <= b_ineq_neg + DictPos(:,indx)*(W(indx).*a) <= b_ineq_pos_upper_limit + DictNeg(:,indx)*(W(indx).*a) >= b_ineq_neg_upper_limit + cvx_end + if cvx_optval>1e3 + cvx_begin + cvx_quiet(true) + variable a(j) + minimize(norm(Dict(:,indx)*a-xObs)) + cvx_end + end +end + +%% Frame Reconstruction +indx(length(a)+1:end) = []; + +Coeff = sparse(size(param.D,2),1); +if (~isempty(indx)) + Coeff(indx) = a; + Coeff = W.*Coeff; +end +y = param.D*Coeff; + +return +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Solvers/inpaintFrame_janssenInterpolation.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,82 @@ +function y = inpaintFrame_janssenInterpolation(problemData,param) +% Frame-level inpainting method based on the linear prediction by +% Janssen. +% +% Usage: xEst = inpaintFrame_janssenInterpolation(problemData,param) +% +% +% Inputs: +% - problemData.x - observed signal to be inpainted +% - problemData.Imiss - Indices of clean samples +% - param.p - Order of the autoregressive model used in +% for linear prediction +% +% Outputs: +% - y: estimated frame +% +% References: +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +s = problemData.x; +N = length(s); +Im = find(problemData.IMiss); +IObs = find(~problemData.IMiss); +M = length(Im); +Im = sort(Im); Im = Im(:); % Im: indexes of missing samples +s(Im) = 0; + +if nargin<2 || ~isfield(param,'p') + p = min(3*M+2,round(N/3)); +else + p = param.p; +end +if nargin<2 || ~isfield(param,'GR') + param.GR = false; +end +if nargin<2 || ~isfield(param,'NIt') + NIt = 100; +else + NIt = param.NIt; +end + + +IAA = abs(Im*ones(1,N)-ones(M,1)*(1:N)); +IAA1 = IAA<=p; +AA = zeros(size(IAA)); + +if param.GR + figure; + hold on +end +for k=1:NIt + + % Re-estimation of LPC + aEst = lpc(s,p).'; + + % Re-estimation of the missing samples + b = aEst.'*hankel(aEst.',[aEst(end),zeros(1,p)]); + AA(IAA1) = b(IAA(IAA1)+1); +% xEst = -inv(AA(:,Im))*AA(:,IObs)*s(IObs); % use Chol to invert matrix + [R flagErr] = chol(AA(:,Im)); + if flagErr + % xEst = - AA(:,Im)\(AA(:,IObs)*s(IObs)); + xEst = -inv(AA(:,Im))*AA(:,IObs)*s(IObs); + else + xEst = -R\(R'\(AA(:,IObs)*s(IObs))); + end + s(Im) = xEst; + if param.GR + e = filter(aEst,1,s); + plot(k,10*log10(mean(e(p+1:end).^2)),'o') + end +end + +y = s; + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Solvers/inpaintSignal_IndependentProcessingOfFrames.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,372 @@ +function [ReconstSignal1 ReconstSignal2] = inpaintSignal_IndependentProcessingOfFrames(problemData,param) +% +% +% Usage: +% +% +% Inputs: +% - +% - +% - +% - +% - +% - +% - +% - +% +% Outputs: +% - +% - +% - +% - +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% ======================================================== +% Perform Audio De-clipping with overlapping blocks +% Synthesis Approach, union of overcomplete DCT dictionary +% Date: 14 Apr. 2010 +% Inputs: +% - x: Clipped signal +% - ClipMask: Indices of clipped samples +% - Optional parameters [and default values]: +% - param.N: frame length [256] +% - param.frameOverlapFactor: overlap factor between frames [2] +% - param.wa: weighting analysis window [@sineWin] +% - param.ws: weighting synthesis window [@sineWin] +% - param.OMPerr: error threshold to stop OMP iterations [0.001] +% - param.sparsityDegree: max number of non-zero components to +% stop OMP iterations [param.N/4]; +% - other fields: see the documentation of UDCT_Dictionary +% +% Outputs: +% ReconstSignal1 - reconstructed signal (all samples generated +% from the synthesis model) +% ReconstSignal2 - reconstructed signal (only clipped samples are generated +% from the synthesis model) +% +% By Valentin Emiya - SMALL Project, 2010 +% +% ======================================================== + +% Check parameters +defaultParam.N = 256; +defaultParam.OLA_frameOverlapFactor = 4; +defaultParam.wa = @wSine; +defaultParam.OLA_ws = @wSine; +defaultParam.OLA_par_waitingTime_mainProcess = 0.2; +defaultParam.OLA_par_waitingTime_thread = 0.2; +defaultParam.OLA_par_frameBlockSize = 1; +defaultParam.TCPIP_port = 3000; +defaultParam.COM_DISP = false; +defaultParam.STATE_DISP = false; + +if nargin<2 + param = defaultParam; +else + names = fieldnames(defaultParam); + for k=1:length(names) + if ~isfield(param,names{k}) || isempty(param.(names{k})) + param.(names{k}) = defaultParam.(names{k}); + end + end +end + +x = problemData.x; +ClipMask = find(problemData.IMiss); + +% According to this flag, switch between a parallel multithread processing +% and a singlethread processing. This can fasten the computations but does +% not affect the results. +if param.MULTITHREAD_FRAME_PROCESSING + [ReconstSignal1 ReconstSignal2] = multithreadProcessing(x,ClipMask,param); +else + [ReconstSignal1 ReconstSignal2] = singlethreadProcessing(x,ClipMask,param); +end + +return; + +function [ReconstSignal1 ReconstSignal2] = singlethreadProcessing(x,ClipMask,param) +% ======================================================== +% Overlap-and-add processing of a signal with missing samples. +% Decomposition into overlapping frames, processing of each +% frame independently and OLA reconstruction. +% Date: 01 Jun. 2010 +% Inputs: +% - x: Clipped signal +% - ClipMask: Indices of clipped samples +% - Optional parameters [and default values]: +% - param.N: frame length [256] +% - param.inpaintFrame: function handle for inpainting a frame +% [@inpaintFrame_OMP] +% - param.OLA_frameOverlapFactor: overlap factor between frames [2] +% - param.wa: weighting analysis window [@sineWin] +% - param.OLA_ws: weighting synthesis window [@sineWin] +% - param.SKIP_CLEAN_FRAMES: flag to skip frames with no +% missing samples [true] +% - other fields: see the documentation the inpainting method +% +% Outputs: +% ReconstSignal1 - reconstructed signal (all samples generated +% from the synthesis model) +% ReconstSignal2 - reconstructed signal (only clipped samples are generated +% from the synthesis model) +% +% By Amir Adler, Maria Jafari, Valentin Emiya - SMALL Project, 2010 +% +% ======================================================== + +% Check parameters +defaultParam.N = 256; +defaultParam.inpaintFrame = @inpaintFrame_OMP; +defaultParam.OLA_frameOverlapFactor = 2; +defaultParam.wa = @wSine; +defaultParam.ws = @wSine; +defaultParam.SKIP_CLEAN_FRAMES = true; + +if nargin<3 + param = defaultParam; +else + names = fieldnames(defaultParam); + for k=1:length(names) + if ~isfield(param,names{k}) || isempty(param.(names{k})) + param.(names{k}) = defaultParam.(names{k}); + end + end +end +% if ~isfield(param,'D') +% param.D = param.D_fun(param); +% end + +bb=param.N; % block size + +% modify signal length to accommodate integer number of blocks +L=floor(length(x)/bb)*bb; +x=x(1:L); +ClipMask(ClipMask>L) = []; + +% Extracting the signal blocks with 50% overlap +Ibegin = (1:bb/param.OLA_frameOverlapFactor:length(x)-bb); +if Ibegin(end)~=L-bb+1 + Ibegin(end+1) = L-bb+1; +end +Iblk = ones(bb,1)*Ibegin+(0:bb-1).'*ones(size(Ibegin)); +wa = param.wa(bb); % analysis window +xFrames=diag(wa)*x(Iblk); + +% Generating the block mask +Mask=ones(size(x)); +Mask(ClipMask)=0; +blkMask=Mask(Iblk); + +% Declipping the Patches +[n,P]=size(xFrames); + +if ~isdeployed + h=waitbar(0,'Processing each frame...'); +end +Reconst = zeros(n,P); +co = zeros(512,P); +for k=1:1:P, + if ~isdeployed + waitbar(k/P); + end + if param.SKIP_CLEAN_FRAMES && all(blkMask(:,k)) + continue + end + frameProblemData.x = xFrames(:,k); + frameProblemData.IMiss = ~blkMask(:,k); + + [Reconst(:,k)]= ... + param.inpaintFrame(frameProblemData,param); + +end; +if ~isdeployed + close(h); +end + +% Overlap and add + +% The completly reconstructed signal +ReconstSignal1 = zeros(size(x)); +ws = param.OLA_ws(bb); % synthesis window +wNorm = zeros(size(ReconstSignal1)); +for k=1:size(Iblk,2) + ReconstSignal1(Iblk(:,k)) = ReconstSignal1(Iblk(:,k)) + Reconst(:,k).*ws(:); + wNorm(Iblk(:,k)) = wNorm(Iblk(:,k)) + ws(:).*wa(:); +end +ReconstSignal1 = ReconstSignal1./wNorm; + +% Only replace the clipped samples with the reconstructed ones +ReconstSignal2=x; +ReconstSignal2(ClipMask)=ReconstSignal1(ClipMask); + +return; + +function [ReconstSignal1 ReconstSignal2] = multithreadProcessing(x,ClipMask,param) +% Send parameters to the threads +% initParamFilename = [param.OLA_par_threadDir 'par_param.mat']; +% save(initParamFilename,'param'); + +bb=param.N; % block size + +% modify signal length to accommodate integer number of blocks +L=floor(length(x)/bb)*bb; +x=x(1:L); +ClipMask(ClipMask>L) = []; + +% Extracting the signal blocks with 50% overlap +Ibegin = (1:round(bb/param.OLA_frameOverlapFactor):length(x)-bb); +if Ibegin(end)~=L-bb+1 + Ibegin(end+1) = L-bb+1; +end +Iblk = ones(bb,1)*Ibegin+(0:bb-1).'*ones(size(Ibegin)); +wa = param.wa(bb); % analysis window +xFrames=diag(wa)*x(Iblk); + +% Generating the block mask +Mask=ones(size(x)); +Mask(ClipMask)=0; +blkMask=Mask(Iblk); + +% Declipping the Patches +if ~isdeployed && false + h=waitbar(0,'Processing each frame...'); +end +[n,P]=size(xFrames); +Reconst = NaN(n,P); +% initializedThreads = []; + +% find the block of frames to process +k_lists = {}; +kTrame = 1; +while kTrame<=P + k_list = zeros(param.OLA_par_frameBlockSize,1); + ind = 0; + while ind<param.OLA_par_frameBlockSize && kTrame<=P + if param.SKIP_CLEAN_FRAMES && all(blkMask(:,kTrame)) + kTrame=kTrame+1; + continue + end + ind = ind+1; + k_list(ind) = kTrame; + kTrame=kTrame+1; + end + if ind==0 + break; + end + k_lists{end+1} = k_list(1:ind); +end +k_list_all = cell2mat(k_lists'); + +% Create a server +serverSocket = createServer(param); +% Definition of the client states +stateDef; + +param.COM_DISP = false; + +kBlock=1; +initializedClientIDs = []; +while any(isnan(Reconst(1,k_list_all))) + if ~isdeployed && false + waitbar(sum(~isnan(Reconst(1,k_list_all)))/length(k_list_all)); + end + + % Wait for a new client + currentClient = waitClient(serverSocket); + + % Receive client state + clientIDState = readData(currentClient,param.COM_DISP); + clientID = clientIDState(1); + clientState = clientIDState(2); + switch clientState + case INIT + if param.STATE_DISP + fprintf('INIT %d\n',clientID); + end + if 0 + sendData(currentClient,initParamFilename,param.COM_DISP); + else + sendData(currentClient,param,param.COM_DISP); + end + initializedClientIDs(end+1) = clientID; + case FREE + if ~ismember(clientID,initializedClientIDs) + sendData(currentClient,INIT_ORDER,param.COM_DISP); % INIT + elseif kBlock<=length(k_lists) + k_list = k_lists{kBlock}; + if param.STATE_DISP + fprintf('TO PROCESS %d:',clientID); + arrayfun(@(x)fprintf(' %d',x),k_list); + fprintf('\n'); + end + sendData(currentClient,k_list,param.COM_DISP); + sendData(currentClient,xFrames(:,k_list),param.COM_DISP); + sendData(currentClient,find(blkMask(:,k_list)),param.COM_DISP); + kBlock = kBlock+1; + else + if param.STATE_DISP + fprintf('WAIT %d\n',clientID); + end + sendData(currentClient,WAIT_ORDER,param.COM_DISP); % no data to process + end + case PROCESSED + processed_k_list = readData(currentClient,param.COM_DISP); + y = readData(currentClient,param.COM_DISP); + y = reshape(y,[],length(processed_k_list)); + if param.STATE_DISP + fprintf('PROCESSED %d:',clientID); + arrayfun(@(x)fprintf(' %d',x),processed_k_list); + fprintf('\n'); + end + if ~isempty(processed_k_list) + Reconst(:,processed_k_list) = y; + end + otherwise + error('switch:UndefinedClientState','Undefined client state'); + end + + closeClientConnection(currentClient); +end; + +% Close the server +closeServer(serverSocket); + +if ~isdeployed && false + close(h); +end + +% Overlap and add + +% The completly reconstructed signal +ReconstSignal1 = zeros(size(x)); +ws = param.OLA_ws(bb); % synthesis window +wNorm = zeros(size(ReconstSignal1)); +for k=1:size(Iblk,2) + ReconstSignal1(Iblk(:,k)) = ReconstSignal1(Iblk(:,k)) + Reconst(:,k).*ws(:); + wNorm(Iblk(:,k)) = wNorm(Iblk(:,k)) + ws(:).*wa(:); +end +ReconstSignal1 = ReconstSignal1./wNorm; + +% Only replace the clipped samples with the reconstructed ones +ReconstSignal2=x; +ReconstSignal2(ClipMask)=ReconstSignal1(ClipMask); + +killClients(param); + +return; + +% ======================================================== +% ======================================================== + + + +% ======================================================== +% ========================================================
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/dictionaries/DCT_Dictionary.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,51 @@ +function D = DCT_Dictionary(param) +% Windowed DCT dictionary +% +% Usage: +% D = DCT_Dictionary(param) +% +% +% Inputs [and default values]: +% - param.N: frame length [256] +% - param.redundancyFactor: redundancy factor to adjust the number of +% frequencies [1]. The number of atoms in the dictionary equals +% param.N*param.redundancyFactor +% - param.wd: weigthing window function [@wSine] +% +% Output: +% - Dictionary: D +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% Windowed DCT dictionary +% + +% Check and load default parameters +defaultParam.N = 256; +defaultParam.redundancyFactor = 1; +defaultParam.wd = @wSine; + +if nargin<1 + param = defaultParam; +else + names = fieldnames(defaultParam); + for k=1:length(names) + if ~isfield(param,names{k}) || isempty(param.(names{k})) + param.(names{k}) = defaultParam.(names{k}); + end + end +end +K = param.N*param.redundancyFactor; % number of atoms +wd = param.wd(param.N); % weigthing window +u = 0:(param.N-1); % time +k=0:K-1; % frequency +D = diag(wd)*cos(pi/K*(u.'+1/2)*(k+1/2)); + +% normalisation +D = D*diag(1./sqrt(diag(D'*D))); +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/dictionaries/Gabor_Dictionary.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,57 @@ +function D = Gabor_Dictionary(param) +% Windowed Gabor dictionary. In this implementation, the dictionary matrix +% is the concatenation of a DCT (left part of the matrix) and of a DST +% (right part). +% Note that one can use this dictionary +% - either by constraining the simulaneous selection of cosine and sine +% atoms with same frequency in order to implement Gabor atoms; +% - or, without any selection constraint, by considering that the +% dictionary is not a Gabor dictionary but the concatenation of a DCT and +% of a DST. +% +% Usage: +% D = Gabor_Dictionary(param) +% +% Inputs [and default values]: +% - param.N: frame length [256] +% - param.redundancyFactor: redundancy factor to adjust the number of +% frequencies [1]. The number of atoms in the dictionary equals +% param.N*param.redundancyFactor +% - param.wd: weigthing window function [@wSine] +% +% Output: +% - Dictionary: D (cosine atoms followed by sine atoms) +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +% Check and load default parameters +defaultParam.N = 256; +defaultParam.redundancyFactor = 1; +defaultParam.wd = @wSine; + +if nargin<1 + param = defaultParam; +else + names = fieldnames(defaultParam); + for k=1:length(names) + if ~isfield(param,names{k}) || isempty(param.(names{k})) + param.(names{k}) = defaultParam.(names{k}); + end + end +end +K = param.N*param.redundancyFactor; % number of atoms +wd = param.wd(param.N); % weigthing window +u = 0:(param.N-1); % time +k=0:K/2-1; % frequency +D = diag(wd)*[cos(2*pi/K*(u.'+1/2)*(k+1/2)),sin(2*pi/K*(u.'+1/2)*(k+1/2))]; + +% normalisation +D = D*diag(1./sqrt(diag(D'*D))); + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/evaluation/SNR.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,26 @@ +function snr = SNR(xRef,xEst) +% Signal-to-noise Ratio +% +% Usage: snr = SNR(xRef,xEst) +% +% +% Inputs: +% - xRef - reference signal +% - xEst - estimate signal +% +% Outputs: +% - snr - SNR +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% Signal to noise ratio (SNR) + +% Add eps to avoid NaN/Inf values +snr = 10*log10((sum(abs(xRef(:)).^2)+eps)/sum((abs(xRef(:)-xEst(:)).^2)+eps)); + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/evaluation/SNRInpaintingPerformance.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,43 @@ +function [SNRAll,SNRmiss] = SNRInpaintingPerformance(xRef,xObs,xEst,IMiss,DISP_FLAG) +% Various SNR measures for inpainting performance +% +% Usage: [SNRAll,SNRmiss] = SNRInpaintingPerformance(xRef,xObs,xEst,IMiss,DISP_FLAG) +% +% +% Inputs: +% - xRef - reference signal +% - xObs - observed signal +% - xEst - estimate signal +% - IMiss - location of missing data +% +% Outputs: +% - SNRAll - SNRAll(1) is the original SNR, between xRef and xObs; +% SNRAll(2) is the SNR is the obtained SNR, between xRef and xEst +% - SNRmiss - the same as SNRAll but computed on the missing/restored +% samples only +% +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +if nargin<5 + DISP_FLAG = 0; +end + +SNRAll = [SNR(xRef,xObs),SNR(xRef,xEst)]; +SNRmiss = [SNR(xRef(IMiss),xObs(IMiss)),SNR(xRef(IMiss),xEst(IMiss))]; + +if DISP_FLAG>0 + fprintf('SNR on all samples / clipped samples:\n'); + fprintf('Original: %g dB / %g dB\n',... + SNRAll(1),... + SNRmiss(1)); + fprintf('Estimate: %g dB / %g dB\n',... + SNRAll(2),... + SNRmiss(2)); +end + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/evaluation/exclude_audioQualityMeasures.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,203 @@ +function [SNRx, PSM, PSMt, PESQ_MOS, EAQUAL_ODG, EAQUAL_DIX] = ... + audioQualityMeasures(xRef,xTest,fs,options) +% +% +% Usage: +% +% +% Inputs: +% - +% - +% - +% - +% - +% - +% - +% - +% +% Outputs: +% - +% - +% - +% - +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% Computes a series of audio quality measures +% +% Usage: +% [PSM,PSMt] = ... +% audioQualityMeasures(xRef,xTest,fs,options) +% +% Inputs: +% - xRef: reference signal +% - xTest: test signal (to be compared to xRef) +% - fs: sampling frequency +% - optional parameters [default]: +% - options.ENABLE_PEMOQ: flag to use PEMO-Q or not [true] +% - options.pemoQExec: name of PEMO-Q executable ['"./PEMO-Q v1.1.2 demo/audioqual_demo.exe"'] +% - options.PESQExec: name of PESQ executable [''./PESQ/pesq''] +% - options.EAQUALExec: name of EAQUAL (PEAQ) executable ['./EAQUAL/eaqual.exe'] +% +% Note that PEMO-Q and EAQUAL programs are Windows executable and that +% under unix, they can be used by means of wine (Windows Emulator). One +% just have to have wine installed. +% +% Valentin Emiya, INRIA, 2010. + + +%% default options +defaultOptions.pemoQExec = '"C:/Program Files/PEMO-Q v1.2/audioqual.exe"'; % Full licensed version +if isempty(dir(defaultOptions.pemoQExec)) + defaultOptions.pemoQExec = '"./PEMO-Q v1.1.2 demo/audioqual_demo.exe"'; % Demo version +end +defaultOptions.ENABLE_PEMOQ = true; +defaultOptions.PESQExec = './PESQ/pesq'; + +if ispc + defaultOptions.EAQUALExec = './EAQUAL/eaqual.exe'; +else % if unix, use wine + defaultOptions.EAQUALExec = 'wine ./EAQUAL/eaqual.exe'; + defaultOptions.pemoQExec = ['wine ' defaultOptions.pemoQExec]; +end + +if nargin<4 + options = defaultOptions; +else + names = fieldnames(defaultOptions); + for k=1:length(names) + if ~isfield(options,names{k}) || isempty(options.(names{k})) + options.(names{k}) = defaultOptions.(names{k}); + end + end +end + +if ~ischar(xRef) && ~ischar(xTest) && length(xRef)~=length(xTest) + warning('EVAL:LENGTH','Different lengths'); + L = min(length(xRef),length(xTest)); + xRef = xRef(1:L); + xTest = xTest(1:L); +end + +if ischar(xRef) + refFile = xRef; + sRef = wavread(refFile); +else + refFile = [tempname '.wav']; + sRef = xRef; + wavwrite(xRef,fs,refFile); +end +if ischar(xTest) + testFile = xTest; + sTest = wavread(testFile); +else + testFile = [tempname '.wav']; + sTest = xTest; + wavwrite(xTest,fs,testFile); +end + + +SNRx = SNR(sRef,sTest); + +try + % if ispc && options.ENABLE_PEMOQ + if options.ENABLE_PEMOQ + %% PEMO-Q + [PSM,PSMt] = aux_pemoq(refFile,testFile,options); + else + warning('audioQualityMeasures:noPQ','PEMO-Q is not available (requires Windows plateform)') + PSM = NaN; + PSMt = NaN; + end + + %% PESQ + PESQ_MOS = aux_pesq(refFile,testFile,options); + + %% EAQUAL (PEAQ) + [EAQUAL_ODG, EAQUAL_DIX] = aux_eaqual(refFile,testFile,options); + + if ~ischar(xRef) + %% Delete temporary files + delete(refFile); + end + if ~ischar(xTest) + delete(testFile); + end + +catch + if ~ischar(xRef) + %% In case of error, delete the temporary files + delete(refFile); + end + if ~ischar(xTest) + delete(testFile); + end + rethrow; +end + + +return + +function [PSM,PSMt] = aux_pemoq(refFile,testFile,options) +if ~isempty(findstr(options.pemoQExec, 'demo')) + fprintf('To unlock PEMO-Q demo, please enter the PIN shown in the new window\n'); +end +[dum, pemo] = system(sprintf('%s %s %s [] [] 0 0 0', options.pemoQExec, refFile, testFile)); +pemo = regexp(pemo, 'PSM.? = \d*.\d*', 'match'); +PSM = str2double(cell2mat(regexp(pemo{1},'\d+.?\d*', 'match'))); +PSMt = str2double(cell2mat(regexp(pemo{2},'\d+.?\d*', 'match'))); + +return + +function PESQ_MOS = aux_pesq(refFile,testFile,options) +[dum fs] = wavread(refFile,'size'); +if ~ismember(fs,[8000 16000]) + error('audioQualityMeasures:badFs',... + '8kHz or 16 kHz sampling frequency required for PESQ'); +end +[dum,s] = system(sprintf('%s +%d %s %s',options.PESQExec,fs,refFile,testFile)); +PESQ_MOS = regexp(s, 'Prediction : PESQ_MOS = \d*.\d*', 'match'); +PESQ_MOS = str2double(PESQ_MOS{end}(length('Prediction : PESQ_MOS = ')+1:end)); +return + +function [EAQUAL_ODG, EAQUAL_DIX] = aux_eaqual(refFile,testFile,options) +[dum fs] = wavread(refFile,'size'); +DELETE_FLAG = false; +if fs<44100 + warning('EAQUAL:BAD_FS',... + 'Sampling frequency is too low for Eaqual (<44.1kHz).\nResampling first (result not relevant)'); + DELETE_FLAG = true; + + x = wavread(refFile); + fsEaqual = 48000; + x = resample(x,fsEaqual,fs); + refFile = [tempname '.wav']; + wavwrite(x,fsEaqual,refFile); + + x = wavread(testFile); + fsEaqual = 48000; + x = resample(x,fsEaqual,fs); + testFile = [tempname '.wav']; + wavwrite(x,fsEaqual,testFile); + + fs = fsEaqual; +end + +[dum,s] = system(sprintf('%s -fref %s -ftest %s -srate %d',options.EAQUALExec,refFile,testFile,fs)); + +EAQUAL_ODG = regexp(s, 'Resulting ODG:\t.?\d*(\.\d*)?', 'match'); +EAQUAL_ODG = str2double(EAQUAL_ODG{end}(length('Resulting ODG: ')+1:end)); +EAQUAL_DIX = regexp(s, 'Resulting DIX:\t.?\d*(\.\d*)?', 'match'); +EAQUAL_DIX = str2double(EAQUAL_DIX{end}(length('Resulting DIX: ')+1:end)); + +if DELETE_FLAG + delete(refFile); + delete(testFile); +end +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/evaluation/exclude_testAudioQualityMeasures.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,70 @@ +function testAudioQualityMeasures +% +% +% Usage: +% +% +% Inputs: +% - +% - +% - +% - +% - +% - +% - +% - +% +% Outputs: +% - +% - +% - +% - +% +% Note that the CVX library is needed. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +soundDir = './'; + +[xRef fs] = wavread([soundDir 'xClean.wav']); + +testFiles = {'xClipped.wav','xEst2.wav','xEstInterp'}; +Nf = length(testFiles); + +SNR = zeros(Nf,1); +PSM = zeros(Nf,1); +PSMt = zeros(Nf,1); +PESQ_MOS = zeros(Nf,1); +EAQUAL_ODG = zeros(Nf,1); +EAQUAL_DIX = zeros(Nf,1); + +options.ENABLE_PEMOQ = true; + +for kf = 1:Nf + xTest = wavread([soundDir testFiles{kf}]); + [SNR(kf) PSM(kf),PSMt(kf),... + PESQ_MOS(kf),EAQUAL_ODG(kf), EAQUAL_DIX(kf)] = ... + audioQualityMeasures(xRef,xTest,fs,options); +end + +for kf = 1:Nf + fprintf('Quality of %s: SNR = %g dB, PSM=%g, PSMt=%g, PESQ=%g, EAQUAL_ODG=%g, EAQUAL_DIX=%g\n',... + testFiles{kf},SNR(kf),PSM(kf),PSMt(kf),PESQ_MOS(kf),EAQUAL_ODG(kf),EAQUAL_DIX(kf)); +end + +Q = [SNR,PSM,PSMt,PESQ_MOS,EAQUAL_ODG,EAQUAL_DIX]; +Qs = {'SNR','PSM','PSMt','PESQ MOS','EAQUAL ODG','EAQUAL DIX'}; + +figure +for k=1:size(Q,2) + subplot(ceil(sqrt(size(Q,2))),ceil(sqrt(size(Q,2))),k) + plot(Q(:,k)) + xlabel('audio files'); + ylabel(Qs{k}) +end +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/makeClippedSignal.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,110 @@ +function [xClipped, IClipped, xClean, clipSizes] = makeClippedSignal(x,clippingLevel,GR) +% Normalize and clip a signal. +% +% Usage: +% [xClipped, IClipped, xClean, clipSizes] = makeClippedSignal(x,clippingLevel,GR) +% +% Inputs: +% - x: input signal (may be multichannel) +% - clippingLevel: clipping level, between 0 and 1 +% - GR (default: false): flag to generate an optional graphical display +% +% Outputs: +% - xClipped: clipped signal +% - IClipped: boolean vector (same size as xClipped) that indexes clipped +% samples +% - xClean: clean signal +% - clipSizes: size of the clipped segments +% +% Note that the input signal is normalized to 0.9999 (-1 is not allowed in +% wav files) to provide xClipped and xClean. +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +if nargin<3 || isempty(GR) + GR = false; +end + +%% Normalization +xMax = 0.9999; +xClean = x/max(abs(x(:)))*xMax; +clippingLevel = clippingLevel*xMax; + +%% DISABLED - Ramp to produce a clipping level that linearly increases +if 0 + xClean = xClean.*(1:length(xClean))'/length(xClean); +end + +%% Clipping (hard threshold) +xClipped = min(max(xClean,-clippingLevel),clippingLevel); +IClipped = abs(xClipped)>=clippingLevel; % related indices + +%% Size of the clipped segments +if nargout>3 || GR + % clipSizes = diff(find(diff(~IClipped))); + % clipSizes = clipSizes(2-(IClipped(1)==0):2:end); + clipSizes = diff(IClipped); + if clipSizes(find(clipSizes,1,'first'))==-1,clipSizes = [1;clipSizes]; end + if clipSizes(find(clipSizes,1,'last'))==1,clipSizes = [clipSizes;-1]; end + clipSizes = diff(find(clipSizes)); + clipSizes = clipSizes(1:2:end); +end + +%% Optional graphical display +if GR + + % Plot histogram of the sizes of the clipped segments + if ~isempty(clipSizes) + figure + hist(clipSizes,1:max(clipSizes)) + title('Size of missing segments') + xlabel('Size'),ylabel('# of segments') + end + + t = (0:length(xClean)-1); % time scale in samples + + % Plot original and clipped signals + figure + plot(t,xClean,'',t,xClipped,'') + legend('original','clipped') + + % Scatter plot between original and clipped signals + figure + plot(xClean,xClipped,'.') + xlabel('Original signal'),ylabel('Clipped signal') + + % Spectrograms + N = 512; + w = hann(N); + fs = 1; + NOverlap = round(.8*N); + nfft = 2^nextpow2(N)*2*2; + figure + subplot(3,3,[1,4]) + spectrogram(xClean,w,NOverlap,nfft,fs,'yaxis') + title('Original') + xlim(t([1,end])) + cl = get(gca,'clim'); + set(gca,'clim',cl); + subplot(3,3,[1,4]+1) + spectrogram(xClipped,w,NOverlap,nfft,fs,'yaxis') + title('Clipped') + set(gca,'clim',cl); + subplot(3,3,[1,4]+2) + spectrogram(xClean-xClipped,w,NOverlap,nfft,fs,'yaxis') + title('Error (=original-clipped)') + set(gca,'clim',cl); + subplot(3,3,7) + plot(t,xClean,'');xlim(t([1,end])) + subplot(3,3,8) + plot(t,xClean,'',t,xClipped,'');xlim(t([1,end])) + subplot(3,3,9) + plot(t,xClean-xClipped,'');xlim(t([1,end])) +end + +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/wRect.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,20 @@ +function w = wRect(L) +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +% rectangular window with length L +% +% Usage: +% w = wRect(L) +% +% Inputs: +% - L - window length +% +% Outputs: +% - w - window +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +w = ones(1,L); +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/Utils/wSine.m Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,21 @@ +function w = wSine(L) +% Symetric sine window with length L +% +% Usage: +% w = wSine(L) +% +% Inputs: +% - L - Window length +% +% Outputs: +% - w - window +% +% ------------------- +% +% Audio Inpainting toolbox +% Date: June 28, 2011 +% By Valentin Emiya, Amir Adler, Maria Jafari +% This code is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). + +w = sin(((0:(L-1))+.5)/L*pi); +return
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/license.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,680 @@ +The code of this toolbox is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +The data files are distributed under specific licenses as stated in the related .txt files in the directory 'Data/'. + +Authors: Valentin Emiya, INRIA, France; Amir Adler, The Technion, Israel; Maria Jafari, Queen Mary University of London, UK. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/toolboxes/AudioInpaintingToolbox/readme.txt Tue Jul 26 15:14:15 2011 +0100 @@ -0,0 +1,70 @@ + +------------------------------------------------- + +Audio Inpainting Toolbox + +By + +Valentin Emiya, INRIA, France +Amir Adler, The Technion, Israel +Maria Jafari, Queen Mary University of London, UK + +Contact: valentin.emiya@inria.fr +------------------------------------------------- + +%%%%%%%%%%%% +Requirements +%%%%%%%%%%%% +The code has been developped in Matlab (R2010a). +The CVX toolbox is required by solvers. + +%%%%%%%%%%%% +Installation +%%%%%%%%%%%% +Just unpack the archive and ensure that you have CVX installed. + +%%%%%%%%%%%%%%% +Getting started +%%%%%%%%%%%%%%% +Just run the files in the subdirectories of 'Experiments/'. +As a starting example, the simplest one is declipOneSoundExperiment.m. + +%%%%%%%%%%%%%%%%%%% +Very quick tutorial +%%%%%%%%%%%%%%%%%%% +The toolbox is organized into several types of components, each type being located in a separate directory: +- Problems (API: '[problemData,solutionData] = generateMyProblem(mysound,problemParam);'): generates a particular problem (e.g. "declip this sound"), with given parameters, and generates the true solution. +- Solvers/algorithms (API: 'solutionEstimate = mySolver(problemData,solverParameters);'): given a problem and the solver parameters (a dictionary, thresholds, and so on), a solver proposes a solution using its particular algorithm +- Utils: e.g. dictionaries, evaluation functions are stored here +- Data: audio datasets including speech, music +- Experiments (API: 'myExperiment(experimentParameters);'): they are the main files one may run. A specific experiment takes a dataset, generates specific problems (e.g. increasing clipping levels), solves each problem with a number of solvers (specified in the experiment parameters), displays the performance for each solver. The experiments can be run without any input argument. In this case, default values will be used. + +You may find more information: +- about each function 'myFunction', by typing 'help myFunction' in Matlab +- in the documented code of each function +- in the extended abstract and slides presented at the SPARS'11 workshop +- in the paper available at http://hal.inria.fr/inria-00577079/en + +%%%%%%%%%%%%%%%%%%%%%%%% +How to cite this toolbox +%%%%%%%%%%%%%%%%%%%%%%%% +Please cite the following paper: +Adler Amir; Emiya Valentin; Jafari Maria; Elad Michael; Gribonval Remi; Plumbley Mark +Audio Inpainting +Submitted to IEEE Transactions on Audio, Speech, and Language Processing (2011) +Available at http://hal.inria.fr/inria-00577079/en. + +%%%%%%%%%%%%%%%%%%%%%%%%%%% +Known issues / Future works +%%%%%%%%%%%%%%%%%%%%%%%%%%% +- The multithread processing of audio frames is not yet available (you may wonder about the Java TCP/IP utils, which will be used soon for this purpose). +- Some solvers based on L1 minimization will be added soon. +- The experiment called 'FromSmallToLargeHoleExperiment' will be added soon. + +%%%%%%% +License +%%%%%%% +The code of this toolbox is distributed under the terms of the GNU Public License version 3 (http://www.gnu.org/licenses/gpl.txt). +The data files are distributed under specific licenses as stated in the related .txt files in the directory 'Data/'. + +
--- a/util/SMALL_init_solver.m Tue Jul 26 15:13:29 2011 +0100 +++ b/util/SMALL_init_solver.m Tue Jul 26 15:14:15 2011 +0100 @@ -1,4 +1,4 @@ -function solver = SMALL_init_solver(varargin) +function solver = SMALL_init_solver(toolbox, name, param, profile) %% Function initialise SMALL structure for sparse representation. % Optional input variables: % toolbox - name of Dictionary Learning toolbox you want to use @@ -17,11 +17,29 @@ % %% -solver.toolbox=[]; -solver.name=[]; -solver.param=[]; -solver.solution=[]; -solver.reconstructed=[]; -solver.time=[]; +if ~ exist( 'toolbox', 'var' ) || isempty(toolbox) + solver.toolbox = []; +else + solver.toolbox = toolbox; +end +if ~ exist( 'name', 'var' ) || isempty(name) + solver.name = []; +else + solver.name = name; +end +if ~ exist( 'param', 'var' ) || isempty(param) + solver.param = []; +else + solver.param = param; +end +if ~ exist( 'profile', 'var' ) || isempty(profile) + solver.profile = 1; +else + solver.profile = profile; +end +solver.add_constraints = 0; +solver.solution = []; +solver.reconstructed = []; +solver.time = []; end \ No newline at end of file
--- a/util/SMALL_solve.m Tue Jul 26 15:13:29 2011 +0100 +++ b/util/SMALL_solve.m Tue Jul 26 15:14:15 2011 +0100 @@ -39,7 +39,10 @@ b = Problem.b; % The right-hand-side vector. end %% -fprintf('\nStarting solver %s... \n', solver.name); +if (solver.profile) + fprintf('\nStarting solver %s... \n', solver.name); +end + start=cputime; tStart=tic; if strcmpi(solver.toolbox,'sparselab') @@ -93,8 +96,10 @@ % Sparse representation time tElapsed=toc(tStart); solver.time = cputime - start; -fprintf('Solver %s finished task in %2f seconds (cpu time). \n', solver.name, solver.time); -fprintf('Solver %s finished task in %2f seconds (tic-toc time). \n', solver.name, tElapsed); +if (solver.profile) + fprintf('Solver %s finished task in %2f seconds (cpu time). \n', solver.name, solver.time); + fprintf('Solver %s finished task in %2f seconds (tic-toc time). \n', solver.name, tElapsed); +end solver.time=tElapsed; % geting around out of memory problem when converting big matrix from % sparse to full... @@ -105,7 +110,7 @@ solver.solution = full(y); end if isfield(Problem,'reconstruct') -% Reconstruct the signal from the solution -solver.reconstructed = Problem.reconstruct(solver.solution); + % Reconstruct the signal from the solution + solver.reconstructed = Problem.reconstruct(solver.solution); end end