function [result_q]=HMC_sparse(template, filters,currSample, stepsize, L)

q=currSample;
sigma = 0.1;
p= normrnd(0,sqrt(sigma),size(currSample));
current_p=p;

p=p- (stepsize/2) * grad_U_sparse(q, filters,template);

for i=1:L
  q=q+ stepsize * p/sigma;
  if(i~=L) 
      p=p-stepsize * grad_U_sparse(q, filters, template); 
  end
end

p=p-stepsize/2 *grad_U_sparse(q, filters, template);


current_U=U(currSample, filters, template);
current_K= sum(sum((current_p.^2/sigma)))/2;
  
proposed_U=U(q, filters, template);
proposed_K=sum(sum((p.^2/sigma)))/2;

test=rand(1);
accProb = exp(current_U-proposed_U+current_K-proposed_K);
fprintf('accept probabilty: %f ', accProb);
if (test<accProb)
   result_q=q;
   disp( [ 'Accepted!' ]);
else
   result_q=currSample;
   disp( [ 'not accepted!' ]);
end
    
end


function result_u = U(currImage, filters, template)
   
 
   [rSample] = sparseFeatureExtraction(single(currImage),filters, template,true);
     
   result_u = - (rSample * template.selectedLambdas') + (norm(currImage(:))^2)/2;
   
   
end







