%% Import Script for EBSD Data
%
% Example importation of Aluminum data from TSL system *.osc file
% Data from Anne-Laure HELBERT
% ICMMO (Institut de Chimie Molèculaire et des Matèriaux d'Orsay) - UMR 8182
% LPCES (Laboratoire de Physico-Chimie de l'Etat Solide )
% Bat. 410, Universitè Paris Sud, F- 91405 Orsay Cedex 
%
% MTEX 3.5.0
%
% Script by David Mainprice 4/09/2014
%
%% clear memory and close plots - for new analysis of EBSD data
clear all
close all
%% Specify Crystal and Specimen Symmetries

% crystal symmetry
CS = symmetry('43', 'mineral', 'Aluminum', 'color', 'light blue');

% specimen symmetry
SS = symmetry('triclinic');

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

%% Specify File Names

% path to files
pname = '/MatLab_Programs';

% which files to be imported
fname = [pname '/Al-210.osc'];

%% Import the Data

% create an EBSD variable containing the data
ebsd = loadEBSD(fname,CS,SS,'interface','osc',...
  'wizard')
%
%***********************************************************************
%% Fix the map aspect ratio and dimensions
%***********************************************************************
ratio = (max(get(ebsd,'x')) - min(get(ebsd,'x')))...
       /(max(get(ebsd,'y')) - min(get(ebsd,'y')));
% plot height (you can change this value)
% I normally use for plot_h = 600
% But for teaching larger plots with plot_h = 1200 is useful
plot_h = 1200;
% plot width with correct aspect ratio
plot_w = round(plot_h*ratio);

%% Standard gray map 8-bit image quality (IQ) Map - good indicator of grain boundaries
% non-index is black and grain internal microstructure more visible
% 255 levels RGB=000 (black) to RGB=111 (white)
close all
figure('position',[200 200 plot_w plot_h])
std_gray = makeColorMap([0 0 0],[0.5 0.5 0.5],[1 1 1],255);
plot(ebsd,'property','imagequality');
colormap(std_gray)
savefigure('/MatLab_Programs/Image_Quality_map_Al_210C.png')

%% Orientation IPF map sample direction Z
close all
figure('position',[0 0 plot_w plot_h])
% IPF sample direction z 'into plane' direction EBSD map (r = zvector)
plot(ebsd('Aluminum'),'colorcoding','ipdfHSV','r',zvector,'antipodal')
% red grains   [100]//Z
% green grains [101]//Z
% blue grains  [111]//Z
savefigure('/MatLab_Programs/Orientation_map_ipf_z_Al_210C.pdf')
%%
% inverse pole figure (IPF) colorbar for orientation
ebsdColorbar(symmetry('43'),'antipodal')
% title of colorbar
title('IPF colorbar cubic 43 antipodal','FontSize',12)
savefigure('/MatLab_Programs/IPF_colorbar_Cubic_43_antipodal.png')
%% Detect grains using the segmentation angle and keep non-indexed option
%**************************************************************************
%
% You can loop over this cell changing segmentation angle and the
% the 'keepNotIndexed' options
% You should compared the resulting grain map with EBSD (pixel) phase
% or orientation (pixel) map
%**************************************************************************
%
disp(' ')
disp(' Grain segmentation angle option ')
disp(' Choose a high angle typically between 10 to 15 degrees for geological samples')
disp(' OR choose low angle of 2 degrees if you want to detect sub-grains')
segmentation_angle = input('The segmentation angle (e.g. 2-15):');
segAngle = segmentation_angle*degree;
%
disp(' ')
disp(' Keep non-indexed points option ')
disp('*1= Scientifically correct, not extrapolating raw indexed data')
disp('    model grains BUT keep non-index points')
disp(' 2= May be more geologically correct in some cases, use with care')
disp('    model grains AND include non-index points within grains boundaries')
disp('    N.B. this option does NOT ADD map pixels with neighouring ORIENTATIONS')
non_indexed_option = input('Option an integer  (1-2):');
%
% keep non-indexed
if(non_indexed_option == 1)
  grains = calcGrains(ebsd,'angle',segAngle,'keepNotIndexed')
end
% remove non-indexed points
if(non_indexed_option == 2)
  grains = calcGrains(ebsd,'angle',segAngle)
end 
%
% number of ORIENTATIONS using length
n_Aluminum_orientations = length(grains('Aluminum'))
% number of GRAINS using numel
n_Aluminum_grains = numel(grains('Aluminum'))
% plot 'grain' phase map
figure('position',[200 200 plot_w plot_h])
plot(grains,'property','phase')
%
%**************************************************************************
%% Removing small grains - not representative small grains, may be errors
%**************************************************************************
%
% You can loop over this cell changing number of indexed points per grain
% You should compared the resulting grain map with EBSD (pixel) phase
% or orientation (pixel) map
%**************************************************************************
%
disp(' ')
disp(' Small grains option ')
disp(' Remove small grains containing less than a critical')
disp(' number of indexed points as they error prone or ')
disp(' If you require an accurate grain size and shape analysis')
disp(' the recommended minimum number indexed points per grain size is 10')
disp(' You can decide to keep all grain by accepting all grains with 0')
small_grains_option = input('Indexed points per grain an integer (e.g. 0-10):');
%
% remove grains containing less than critical number of indexed points, 
selected_grains = grains(grainSize(grains)>small_grains_option);
% number of ORIENTATIONS using length
n_Aluminum_orientations = length(grains('Aluminum'))
% number of GRAINS using numel
n_Aluminum_grains = numel(grains('Aluminum'))
% plot 'grain' map
figure('position',[200 200 plot_w plot_h])
plot(selected_grains,'property','phase')
%%
%**************************************************************************
% Detecting twins - For example for FCC metals
%                   Sigma 3 twin 3 <111> / 60.0 degrees
%               and Sigma 9 twin 9 <110> / 38.9 degrees
%**************************************************************************
%
% Define misorientation rotations for twins
%
% Sigma 3 twin <111> / 60 degrees
Sigma_3 = rotation('axis',Miller(1,1,1,CS,'uvw','phase','Aluminum'),'angle',60.0*degree)
% Sigma 9 twin 9 <110> / 38.9 degrees
Sigma_9 = rotation('axis',Miller(1,1,0,CS,'uvw','phase','Aluminum'),'angle',38.9*degree)
%**************************************************************************
%% Estimate twin fractions
%**************************************************************************
% Calculate twin boundary segment length satisfying the special rotation
% of twins within detection error for each grain
%
Detection_angle = 2.0*degree;
% Sigma3
Sigma3_length = sum(perimeter(selected_grains('Aluminum'),Sigma_3,'delta',Detection_angle));
% Sigma9
Sigma9_length = sum(perimeter(selected_grains('Aluminum'),Sigma_9,'delta',Detection_angle));
% Total lengths of all plagioclase twins
Total_Twin_length = Sigma3_length + Sigma9_length;
% Total length of all Aluminum boundaries (twins and others)
Total_Grain_Aluminum_length = sum(perimeter(selected_grains('Aluminum')));
% Fractions : Twin/total Twin
% Sigma3
Sigma3_Fraction = 100 * Sigma3_length/Total_Grain_Aluminum_length;
% Sigma 9
Sigma9_Fraction = 100 * Sigma9_length/Total_Grain_Aluminum_length;
Total_Twin_Fraction_Al =  100 * Total_Twin_length/Total_Grain_Aluminum_length;
%%
%**************************************************************************
% Print twin table
%**************************************************************************
fprintf('   \n')
fprintf(' Aluminum twin table \n')
fprintf('   \n')
fprintf('%s %6.2f\n',' Detection angle =',Detection_angle/degree)
fprintf(' -----------------------------------------\n')
fprintf(' Twin law                             Twin fractions (%%) \n')
fprintf('%s %6.2f  \n',' Sigma 3 twin <111> / 60.0 degrees ',Sigma3_Fraction)
fprintf('%s %6.2f  \n',' Sigma 9 twin <110> / 38.9 degrees ',Sigma9_Fraction)
fprintf('   \n')
fprintf('%s %6.2f  \n',' All twins/all Aluminum boundaries ',Total_Twin_Fraction_Al)
fprintf('   \n')

%%
%**************************************************************************
% Determine all MTEX standard Grain Size and Shape parameters
% for ALL phases in 'selected_grains' or selected_grains('Aluminum') etc
%**************************************************************************
%
% calculate all parameters
% ** area (with holes = non-indexed points)
g_area = area(selected_grains);
% ** aspect ratio is the ratio between the two (X/Y) principal components
% what we normally use
g_aspectratio = aspectratio(selected_grains);
% centroid = barycenter of the grain-polygon, with respect to its holes
% note that the barycenter can be outside the grain for some complex shapes
g_centroid = centroid(selected_grains);
% equivalent radius er = sqrt(area/pi)
g_equivalentradius = equivalentradius(selected_grains);
% equivalent diameter ed = 2*sqrt(area/pi)
g_equivalentdiameter = 2 * equivalentradius(selected_grains);
% equivalent perimeter ep = 2*pi*equivalent radius
g_equivalentperimeter =  equivalentperimeter(selected_grains);
% calculates the perimeter (p) of a grain, with holes
g_perimeter = perimeter(selected_grains);          
% shapefactor = perimeter/equivalent perimeter = p/ep
% this parameter is more like tortuosity of grain boundaries
% (total boundary length / length for circle with same area)
g_shapefactor = shapefactor(selected_grains);
% increase number of bins for greater resolution
nbins=25;
% text size
font_size_text=16;
% close all plots
close all
%%
%**************************************************************************
% Plot frequency versus equivalent grain diameter
%**************************************************************************
% get counts per bin and bin centres (in microns)
[g_diameter_counts,g_diameter_bin_centres] = hist(g_equivalentdiameter,nbins);
% define bin lo and hi ranges in Equivalent diameter (microns)
% avoid 2 - 1 sometimes gives slight error
Bin_width = g_diameter_bin_centres(3)-g_diameter_bin_centres(2);
Half_bin_width = Bin_width/2.0;
Bin_lo=zeros(nbins);
Bin_hi=zeros(nbins);
for i=1:nbins
    Bin_lo(i) = g_diameter_bin_centres(i)-Half_bin_width;
    Bin_hi(i) = g_diameter_bin_centres(i)+Half_bin_width;
end
% ensure all diameters of data in bin window
Bin_lo(1)=min(g_equivalentdiameter);
Bin_hi(nbins)=max(g_equivalentdiameter);
% Percent counts per bin
g_diameter_percent = (100*g_diameter_counts)/sum(g_diameter_counts);
% plot
figure
bar(g_diameter_bin_centres,g_diameter_percent,'histc')
% plot labels
xlabel('Equivalent grain diameter (microns)','FontSize',font_size_text)
ylabel('Frequency (%)','FontSize',font_size_text)
% plot title
title('Equivalent grain diameter distribution','FontSize',font_size_text)
% save plot
savefigure('/MatLab_Programs/Plot_freqency_grain_diameter_histogram_Al_210C.png')
%%
%**************************************************************************
% Plot frequency versus Log equivalent grain diameter
%**************************************************************************
% get counts per bin and bin centres (in microns)
[g_diameter_counts,g_diameter_bin_centres] = hist(g_equivalentdiameter,nbins);
% define bin lo and hi ranges in Equivalent diameter (microns)
% avoid 2 - 1 sometimes gives slight error
Bin_width = g_diameter_bin_centres(3)-g_diameter_bin_centres(2);
Half_bin_width = Bin_width/2.0;
Bin_lo=zeros(nbins);
Bin_hi=zeros(nbins);
for i=1:nbins
    Bin_lo(i) = g_diameter_bin_centres(i)-Half_bin_width;
    Bin_hi(i) = g_diameter_bin_centres(i)+Half_bin_width;
end
% ensure all diameters of data in bin window
Bin_lo(1)=min(g_equivalentdiameter);
Bin_hi(nbins)=max(g_equivalentdiameter);
% Percent counts per bin
g_diameter_percent = (100*g_diameter_counts)/sum(g_diameter_counts);
% plot
figure
bar(g_diameter_bin_centres,g_diameter_percent,'histc')
% set log grain diameter scale
set(gca,'XScale','log')
% plot labels
xlabel('Log equivalent grain diameter (microns)','FontSize',font_size_text)
ylabel('Frequency (%)','FontSize',font_size_text)
% plot title
title('Equivalent grain diameter distribution','FontSize',font_size_text)
% save plot
savefigure('/MatLab_Programs/Plot_freqency_Log_grain_diameter_histogram_Al_210C.png')
%%
%**************************************************************************
% Grain diameter (plot percent weighted by area fraction)
%**************************************************************************
%
% Total surface area
Total_surface_area = sum(g_area);
% accumulate in bins
n_sample=length(g_equivalentdiameter);
area_per_bin = zeros(nbins);
area_counts_per_bin = zeros(nbins);
for n=1:n_sample
% search bins
      for i=1:nbins
           if (g_equivalentdiameter(n) >= Bin_lo(i)) && ...
              (g_equivalentdiameter(n) <= Bin_hi(i))
              area_per_bin(i)=area_per_bin(i)+g_area(n);
              area_counts_per_bin(i)=area_counts_per_bin(i)+1;
           end
      end
end
% Percent surace area per bin
g_counts_percent_wt_area = zeros(nbins);
for i=1:nbins
    g_counts_percent_wt_area(i) = 100.0*area_per_bin(i,1)/Total_surface_area;
end
% get array into format (1 x ibin)
g_counts_percent_wt_area2 = g_counts_percent_wt_area(:,1);
% transpose
g_counts_percent_wt_area3 = g_counts_percent_wt_area2';
% plot
figure;
bar(g_diameter_bin_centres,g_counts_percent_wt_area2,'histc')
xlabel('Grain diameter (microns)','FontSize',font_size_text)
ylabel('Frequency (%)','FontSize',font_size_text)
% plot title
title('Grain diameter distribution - Weighted by Area fraction','FontSize',font_size_text)
% plot file name
savefigure('/MatLab_Programs/Plot_hist_grain_diameter_wt_area_Al_210C.png')
%%
%**************************************************************************
% grain diameter (plot percent counts AND weighted by area fraction)
%**************************************************************************
% vertically concatenates and transposed
Combined_count_wt_area = [g_diameter_percent; g_counts_percent_wt_area3]';
% plot
figure;
bar(g_diameter_bin_centres,Combined_count_wt_area,'histc')
xlabel('Equivalent Grain diameter (microns)','FontSize',font_size_text)
ylabel('Frequency (%)','FontSize',font_size_text)
% plot title
title('Grain diameter distribution - Number & Area fraction','FontSize',font_size_text)
hold off
legend('Number','Area fraction')
% plot file name
savefigure('/MatLab_Programs/Plot_hist_grain_diameter_counts_wt_area_Al_210C.png')
%**************************************************************************
%% Image quality (IQ) with misorientation boundaries all angles black
%**************************************************************************
close all
figure('position',[0 0 plot_w plot_h])
% band contrast map
plot(ebsd,'property','imagequality');
% gray color map
colormap(gray)
%colorbar
hold on
% misorientation boundaries color 'k' = black
plotBoundary(selected_grains,'linecolor','k','linewidth',0.2)
hold off
title('Image quality (IQ) map with misorienation boundaries (black)','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/IQ_map_with white_grain_sub_boundaries_Al_210C.png')
%**************************************************************************
%% Orientation IPF map sample direction Z with blue misorientation boundaries
%**************************************************************************
close all
figure('position',[200 200 plot_w plot_h])
% IPF sample direction z 'into plane' direction EBSD map (r = zvector)
plot(ebsd('Aluminum'),'colorcoding','ipdfHSV','r',zvector,'antipodal')
% Standard IPF colorbar for High-Cubic (43) with antipodal option
% red grains   [100] parallel sample Z
% green grains [101] parallel sample Z
% blue grains  [111] parallel sample Z
hold on
% misorientation boundaries color 'b' = blue
plotBoundary(selected_grains,'linecolor','b','linewidth',0.2)
hold off
title('Orientation IPF-Z map with misorienation boundaries (blue)','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/IPF_z_map_with_blue_grain_sub_boundaries_Al_210C.pdf')
%**************************************************************************
%% EBSD map with misorientation boundaries angle ranges in colour
% With No overlay
%**************************************************************************
close all
figure('position',[0 0 plot_w plot_h])
% plot all misorientation boundaries of all angles as black lines (k=black)
plotBoundary(selected_grains,'linecolor','k','linewidth',1.3)
hold on
LineThickness = 1.3;
% superpose misorientation boundaries with specific angle ranges
% 20-25 magenta, 15-20 cyan, 10-15 blue,5-10 green,0-5 red
plotBoundary(selected_grains,'property',[20 25]*degree,'linecolor','m','linewidth',LineThickness)
plotBoundary(selected_grains,'property',[15 20]*degree,'linecolor','c','linewidth',LineThickness)
plotBoundary(selected_grains,'property',[10 15]*degree,'linecolor','b','linewidth',LineThickness)
plotBoundary(selected_grains,'property',[ 5 10]*degree,'linecolor','g','linewidth',LineThickness)
plotBoundary(selected_grains,'property',[ 2  5]*degree,'linecolor','r','linewidth',LineThickness)
hold off
% legend
legend('>25^\circ',...
       '20^\circ-25^\circ',...
       '15^\circ-20^\circ',...
       '10^\circ-15^\circ',...
       '5^\circ-10^\circ',...
       '0^\circ-5^\circ','Location','SouthOutside')
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
title('Misorientation boundaries colour angles map','FontSize',18)
savefigure('/MatLab_Programs/Map_with_colour_grain_sub_boundaries_ranges_Al_210C.pdf')   
%**************************************************************************
%% Plot internal misorientation AXES from mean grain orientations
% No over lay
%**************************************************************************
figure('position',[0 0 plot_w plot_h])
plot(selected_grains,'property','mis2mean','antipodal')
colorbar
title('Misorientation AXES from the mean map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Grain_map_mis2mean_Axes_only_color_Al_210C.pdf')
%**************************************************************************
%% Plot internal misorientation AXES from mean grain orientations (antipodal)
%**************************************************************************
close all
figure('position',[0 0 plot_w plot_h])
hold all
plot(selected_grains,'property','mis2mean','antipodal')
plotBoundary(selected_grains,'linecolor','k','linewidth',1)
hold off
title('Misorientation AXES from the mean map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Grain_map_mis2mean_Axes_boundaries_color_antipodal_Al_210C.pdf')
%**************************************************************************
%% plot internal misorientation ANGLES from the mean grain orientations
%**************************************************************************
close all
figure('position',[0 0 plot_w plot_h])
hold all
plot(selected_grains,'property','mis2mean','colorcoding','angle')
plotBoundary(selected_grains,'linecolor','k','linewidth',1)
hold off
colorbar
title('Misorientation ANGLES from the mean map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Grain_map_mis2mean_Angle_boundaries_color_Al_210C.pdf')
%**************************************************************************
%% 1st order Kernel average misorientation angle between adjacent measurements
%**************************************************************************
close all
figure('position',[0 0 plot_w plot_h])
plotKAM(selected_grains)
hold on
plotBoundary(selected_grains,'linecolor','k','linewidth',1.5)
colorbar
title('Kernel average misorientation (KAM) 1st order map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Map_KAM_1st_angles_from_mean_within_grains_Al_210.pdf')
%**************************************************************************
%% 2nd order Kernel average misorientation angle between adjacent measurements
%**************************************************************************
close all
figure('position',[0 0 plot_w plot_h])
plotKAM(selected_grains,'secondorder')
hold on
plotBoundary(selected_grains,'linecolor','k','linewidth',1.5)
colorbar
title('Kernel average misorientation (KAM) 2nd order map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Map_KAM_2nd_angles_from_mean_within_grains_Al_210.pdf')
%
%**************************************************************************
% single grain analysis
%**************************************************************************
%
%
%**************************************************************************
%% plot all grains and select a grain using the a curser on the phase map
%**************************************************************************
% plot grain map
close all
figure('position',[0 0 plot_w plot_h])
plot(selected_grains,'property','phase')
% selecting a single grain by x,y coordinates
disp(' ') 
disp('Select grain with cursor and one mouse click')
disp(' ')
%helpdlg('Move cursor to grain, CLICK to select','GRAIN SELECTION')
% Displays a cursor over the map and waits for one click on the selected grain 
[xgg, ygg]=ginput(1); 
% select single grain by position in map
selected_single_grain = findByLocation(grains,[xgg  ygg])
% fix the grain map aspect ratio and dimensions
ratio = (max(get(selected_single_grain,'x')) - min(get(selected_single_grain,'x')))...
       /(max(get(selected_single_grain,'y')) - min(get(selected_single_grain,'y')));
% plot height (you can change this value)
plot_hgrain = 1200;
% plot width with correct aspect ratio
plot_wgrain = round(plot_hgrain*ratio);
% calculates the x,y barycenter of the  single grain-polygon
bary_center_xy = centroid(selected_single_grain);
figure('position',[0 0 plot_wgrain plot_hgrain])
% plot boundary, grain, bary center (red square)
plotBoundary(selected_single_grain,'linewidth',2)
hold on
plot(bary_center_xy(1),bary_center_xy(2),...
 's','MarkerEdgeColor','k','MarkerFaceColor','r','MarkerSize',10)
hold off
grain_mean_orientation = get(selected_single_grain,'meanOrientation')
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Selected_Single_grain_1_Al_210C.pdf')
%**************************************************************************
%% Visualize the misorientation ANGLE from mean within a grain
%**************************************************************************
% with black grain boundaries
close all
% get all misorientations from the mean orientation
o = get(selected_single_grain,'mis2mean')
max_deviation_degrees = max(angle(o))/degree
min_deviation_degrees = min(angle(o))/degree
% plot misorientation angles from the mean
figure('position',[200 200 plot_wgrain plot_hgrain])
hold all
plotspatial(selected_single_grain,'property',angle(o)/degree)
% plot grain boundary
plotBoundary(selected_single_grain,'linewidth',2)
hold off
title('Misorientation ANGLE from mean within single grain','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Misorientation_angles_from_mean_within_grain_plus_GB_1_Al_210C.pdf')
%**************************************************************************
%% Visualize the misorientation ANGLE from mean within a grain
%**************************************************************************
% with black grain boundaries
close all
% get all misorientations from the mean orientation
o = get(selected_single_grain,'mis2mean')
max_deviation_degrees = max(angle(o))/degree
min_deviation_degrees = min(angle(o))/degree
% plot misorientation angles from the mean
figure('position',[200 200 plot_wgrain plot_hgrain])
hold all
plotspatial(selected_single_grain,'property',angle(o)/degree)
%hold on
LineThickness = 3;
% superpose misorientation boundaries with specific angle ranges
% 20-25 magenta, 15-20 cyan, 10-15 blue,5-10 green,0-5 red
plotBoundary(selected_single_grain,'property',[20 25]*degree,'linecolor','m','linewidth',LineThickness)
plotBoundary(selected_single_grain,'property',[15 20]*degree,'linecolor','c','linewidth',LineThickness)
plotBoundary(selected_single_grain,'property',[10 15]*degree,'linecolor','b','linewidth',LineThickness)
plotBoundary(selected_single_grain,'property',[ 5 10]*degree,'linecolor','g','linewidth',LineThickness)
plotBoundary(selected_single_grain,'property',[ 2  5]*degree,'linecolor','r','linewidth',LineThickness)
hold off
title('Misorientation ANGLE from mean within single grain - color boundaries','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Misorientation_angles_from_mean_within_grain_plus_color_GB_1_Al_210C.pdf')
%**************************************************************************
%% Visualize the misorientation ANGLE from mean within a grain
%**************************************************************************
% no grain boundaries but with colorbar
close all
% get all misorientations from the mean orientation
o = get(selected_single_grain,'mis2mean')
max_deviation_degrees = max(angle(o))/degree
min_deviation_degrees = min(angle(o))/degree
% plot misorientation angles from the mean
figure('position',[200 200 plot_wgrain plot_hgrain])
plotspatial(selected_single_grain,'property',angle(o)/degree)
colorbar
title('Misorientation ANGLE from mean within single grain','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Misorientation_angles_from_mean_within_grain_1_plus_colorbar_Al_210C.pdf')
%**************************************************************************
%% Visualize the misorientation AXIS from mean within a grain
%**************************************************************************
close all
figure('position',[200 200 plot_wgrain plot_hgrain])
hold on
plotspatial(selected_single_grain,'property','mis2mean','antipodal')
% plot grain boundary
plotBoundary(selected_single_grain,'linewidth',2)
hold off
title('Misorientation Axis from mean within single grain','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Misorientation_axes_from_mean_within_grain_1_Al_210C.pdf')
%**************************************************************************
%% 1st order Kernel average misorientation angle between adjacent measurements
%**************************************************************************
close all
figure('position',[200 200 plot_wgrain plot_hgrain])
plotKAM(selected_single_grain)
hold on
plotBoundary(selected_single_grain,'linecolor','k','linewidth',2)
colorbar
title('Kernel average misorientation (KAM) 1st order map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Map_KAM_1st_angles_from_mean_within_grains_1_Al_210.pdf')
%**************************************************************************
%% 2nd order Kernel average misorientation angle between adjacent measurements
%**************************************************************************
close all
figure('position',[200 200 plot_wgrain plot_hgrain])
plotKAM(selected_single_grain,'secondorder')
hold on
plotBoundary(selected_single_grain,'linecolor','k','linewidth',2)
colorbar
title('Kernel average misorientation (KAM) 2nd order map','FontSize',18)
% Correct MatLab problem with colour buffer
set(gcf,'renderer','zbuffer')
savefigure('/MatLab_Programs/Map_KAM_2nd_angles_from_mean_within_grains_1_Al_210.pdf')
%**************************************************************************
%% plot a histogram of the misorientation angles from the mean
%**************************************************************************
close all
figure('position',[0 0 600 600])
Mis_data = angle(o)/degree;
% stats
max_Mis = max(Mis_data)
min_Mis = min(Mis_data)
mean_Mis = mean(Mis_data)
std_dev_Mis = std(Mis_data)
nbins = 25;
hist(Mis_data,nbins)
xlabel('Misorientation angles in degrees','FontSize',18)
ylabel('Counts','FontSize',18)
title('Histogram of the misorientation angles from the mean - single grain','FontSize',18)
savefigure('/MatLab_Programs/Histo_misorientation_angles_from_mean_within_grain1_Al_210.png')
%**************************************************************************
%% Kernel averaged misorientation (KAM) histogram
%**************************************************************************
KAM_data = calcKAM(selected_grains)/degree;
% remove NaN from array
KAM_data=(KAM_data(isfinite(KAM_data)));
% stats
max_KAM = max(KAM_data)
min_KAM = min(KAM_data)
mean_KAM = mean(KAM_data)
std_dev_KAM = std(KAM_data)
nbins = 25;
figure('position',[0 0 600 600])
hist(KAM_data,nbins)
xlabel('Misorientation angles in degrees','FontSize',18)
ylabel('Counts','FontSize',18)
title('Kernel averaged misorientation (KAM) histogram - single grain','FontSize',18)
savefigure('/MatLab_Programs/Histo_KAM_angles_from_mean_within_grain1_Al_210.png')
%**************************************************************************
%% Find number of neighbouring grains
%**************************************************************************
[n_neighbours,pairs] = neighbors(selected_grains);
max_neighbours = max(n_neighbours)
min_neighbours = min(n_neighbours)
mean_neighbours = mean(n_neighbours)
std__neighbours = std(n_neighbours)
nbins = 90;
figure('position',[0 0 600 600])
hist(n_neighbours,nbins)
xlabel('Number of neighbours','FontSize',18)
ylabel('Counts','FontSize',18)
title('Number of neighbours for all grains','FontSize',18)
savefigure('/MatLab_Programs/Histo_number_neighbours_Al_210.png')
%**************************************************************************
%% Find number of neighbouring grains - zoom
%**************************************************************************
[n_neighbours,pairs] = neighbors(selected_grains);
n_neighbours=(n_neighbours(n_neighbours<11));
max_neighbours = max(n_neighbours)
min_neighbours = min(n_neighbours)
mean_neighbours = mean(n_neighbours)
std__neighbours = std(n_neighbours)
nbins = 10;
figure('position',[0 0 600 600])
hist(n_neighbours,nbins)
xlabel('Number of neighbours','FontSize',18)
ylabel('Counts','FontSize',18)
title('Number of neighbours for all grains','FontSize',18)
savefigure('/MatLab_Programs/Histo_number_neighbours_zoom_Al_210.png')



