%% Demostration of the use of the UNLocBox solver to solve an image denoising problem of the SMALLBox form
%
% argmin_x ||x||_1 such that ||Ax-b||_2 < sima_t
%
%   The dictionary A is first learn using SMALLbox
%
% Queen Mary University
% 29 August 2012
% Nathanael Perraudin
% nathanael.perraudin@epfl.ch


% % Initialisation
% clear all;
% close all;
% clc;


%% Load an image and create the problem

% Defining Image Denoising Problem as Dictionary Learning
% Problem. As an input we set the number of training patches.

SMALL.Problem = generateImageDenoiseProblem('', 40000);


%%
%   Use KSVD Dictionary Learning Algorithm to Learn overcomplete dictionary

%   Initialising Dictionary structure
%   Setting Dictionary structure fields (toolbox, name, param, D and time)
%   to zero values

SMALL.DL=SMALL_init_DL();

% Defining the parameters needed for dictionary learning

SMALL.DL.toolbox = 'KSVD';
SMALL.DL.name = 'ksvd';

%   Defining the parameters for KSVD
%   In this example we are learning 256 atoms in 20 iterations, so that
%   every patch in the training set can be represented with target error in
%   L2-norm (EData)
%   Type help ksvd in MATLAB prompt for more options.

Edata=sqrt(prod(SMALL.Problem.blocksize)) * SMALL.Problem.sigma * SMALL.Problem.gain;
maxatoms = floor(prod(SMALL.Problem.blocksize)/2);

SMALL.DL.param=struct(...
    'Edata', Edata,...
    'initdict', SMALL.Problem.initdict,...
    'dictsize', SMALL.Problem.p,...
    'iternum', 20,...
    'memusage', 'high');

%   Learn the dictionary

SMALL.DL = SMALL_learn(SMALL.Problem, SMALL.DL(1));

%   Set SMALL.Problem.A dictionary
%   (backward compatiblity with SPARCO: solver structure communicate
%   only with Problem structure, ie no direct communication between DL and
%   solver structures)

SMALL.Problem.A = SMALL.DL.D;
SMALL.Problem.reconstruct = @(x) ImageDenoise_reconstruct(x, SMALL.Problem);

%% Solving the problem with UNLocBox
% This might not be the better way to solve the problem...


% Set the different parameter

SMALL.solver=SMALL_init_solver; % Initialisation
SMALL.solver.toolbox='UNLocBox';     % select the UNLocBox solver
SMALL.solver.name='Douglas_Rachford'; % 'Forward_Backard' 'ADMM' Warning forward backward still need some review...
SMALL.solver.param.sigma=1.15*sqrt(SMALL.Problem.m*SMALL.Problem.n)*SMALL.Problem.sigma; % set the radius of the ball
SMALL.solver.param.max_iter=100;


SMALL.solver=SMALL_solve(SMALL.Problem, SMALL.solver);


SMALL_ImgDeNoiseResult(SMALL);