%==========================================================================
%==========================================================================
%
%                    /$$$$$$$$ /$$$$$$$   /$$$$$$  /$$$$$$$                 
%                   | $$_____/| $$__  $$ /$$__  $$| $$__  $$                
%                   | $$      | $$  \ $$| $$  \__/| $$  \ $$                
%                   | $$$$$   | $$$$$$$ |  $$$$$$ | $$  | $$                
%                   | $$__/   | $$__  $$ \____  $$| $$  | $$                
%                   | $$      | $$  \ $$ /$$  \ $$| $$  | $$                
%                   | $$$$$$$$| $$$$$$$/|  $$$$$$/| $$$$$$$/                
%                   |________/|_______/  \______/ |_______/                 
%                                                                           
%                                                                           
%                                                                           
%                                                    /$$                    
%                                                   |__/                    
%  /$$$$$$  /$$   /$$  /$$$$$$   /$$$$$$   /$$$$$$$ /$$  /$$$$$$$  /$$$$$$ 
% /$$__  $$|  $$ /$$/ /$$__  $$ /$$__  $$ /$$_____/| $$ /$$_____/ /$$__  $$
%| $$$$$$$$ \  $$$$/ | $$$$$$$$| $$  \__/| $$      | $$|  $$$$$$ | $$$$$$$$
%| $$_____/  >$$  $$ | $$_____/| $$      | $$      | $$ \____  $$| $$_____/
%|  $$$$$$$ /$$/\  $$|  $$$$$$$| $$      |  $$$$$$$| $$ /$$$$$$$/|  $$$$$$$
% \_______/|__/  \__/ \_______/|__/       \_______/|__/|_______/  \_______/
%                                                                           
%                                                                           
%                                                                           
%                     /$$$$$$   /$$$$$$   /$$$$$$    /$$                    
%                    /$$__  $$ /$$$_  $$ /$$__  $$ /$$$$                    
%                   |__/  \ $$| $$$$\ $$|__/  \ $$|_  $$                    
%                     /$$$$$$/| $$ $$ $$  /$$$$$$/  | $$                    
%                    /$$____/ | $$\ $$$$ /$$____/   | $$                    
%                   | $$      | $$ \ $$$| $$        | $$                    
%                   | $$$$$$$$|  $$$$$$/| $$$$$$$$ /$$$$$$                  
%                   |________/ \______/ |________/|______/                  
%                                                                           
%                                                                           
%                                                                          
%==========================================================================
%==========================================================================


%% import a simple ebsd dataset using the import_wizard
% use sample40.ang
import_wizard('EBSD')

%% we can put the output of import_wizard here

% crystal symmetry
CS = {... 
  'notIndexed',...
  crystalSymmetry('-3m', [4.9 4.9 5.4], 'X||a', 'Y||b*', 'Z||c*', ...
                 'mineral', 'Quartz', 'color', [0.53 0.81 0.98])};

% plotting convention
setMTEXpref('xAxisDirection','east');
setMTEXpref('zAxisDirection','intoPlane');

% path to files
pname = '/home/rk/mtex/workshop/workshop21/exercises/';


% data from Giulia degli Alessandrini MSc thesis,
% "THE EITA SHEAR ZONE; Val Grosina (N Italy), 2013
% supervised by Neil Mancktelow, Eric Reusser
% data by Karsten Kunze, ETHZ

% fname = [pname '/sample13.ang'];
fname = [pname '/sample40.ang'];

% create an EBSD variable containing the data
ebsd = EBSD.load(fname,CS,'interface','ang',...
  'convertEuler2SpatialReferenceFrame','setting 2');

% note that when we use the import_wizard the "setting" option form OIM is 
% not set, meaning 'setting 1' by default (for historic reasons). However, 
% 'setting 2' seems to be the default in many cases as is also the case here.

%% 1) inspect the ebsd object
ebsd

%% 2) plot the image quality with grey colormap and colorbar
% useful commands: plot, mtexColorMap, mtexColorbar

plot(ebsd,ebsd.iq,'micronbar','on')
mtexColorMap black2white
mtexColorbar('title','image quality','Location','southoutside')

%% 2) select points with a certain property 
% a) plot the confidence index and plot only those points with a 
% confidence index > 0.1,

cond = ebsd.ci > 0.1;
plot(ebsd(cond),ebsd(cond).ci)

