%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Plotting 2D scans
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% General script for plotting 2D stray field images
% Starting with the measured ESR resonance, convert to stray field, then
% plot

% input: location of 'data.xlsx' (string)
%      : name of sheet (string)
%      : length of the scale bar (um, double)
%      : length of the scale bar (string)
% output: 2D plot of the stray field

% Modified by N. Hedrich 22.07.2020

%%
%%%%%%%%%% Initialization %%%%%%%%%%
clear;clc;

%%%%%%%%%% WHAT YOU NEED TO ENTER %%%%%%%%%%
%location of file to load.
file = '..\data.xlsx';
%sheet to read out
sheet = 'Fig1D (inset)';
%length of scale bar (um)
len = 10;
%length of scale bar (string)
Length = '10 um';
%name of saved image (string)
SaveFile = 'StrayFieldImage.pdf';

%%%Color map:
cmap=([linspace(0,1,32)' linspace(0,1,32)' ones(32,1); ones(32,1) linspace(1,0,32)' linspace(1,0,32)']);

%%%%%%%%%% Load Data %%%%%%%%%%%%%%%%%%%
opts = detectImportOptions(file); 
opts.DataRange = 'A4'; %define start of data
opts.Sheet = sheet; %select the correct sheet

T = readtable(file,opts); %read the xlsx file

x = T.Var1; %extract x values (um)
x = x(~isnan(x)); %remove any possible NaN values

y = T.Var2; %extract y values (um)
y = y(~isnan(y)); %remove any possible NaN values

ESR = T{1:end,4:end}; %extract ESR values (GHz)
a = size(ESR,1); %determine size of the x axis
ESR = ESR(~isnan(ESR)); %remove any possible NaN values
ESR = reshape(ESR,[size(ESR,1)/a,a]); %reshape the ESR matrix to the correct size

x_dat = reshape(repmat(x,size(y)),[size(ESR,2),size(ESR,1)])'; %create the x matrix
y_dat = reshape(repmat(y,size(x)),[size(ESR,1),size(ESR,2)]); %create the y matrix

%%%calculate the background ESR resonance location
L1 = mean(ESR(:,1)); %take the average of the first line
Lend = mean(ESR(:,end)); %take the average of the last line
bkg = (L1+Lend)/2; %take the average of these values as the background 

field_dat = 100*(bkg - ESR)/0.0028; %convert the ESR resonance value (GHz) to stray field (uT)

%%%%%%%%% PLOT FIGURES %%%%%%%%%%%%

%%%determine the extrema of the plot
bottom = min(min(y_dat));
top = max(max(y_dat));
left = min(min(x_dat));
right = max(max(x_dat));

%%%plot
figure;
s=pcolor(x_dat,y_dat,field_dat);
s.EdgeAlpha = 0;
line([left+1,left+len+1],[bottom+0.5,bottom+0.5],'Color','k');
text(0.8,0.45, Length,'Color',[0 0 0]); %might need to set the label location manually
axis image;
box on;

daspect([1 1 1]);

%%%colorbar
colormap(cmap);
h = colorbar;
caxis([-100, 100]);
set(get(h,'label'),'string','Stray Field (uT)');

%%%axis cleanup
hax.XLabel = [];
hax.XTickLabel = [];

hax.YLabel = [];
hax.YTickLabel = [];
set(gca,'Ydir','normal');

%%%save
%saveas(gcf,SaveFile);




