function[J,grad] = objfun_Comb_NN(x,pr)

% Cost function of the combined, surrogate model-based flowsheet
% Written by Julian Straus, Trondheim 09.12.2018

% This function defines the cost function for the optimization (J) and the
% gradient of the cost function grad. It uses the scaled values. Hence, one
% has to be careful with respect to the values in pr.

% The needed input is defined as
%       x:  	Solution vector
%       pr:     Price for the cost function

% Cost Function
J = pr.feed*x(1) + pr.prod*x(113) + pr.purg*x(152) + pr.comp*(x(10)+x(43)+x(68))+...
    pr.stea*x(96) + pr.cool*(x(141)+x(142)+x(143));

if nargout > 1
    grad = sparse(numel(x),1);
    
    % Feed Stream
    grad(1) = pr.feed;
    
    % Product Stream
    grad(113) = pr.prod;
    
    % Purge Stream
    grad(152) = pr.purg;
        
    % Compressor duty
    grad(10) = pr.comp;
    grad(43) = pr.comp;
    grad(68) = pr.comp;
    
    % Steam Production
    grad(96) = pr.stea;
    
    % Compressor Cooling
    grad(141) = pr.cool;
    grad(142) = pr.cool;
    grad(143) = pr.cool;
end

%% Indices off the variables
% Makeup Section
% Cold Flow HEx1:       27
% Compressor 1 Duty:    10
% Compressor 2 Duty:    43
% Compressor 3 Duty:    68

% Reactor Section
% HEx5 Duty:            96

% Separation Seciont
% Product stream:       113
% HEx8 Duty:            141
% HEx9 Duty:            142
% HEx10 Duty:           143
% Split flow:           152
% Cold Flow HEx6:       105