%% Make the two figures of the Forsythe and Katz graph (1946)

%% Setup
addpath('../mcode');

%% Load
A = readSMAT('../data/Katz-1946-Cottage-4.smat');
xy = load('../data/Katz-1946-Cottage-4.xy');
names = readList('../data/Katz-1946-Cottage-4.names');

n = size(A,1);

pos = spfun(@(x) x==1,A);
neg = spfun(@(x) x==-1,A);
%% Graph structure
figure(1);
clf;
hold on;

possym = pos & pos';
negsym = neg & neg';
posneg = ((pos & neg') | (neg & pos')).*A;

posother = (xor(pos,pos') & ~posneg) & ~pos';
negother = (xor(neg,neg') & ~posneg) & ~neg';

% check we got it right
B = possym - negsym + posneg + posother - negother;
assert(isequal(B,A))
%[ai,aj]=find(B~=A)

[i,j]=find(triu(possym));
for k=1:length(i)
    plot([xy(i(k),1), xy(j(k),1)], [xy(i(k),2), xy(j(k),2)],'b-');
end

[i,j]=find(triu(negsym));
for k=1:length(i)
    plot([xy(i(k),1), xy(j(k),1)], [xy(i(k),2), xy(j(k),2)],'r--');
end

[i,j]=find(triu(posneg));
for k=1:length(i)
    plot([xy(i(k),1), xy(j(k),1)], [xy(i(k),2), xy(j(k),2)],'k:');
end
as = 15000;
asty = 'solid';

[i, j] = find(posother);
for k = 1:length(i)
    a=arrowline([xy(i(k),1), xy(j(k),1)], [xy(i(k),2), xy(j(k),2)],...
        'Color','b','arrowstyle',asty,'LineStyle','-','arrowsize',as);
end

[i, j] = find(negother);
for k = 1:length(i)
    a=arrowline([xy(i(k),1), xy(j(k),1)], [xy(i(k),2), xy(j(k),2)],...
        'Color','r','arrowstyle',asty,'LineStyle','-.','arrowsize',as);
end
plot(xy(:,1),xy(:,2),'k.');

set(gca,'YDir','reverse');
axis equal;
axis tight;
axis off;

set_figure_size([1.5,1.5]);

print('katz-graph.eps','-depsc2')

%% Matrix structure
figure(2);

imagesc(full(A)+2*eye(n));
colormap([180/255 0 0; 1 1 1; 0 0 180/255; 0 0 0]);
axis equal;
axis tight;
axis off;

rect = @(x,y) ...
    line([x-0.5 y+0.5 y+0.5 x-0.5 x-0.5], [x-0.5 x-0.5 y+0.5 y+0.5 x-0.5], ...
    'LineWidth', 1.5, 'Color',[0.55 0.55 0.55]);
rect(1,3);
rect(5,9);
rect(11,14);
rect(20,21);
rect(22,24);
set_figure_size([1.5,1.5]);
print('katz-matrix-im.eps','-depsc2')

%% Matrix structure 2


ms = 4;

figure(2);
clf; hold on;

% These reversals are necessary to get the figure to look right
[i,j] = find(pos);
plot(j,i,'*','Color',[0 0 180/255],'MarkerSize', ms);
[i,j] = find(neg);
plot(j,i,'x','Color', [180/255 0 0],'MarkerSize', ms);
i = 1:n; j = 1:n;
plot(j,i,'.','Color', [0 0 0]);
rect = @(x,y) ...
    line([x-0.5 y+0.5 y+0.5 x-0.5 x-0.5], [x-0.5 x-0.5 y+0.5 y+0.5 x-0.5], ...
    'LineWidth', 1.5, 'Color',[0.55 0.55 0.55]);
rect(1,3);
rect(5,9);
rect(11,14);
rect(20,21);
rect(22,24);
plot(0,0,'.','Color',[0.999 0.999 0.999]); % fix bad cut-off
axis equal;
axis tight;
axis off;


set(gca,'YDir','reverse');

set_figure_size([1.5,1.5]);

print('katz-matrix.eps','-depsc2')