function [y_infer, loss, delta_feature_mapping, hamm_y_yi]= infer_most_vialated_feature_mapping_v1(prob,G, w, x_inst, y_inst)
%%
nodecnt = prob.num_label; %number of nodes
num_edges = size(G,1);  %number of edges
num_state = 2;

%w contains 2*nodes + 4*edges rows
%nodes
pr_w_dot = w*x_inst';
pr_w_dot_node_inst = zeros(2*nodecnt,1);
indx_node = [0:2:2*nodecnt-2];
pos_map_node = y_inst + 1 + indx_node;
pr_w_dot_node_inst(pos_map_node,1) = pr_w_dot(pos_map_node,:);

%edges
if num_edges>0
    indx_edge = [0:4:4*(num_edges-1)]';
    pos_map_edge = 2*y_inst(1,G(:,1)) + y_inst(1,G(:,2)) + 1 + indx_edge';
    pr_w_dot_edges_inst = zeros(4*num_edges,1);
    pr_w_dot_edges_inst(pos_map_edge,1) = pr_w_dot(pos_map_edge + 2*nodecnt,:);
else
    pr_w_dot_edges_inst = 0;
end
% for unknon y, y^k \in {1,0}
%node potential
nodes_pfunc = zeros(2,nodecnt);
delta_positive = ones(1,nodecnt);
delta_positive((y_inst==1)) = 0;
delta_negitive = ones(1,nodecnt);
delta_negitive((y_inst==0)) = 0;
nodes_pfunc(1,:) = pr_w_dot(1:2:2*nodecnt)' + delta_negitive;
nodes_pfunc(2,:) = pr_w_dot(2:2:2*nodecnt)' + delta_positive;


%edge potential
theta_edge = zeros(4,num_edges);
if num_edges>0
    theta_edge(1,:) = pr_w_dot(2*prob.num_label+1:4:end);  %y_i = 0, y_j=0
    theta_edge(2,:) = pr_w_dot(2*prob.num_label+2:4:end); %y_i = 0, y_j=1
    theta_edge(3,:) = pr_w_dot(2*prob.num_label+3:4:end);  %y_i = 1, y_j=0
    theta_edge(4,:) = pr_w_dot(2*prob.num_label+4:4:end); %y_i = 1, y_j=1
end
%inference
if num_edges==0
    y_infer_= MRFMex(nodecnt,  num_state* ones(1,nodecnt), zeros(2,0), double(nodes_pfunc), zeros(4,0), 100);
else
    y_infer_= MRFMex(nodecnt,  num_state* ones(1,nodecnt), G'-1, nodes_pfunc, theta_edge, 100);
end
y_infer = double(y_infer_)';

%%compute loss after y_infer
pos_map_node_infer = y_infer + 1 + indx_node;
pr_w_dot_node_infer = zeros(2*nodecnt,1);
pr_w_dot_node_infer(pos_map_node_infer,1) = pr_w_dot(pos_map_node_infer,:);

%edges
if num_edges>0
    pos_map_edge_infer = 2*y_infer(1,G(:,1)) + y_infer(1,G(:,2)) + 1 + indx_edge';
    pr_w_dot_edges_infer = zeros(4*num_edges,1);
    pr_w_dot_edges_infer(pos_map_edge_infer,1) = pr_w_dot(pos_map_edge_infer + 2*nodecnt,:);
else
    pr_w_dot_edges_infer = 0;
end

is_not_the_same = find(y_infer~=y_inst);
hamm_y_yi = length(is_not_the_same);
loss = hamm_y_yi + sum(pr_w_dot_node_infer) + sum(pr_w_dot_edges_infer) - (sum(pr_w_dot_edges_inst) + sum(pr_w_dot_node_inst)) ;


%calculate delta_mapping
y_feature_inst = zeros(2*nodecnt + 4*num_edges,1);
y_feature_infer = zeros(2*nodecnt + 4*num_edges,1);

%node
y_feature_inst(pos_map_node) = 1;
y_feature_infer(pos_map_node_infer) = 1;

%edge
if num_edges>0
    y_feature_inst(pos_map_edge+2*nodecnt) = 1;
    y_feature_infer(pos_map_edge_infer+2*nodecnt) = 1;
end
   
delta_feature_mapping = y_feature_inst - y_feature_infer;

