import AITAToolbox.loadData_aita as lda
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.patches as patches
import numpy as np
import math
import scipy
%matplotlib widget

"""
Explanation: This documention is made from a jupyter notebook available in 'Exemple/Documentation.ipynb'
Load data from G50 analyser
Loading data from G50 analyser after you convert binary file into ASCII file with 5 columuns.
End of explanation
"""


data=lda.aita5col('orientation_test.dat')

"""
Explanation: Without 'micro_test.bmp'
End of explanation
"""


out=data.interactive_crop(new=True)

"""
Explanation: With 'micro_test.bmp'
The ‘micro_test.bmp’ file should be a black and white image with the grains boundaries being white. Therefore you should use :
python
data=lda.aita5col('orientation_test.dat','micro.test.bmp')
Basic treatment
Croping
It can be usefull to select a sub area. Within a juptyter notebook use interactive_crop(). In ipython use just crop function.
End of explanation
"""


ss=np.shape(data.phi.field)
res=data.phi.res

fig,ax=plt.subplots()
data.phi1.plot()
rect=patches.Rectangle((out.pos[0]*res, (ss[0]-out.pos[3])*res), (out.pos[1]-out.pos[0])*res, (out.pos[3]-out.pos[2])*res, linewidth=1, edgecolor='b', facecolor='none')
plt.title('Full data with crop area')
ax.add_patch(rect)
plt.subplots()
out.crop_data.phi1.plot()
plt.title('Crop data')

"""
Explanation: Once you did 'Export crop' the position of the rectangle can be find in :
python
out.pos=np.array([xmin,xmax,ymin,ymax])
End of explanation
"""


plt.figure(figsize=(10,10))
seg=out.crop_data.interactive_segmentation()

"""
Explanation: Segmentation of microstrucuture
If you want to do it. It should not be use if you already load the microstrucure.
End of explanation
"""


print('Use scharr:',seg.use_scharr)
print('Value scharr:',seg.val_scharr)
print('Use canny:',seg.use_canny)
print('Value canny:',seg.val_canny)
print('Images canny:',seg.img_canny)
print('Use quality:',seg.use_quality)
print('Value quality:',seg.val_quality)
print('Include border:',seg.include_border)

"""
Explanation: Once you did 'Export AITA' you can save the microstrucuture using :
python
data.micro.save_bmp('micro')
You can also see the parameter used for the segmentation in res.
End of explanation
"""


data.filter(75)

"""
Explanation: Filter the data
This function filter the bad indexed value. Using G50 analyser a quelity factor is given between 0 and 100. Usualy using data with a quality factor higher than 75 is a good option.
End of explanation
"""


plt.figure(figsize=(8,8))
data.plot()
data.micro.plotBoundary(dilatation=2)
plt.title('Colormap')

"""
Explanation: Colormap
Plotting the colormap with the grains boundaries
Full ColorWheel
Advantages
1. The full colorwheel has unique relation between color and orientation.
Inconveniants
1. The color are discountinous for $v=\left[x,y,z=0 \pm \varepsilon\right]$
End of explanation
"""


plt.figure(figsize=(2,2))
plt.imshow(lda.aita.lut())
plt.axis('off')
plt.title('LUT')

"""
Explanation: The associated full colorwheel :
End of explanation
"""


plt.figure(figsize=(8,8))
data.plot(semi=True)
data.micro.plotBoundary(dilatation=2)
plt.title('Colormap')

"""
Explanation: Semi ColorWheel
Advantage
1. No color discontinuity for $v=\left[x,y,z=0 \pm \varepsilon\right]$
Inconvinent

The semi colorwheel has non unique relation between color and orientation.
End of explanation
"""


plt.figure(figsize=(2,2))
plt.imshow(lda.aita.lut(semi=True))
plt.axis('off')
plt.title('LUT')

"""
Explanation: The associated full colorwheel :
End of explanation
"""


