% Chad Myers
% ELE 571
% File: get_delta.m
% ------------------------
% The get_delta function is part of the snakeGUI program for
% demonstrating SNAKE active contours. The function computes the
% appropriate x,y variation for a given node on a SNAKE contour to minimize
% the contour energy.  The function accepts the node number, contour
% vector, sigma (temperature), the learning rate, and the elasticity
% constant as parameters.  It returns a 2-component vector of variations
% along x and y axes.


function delta = get_delta(i,snake,ellipse,sigma,learning_rate,elasticity)
    [snake_len,temp] = size(snake);
    [ellipse_len,temp] = size(ellipse);
    
    i_plus_one = mod(i+1,snake_len);
    if(i_plus_one == 0) i_plus_one = snake_len;
    end
        
    i_plus_two = mod(i+2,snake_len);
    if(i_plus_two == 0) i_plus_two = snake_len;
    end
        
    i_minus_one = i-1;
    if(i_minus_one < 1) i_minus_one = snake_len;
    end
    
    delta = zeros(1,2);
    for j=1:ellipse_len,
        temp = 0;
        temp = 0;
        
        for k=1:snake_len
            diff = [ellipse(j,1)-snake(k,1),ellipse(j,2)-snake(k,2)];
            temp = temp + exp(- (sqrt(diff*diff'))/(2*sigma^2));
        end
        
        diff = [ellipse(j,1)-snake(i,1),ellipse(j,2)-snake(i,2)];
        lambda = (exp(- (sqrt(diff*diff'))/(2*sigma^2)))/temp;
        
        if(isnan(lambda)) lambda = 0;
        end
        
        delta = delta + lambda*[ellipse(j,1)-snake(i,1),ellipse(j,2)-snake(i,2)];
    end
    
        
    if(isnan(delta(1))) delta(1) = 0;
    else delta(1) = delta(1) + elasticity*(snake(i_plus_one,1)-2*snake(i,1)+snake(i_minus_one,1));
    end
    
    if(isnan(delta(2))) delta(2) = 0;
    else delta(2) = delta(2) + elasticity*(snake(i_plus_one,2)-2*snake(i,2)+snake(i_minus_one,2));
    end
    
    delta = learning_rate*delta;