% b) assign the notIndexed phase to the points with ci <=0.1
% % useful info: ebsd.phaseMap ebsd.phase

ebsd.phaseMap
ebsd(~cond).phase=-1;
nextAxis
plot(ebsd)

%% 3) inspect the orientations - ipf plots
% a) make an ipf color mapping  with respect to x,y,z
% b) plot the corresponding (inverse) pole figures (with colored points)
% useful commands: ipfHSVKey

v = [xvector yvector zvector];
ck = ipfHSVKey(ebsd('q').CS);

for i = 1:length(v)
    
    ck.inversePoleFigureDirection=v(i);
    color = ck.orientation2color(ebsd('q').orientations);
    plot(ebsd('q'),color)
    mtexTitle(['ref. dir. (' char(v(i)) ')'])
    nextAxis
    plotIPDF(ebsd('q').orientations,color,v(i),'points',1000)
    
   if i<length(v), nextAxis; end 
   
end

%% 4) inspect the orientations - pdf plots
% a) make a c-axis colorcoding and plot a c-axis mapping
% b) plot a polefigure for c,a,m,r,z with the same colorcoding
% useful commands: HSVDirectionKey

cdk=HSVDirectionKey(specimenSymmetry('-1'))
h = Miller({0,0,0,1},{1,1,-2,0},{1,0,-1,0},{1,0,-1,1},{0,1,-1,1},ebsd('q').CS)
cdir = ebsd('q').orientations.*h(1);
cdir.antipodal=1;

color = cdk.direction2color(cdir);

plot(ebsd('q'),color)

figure
plotPDF(ebsd('q').orientations,color,h,'MarkerSize',3)
hold on
plotPDF(ebsd('q').orientations,h,'contour','contours',1:10,'linecolor','k')
hold off

%% 5) colorize all points as a function of angular distance
% from one of the c-axis maxima
% useful commands: calcDensity, (calcPDF) max, angle

pdf = calcDensity(cdir,'antipodal')

odf = calcDensity(ebsd('q').orientations)
pdf = calcPDF(odf,h(1))

[val, lmax] = max(pdf,'numlocal',2)

plot(pdf,'contourf')
annotate(lmax)


% just use the first one
plot(ebsd('q'),angle(lmax(1),cdir)./degree)
nextAxis
plot(ebsd('q'),angle(lmax(2),cdir)./degree)

% or both
plot(ebsd('q'),min(angle_outer(lmax,cdir))/degree)



%% 6) make a colorcoding as a function of the angle between the
% a-axis and the xvector
% useful commands: ipfSpotKey, angle

aA = angle(inv(ebsd('q').orientations)*xvector,h(2));
plot(ebsd('q'),aA/degree)


sck = ipfSpotKey(ebsd('q').CS)
sck.inversePoleFigureDirection=xvector;
sck.center=h(2)
figure
plot(sck)
figure
plot(ebsd('q'),sck.orientation2color(ebsd('q').orientations))


%% 7) extract the ebsd data along a line
% plot the line in the map and plot the pole figure from the extracted data
% useful commands: spatialProfile

plot(ebsd('q'),color)
xy = ginput(2)
[ebsdLine,dist] = spatialProfile(ebsd,xy)
% find the indexed points
ind = ebsdLine.isIndexed;

hold on
plot(xy(:,1),xy(:,2),':k','linewidth',5)
figure
plotPDF(ebsdLine('q').orientations,dist(ind),h,'MarkerSize',3)
 
%% 8) Question session: What else would you want to do?


%% Bonus: remove single pixels which are nonIndexed and 
% completely surrounded by indexed pixels WITHOUT computing grains
% and fill them afterwards with the nearest neighbor interpolation
% useful commands: gridify, squareNeighbors2

ebsd = ebsd.gridify;

% this gives you the indices indices in an n-by-m-by-8 matrix
ind = squareNeighbors2(size(ebsd));

% number_indexed_neigbors
nin = sum(ebsd(ind).isIndexed,3);

% isolated pixels have 8 indexed neighbors
% condition: have 8 indexed neigbors AND be the notIndexed Phase
cond = nin==8 & ebsd.phase==-1;

plot(ebsd)
hold on
plot(ebsd(cond),'FaceColor','r')
hold off

% remove the single points so that we can fill them
ebsd(cond)=[];

ebsd = fill(ebsd)

%% save data for the next exercise (optional)
save('ebsd_sample40.mat','ebsd')