plt.figure(figsize=(7,7),dpi=160)
plt.subplot(2,2,1)
data.plotpdf(contourf=True,angle=0,cm2=cm.gray)
plt.subplot(2,2,2)
data.plotpdf(contourf=True)
plt.subplot(2,2,3)
data.plotpdf(angle=0)
plt.subplot(2,2,4)
data.plotpdf()

"""
Explanation: Pole figure
There is various option to plot the pole figure here we focus on some of them but to see all of them refer to the documentation of plotpdf function.
The color coding of the pole figure is obtain using a Kernel Density Estimation (KDE). This KDE has to be manipulating carrefully. If you want to have a basic idea of what is a KDE you can look at https://mathisonian.github.io/kde/.
Representation
Pole figure all sample
Here some of the option are shown as contour plot, and with or without circle for specific angle.
Be aware that to reduce the computation time we only used by default 10000 orientations selected randomly. You can modify this using 'nbp' value. If you set nbp to 0 it use all the data.
End of explanation
"""


plt.figure(figsize=(7,7),dpi=160)
plt.subplot(2,2,1)
data.plotpdf(contourf=True,angle=0,bw=0.05)
plt.title('bw=0.05')
plt.subplot(2,2,2)
data.plotpdf(contourf=True,angle=0,bw=0.1)
plt.title('bw=0.1')
plt.subplot(2,2,3)
data.plotpdf(contourf=True,angle=0,bw=0.3)
plt.title('bw=0.3')
plt.subplot(2,2,4)
data.plotpdf(contourf=True,angle=0,bw=2.0)
plt.title('bw=2')

"""
Explanation: Kernel Density Estimation
If you want to have an idea of a basic KDE in one dimention refer to https://mathisonian.github.io/kde/
Here there is some specificities du to the fact that we are computing KDE on a sphere. To do so we are using sklearn.neighbors.KernelDensity (https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KernelDensity.html). 
The 'metric' is set to 'haversine' for spherical computation (for exemple see https://scikit-learn.org/stable/auto_examples/neighbors/plot_species_kde.html#sphx-glr-auto-examples-neighbors-plot-species-kde-py)
We are using a gaussian kernel.
Warning : The 'bandwidth' parameter is crutial parameter to set. It can have a strong influence on your pole figure and you interpretation. You should set it up carefully and be critic on your pole figure. Here we show different pole figure for different bandwidth value using the same data as input.
End of explanation
"""


res=data.interactive_misorientation_profile()

plt.figure()
plt.plot(res.x,res.mis2o,'b-',label='mis2o')
plt.plot(res.x,res.mis2p,'k-',label='mis2p')
plt.grid()
plt.legend()
plt.xlabel('Distance')
plt.ylabel('Angle')

"""
Explanation: Misorientation profile
End of explanation
"""


grelon=data.interactive_grelon()

#You can plot the angle map in degree using.
plt.figure()
grelon.map.plot()
#You can find the center use for the computation
plt.plot(grelon.center[0],grelon.center[1],'ks')

"""
Explanation: Grelon function
The grelon function compute the angle between the c-axis at each pixel and the unit radial vector from the center. The center is given by the user.
Using the interactive_grelon function you can click as many time as you want. When you push export, it will compute the angle using the last click (input)
End of explanation
"""


angle=out.crop_data.misorientation(filter_angle=math.pi/180)
random_angle=out.crop_data.misorientation(filter_angle=math.pi/180,random=True)

kernel_a = scipy.stats.gaussian_kde(angle)
xeval_a=np.linspace(0,math.pi/2,180)
yeval_a=kernel_a(xeval_a)

kernel_ra = scipy.stats.gaussian_kde(random_angle)
xeval_ra=np.linspace(0,math.pi/2,180)
yeval_ra=kernel_ra(xeval_ra)

plt.figure()
plt.plot(xeval_a,yeval_a)
plt.plot(xeval_ra,yeval_ra)

"""
Explanation: Misorientation function
End of explanation
"""


