Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
BM32ESRF committed Dec 8, 2022
1 parent 580e5c7 commit b268efd
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 256 deletions.
36 changes: 4 additions & 32 deletions lauetoolsnn/lauetools/quaternions.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,6 @@ def asEulers(self,
def fromIdentity(cls):
return cls()


@classmethod
def fromRandom(cls,randomSeed = None):
if randomSeed is None:
Expand All @@ -424,7 +423,6 @@ def fromRandom(cls,randomSeed = None):
z = math.sin(2.0*math.pi*r[0])*math.sqrt(r[2])
return cls([w,x,y,z])


@classmethod
def fromRodrigues(cls, rodrigues):
if not isinstance(rodrigues, np.ndarray): rodrigues = np.array(rodrigues)
Expand All @@ -434,7 +432,6 @@ def fromRodrigues(cls, rodrigues):
x,y,z = c*rodrigues
return cls([w,x,y,z])


@classmethod
def fromAngleAxis(cls, angle, axis):
if not isinstance(axis, np.ndarray): axis = np.array(axis,dtype='d')
Expand All @@ -446,12 +443,9 @@ def fromAngleAxis(cls, angle, axis):
z = axis[2] * s
return cls([w,x,y,z])


@classmethod
def fromEulers(cls, eulers, type = 'Bunge'):

eulers *= 0.5 # reduce to half angles

c1 = math.cos(eulers[0])
s1 = math.sin(eulers[0])
c2 = math.cos(eulers[1])
Expand All @@ -471,19 +465,15 @@ def fromEulers(cls, eulers, type = 'Bunge'):
z = c1 * s2 * c3 - s1 * c2 * s3
return cls([w,x,y,z])


# Modified Method to calculate Quaternion from Orientation Matrix,
# Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/

# Modified Method to calculate Quaternion from Orientation Matrix,
# Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
@classmethod
def fromMatrix(cls, m):
if m.shape != (3,3) and np.prod(m.shape) == 9:
m = m.reshape(3,3)

tr = np.trace(m)
if tr > 1e-8:
s = math.sqrt(tr + 1.0)*2.0

return cls(
[ s*0.25,
(m[2,1] - m[1,2])/s,
Expand All @@ -494,7 +484,6 @@ def fromMatrix(cls, m):
elif m[0,0] > m[1,1] and m[0,0] > m[2,2]:
t = m[0,0] - m[1,1] - m[2,2] + 1.0
s = 2.0*math.sqrt(t)

return cls(
[ (m[2,1] - m[1,2])/s,
s*0.25,
Expand All @@ -505,7 +494,6 @@ def fromMatrix(cls, m):
elif m[1,1] > m[2,2]:
t = -m[0,0] + m[1,1] - m[2,2] + 1.0
s = 2.0*math.sqrt(t)

return cls(
[ (m[0,2] - m[2,0])/s,
(m[0,1] + m[1,0])/s,
Expand All @@ -516,15 +504,13 @@ def fromMatrix(cls, m):
else:
t = -m[0,0] - m[1,1] + m[2,2] + 1.0
s = 2.0*math.sqrt(t)

return cls(
[ (m[1,0] - m[0,1])/s,
(m[2,0] + m[0,2])/s,
(m[1,2] + m[2,1])/s,
s*0.25,
])


@classmethod
def new_interpolate(cls, q1, q2, t):
"""
Expand Down Expand Up @@ -826,14 +812,9 @@ def inSST(self,

# code derived from http://pyeuclid.googlecode.com/svn/trunk/euclid.py
# suggested reading: http://web.mit.edu/2.998/www/QuaternionReport1.pdf



# ******************************************************************************************
class Orientation:

__slots__ = ['quaternion','symmetry']

def __init__(self,
quaternion = Quaternion.fromIdentity(),
Rodrigues = None,
Expand Down Expand Up @@ -880,51 +861,42 @@ def __repr__(self):
def asQuaternion(self):
return self.quaternion.asList()

# @property
def asEulers(self,
type = 'bunge',
degrees = False,
standardRange = False):
return self.quaternion.asEulers(type, degrees, standardRange)
eulers = property(asEulers)

# @property
def asRodrigues(self):
return self.quaternion.asRodrigues()
rodrigues = property(asRodrigues)

# @property
def asAngleAxis(self, degrees = False):
return self.quaternion.asAngleAxis(degrees)
angleAxis = property(asAngleAxis)

# @property
def asMatrix(self):
return self.quaternion.asMatrix()
matrix = property(asMatrix)

# @property
def inFZ(self):
return self.symmetry.inFZ(self.quaternion.asRodrigues())
infz = property(inFZ)

def equivalentQuaternions(self,
who = []):
def equivalentQuaternions(self, who = []):
return self.symmetry.equivalentQuaternions(self.quaternion,who)

def equivalentOrientations(self,
who = []):
def equivalentOrientations(self, who = []):
return list(map(lambda q: Orientation(quaternion = q, symmetry = self.symmetry.lattice),
self.equivalentQuaternions(who)))

def reduced(self):
"""Transform orientation to fall into fundamental zone according to symmetry"""
for me in self.symmetry.equivalentQuaternions(self.quaternion):
if self.symmetry.inFZ(me.asRodrigues()): break

return Orientation(quaternion=me,symmetry=self.symmetry.lattice)


def disorientation(self,
other,
SST = True):
Expand Down
8 changes: 4 additions & 4 deletions lauetoolsnn/lauetools/readmccd.py
Original file line number Diff line number Diff line change
Expand Up @@ -867,8 +867,8 @@ def peaksearch_skimage(filename, min_dist, pkid_threshold, bs, fit_peaks_gaussia
# all peaks list building
tabpeak = np.zeros((len(peak_coords),10))
for ii in range(len(peak_coords)):
tabpeak[ii,0] = peak_coords[ii,0]#+1
tabpeak[ii,1] = peak_coords[ii,1]#+1
tabpeak[ii,0] = peak_coords[ii,0]+1
tabpeak[ii,1] = peak_coords[ii,1]+1
tabpeak[ii,2] = peak_coords[ii,2]
tabpeak[ii,3] = 0
tabpeak[ii,4] = 0
Expand Down Expand Up @@ -909,8 +909,8 @@ def peaksearch_skimage(filename, min_dist, pkid_threshold, bs, fit_peaks_gaussia
tabpeak = np.zeros((len(poptimized),10))
for ii in range(len(poptimized)):
px0, py0, _, bs = peak_coords[ii]
tabpeak[ii,0] = poptimized[ii,1]+px0-bs#+1
tabpeak[ii,1] = poptimized[ii,2]+py0-bs#+1
tabpeak[ii,0] = poptimized[ii,1]+px0-bs+1
tabpeak[ii,1] = poptimized[ii,2]+py0-bs+1
tabpeak[ii,2] = poptimized[ii,0]
tabpeak[ii,3] = poptimized[ii,4]
tabpeak[ii,4] = poptimized[ii,5]
Expand Down
14 changes: 10 additions & 4 deletions lauetoolsnn/lauetoolsneuralnetwork.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,7 @@ def load_config_from_file(self, configFile):
dim1_global = detectorfile2[6]
dim2_global = detectorfile2[7]
ccd_label_global = detectorfile2[8]
ccd_label_global = ccd_label_global.strip()
try:
emax_global = float(config.get('DETECTOR', 'emax'))
emin_global = float(config.get('DETECTOR', 'emin'))
Expand Down Expand Up @@ -2881,7 +2882,10 @@ def draw_something(self):

if len(self.pix_x)!=0:
self.canvas.axes.set_title("Laue pattern of pixel x=%d, y=%d (peaks: %d) (file: %s)"%(self.iy,self.ix,len(self.pix_x),self.file), loc='center', fontsize=8)
self.scatter.set_offsets(np.vstack((self.pix_x,self.pix_y)).T)
if self.peaksearch_mode.currentText() in ["lauetools", "skimage", "skimage_relaxed", "skimage_nobounds", "skimage_nofit"]:
self.scatter.set_offsets(np.vstack((self.pix_x-1,self.pix_y-1)).T)
else:
self.scatter.set_offsets(np.vstack((self.pix_x,self.pix_y)).T)
self.canvas.draw()

def refresh_plots(self):
Expand Down Expand Up @@ -3311,7 +3315,7 @@ def __init__(self, th_exp, chi_exp, intensity, tth_sim, chi_sim, sim_energy, sim
self.setDisplayText(texttstr)
texttstr = "# Total experimental spots : "+str(len(th_exp))
self.setDisplayText(texttstr)
texttstr = "# Average residues : "+str(np.average(residues))
texttstr = "# Average residues (angular): "+str(np.average(residues))
self.setDisplayText(texttstr)
texttstr = "# Total linked spots : "+str(len(exp_linkspots))
self.setDisplayText(texttstr)
Expand Down Expand Up @@ -3592,7 +3596,7 @@ def __init__(self, match_rate12, rotation_matrix12, mat_global12, fR_pix12, file
for ijk in range(len(match_rate12)):
if len(tth_sim[ijk]) != 0:
self.setDisplayText("--------------- Matrix "+str(ijk+1)+" \n")
texttstr = "# Average residues : "+str(np.average(residues[ijk]))
texttstr = "# Average residues (angular): "+str(np.average(residues[ijk]))
self.setDisplayText(texttstr)
texttstr = "# Total linked spots : "+str(len(exp_linkspots[ijk]))
self.setDisplayText(texttstr)
Expand Down Expand Up @@ -5227,6 +5231,8 @@ def save_btn(self,):
c_time = now.strftime("%Y-%m-%d_%H-%M-%S")

###convert UB to fundamental zone, before saving the data
## Seems to be not correct, verify with independent scripts
## The error is because UB is not pure rotation matrix (no longer needed)
# try:
# self.rotation_matrix = self.convertUB_reduced(self.rotation_matrix,
# self.mat_global, self.symmetry, self.symmetry1)
Expand Down Expand Up @@ -5924,7 +5930,7 @@ def plot_pcv1(self):
if len(list_of_files) == count_global:
for ii in range(len(list_of_files)):
grid_files[ii] = ii
self.filenm[ii] = list_of_files[ii]
self.filenm[ii] = list_of_files[ii]
else:
print("expected "+str(count_global)+" files based on the XY grid ("+str(self.lim_x)+","+str(self.lim_y)+") defined by user")
print("But found "+str(len(list_of_files))+" files (either all data is not written yet or maybe XY grid definition is not proper)")
Expand Down
69 changes: 54 additions & 15 deletions lauetoolsnn/misc_scripts/orientation_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
@author: PURUSHOT
Script to test misorientation functions
Script to test orientation functions
"""
import numpy as np
Expand All @@ -13,12 +13,15 @@
from tqdm import trange
from itertools import compress
from lauetoolsnn.lauetools.quaternions import Orientation, Quaternion
from lauetoolsnn.utils_lauenn import Lattice, HklPlane
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy import spatial


#### Load some results
folder = os.getcwd()
with open(r"C:\Users\purushot\Desktop\SiC\results_triangle_5UBs\results.pickle", "rb") as input_file:
with open(r"D:\some_projects\GaN\Si_GaN_nanowires\results_Si_2022-12-07_23-57-29\results.pickle", "rb") as input_file:
best_match, \
mat_global, rotation_matrix1, strain_matrix, strain_matrixs,\
col, colx, coly, match_rate, files_treated,\
Expand All @@ -27,28 +30,64 @@
crystal, crystal1 = cPickle.load(input_file)

material_id = [material_, material1_]
#%% convert UB to proper convention
new_rot_mat = [[np.zeros_like(rotation_matrix1[0][0])] for _ in range(len(rotation_matrix1))]


#%% convert UB to proper convention (verify if this does not change the UB components and only their permutations)
transformed_rotation_matrix = [[np.zeros_like(rotation_matrix1[0][0])] for _ in range(len(rotation_matrix1))]
new_rot_mat = [[np.zeros_like(rotation_matrix1[0][0])] for _ in range(len(rotation_matrix1))]
for index in range(len(rotation_matrix1)):
for om_ind in trange(len(rotation_matrix1[index][0])):
## UB matrix in Laue reference frame (or crystal reference frame?)
orientation_matrix = rotation_matrix1[index][0][om_ind]
val = mat_global[index][0][om_ind]
if val == 0 or np.all(orientation_matrix==0):
continue
if val == 1:
symmetry = symmetry0.name
elif val == 2:
symmetry = symmetry1.name
## convert to orientation object to inherit all properties of Orientation class
om = Orientation(matrix=orientation_matrix, symmetry=symmetry).reduced()
new_rot_mat[index][0][om_ind] = om.asMatrix()

if np.all(orientation_matrix!=0):
val = mat_global[index][0][om_ind]
if val == 0 or np.all(orientation_matrix==0):
continue
if val == 1:
symmetry = symmetry0.name
elif val == 2:
symmetry = symmetry1.name

omega = np.deg2rad(-40.0)
# rotation de -omega autour de l'axe x (or Y?) pour repasser dans Rsample
cw = np.cos(omega)
sw = np.sin(omega)
mat_from_lab_to_sample_frame = np.array([[cw, 0.0, sw], [0.0, 1.0, 0.0], [-sw, 0, cw]])
orientation_matrix_temp = np.dot(mat_from_lab_to_sample_frame.T, orientation_matrix)
if np.linalg.det(orientation_matrix_temp) < 0:
orientation_matrix_temp = -orientation_matrix_temp
transformed_rotation_matrix[index][0][om_ind] = orientation_matrix_temp
## convert to orientation object to inherit all properties of Orientation class
om = Orientation(matrix=orientation_matrix_temp, symmetry=symmetry).reduced()
new_rot_mat[index][0][om_ind] = om.asMatrix()

#%% Test
from scipy.spatial.transform import Rotation as R
r = R.from_matrix(transformed_rotation_matrix[0][0][0])
transformed_rotation_matrix[0][0][0]
r.as_quat()

#%%
r.as_matrix()


#%% Some other checks
from lauetools import dict_LaueTools as dictLT
from lauetools import CrystalParameters as CP
from lauetools import findorient as FindO
from lauetools.quaternions import Orientation, Quaternion
lattice_params0 = dictLT.dict_Materials["Si"][1]
B = CP.calc_B_RR(lattice_params0)
pureU = FindO.OrientMatrix_from_2hkl([ 1, -3, 0], [ 51.84038168128769, -11.376240528268882], \
[ 0, -3 , 1], [54.57004855052002, 17.55246093908536],
B)


np.trace(pureU)

quats = Quaternion.fromMatrix(pureU)
quats.asMatrix()
#%% Computing misorientations and then segmenting grains
print("Number of Phases present (includes non indexed phase zero also)", len(np.unique(np.array(mat_global))))

average_UB = []
Expand Down
7 changes: 7 additions & 0 deletions lauetoolsnn/misc_scripts/user_training_dataGeneration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 8 09:02:26 2022
@author: PURUSHOT
"""

Loading

0 comments on commit b268efd

Please sign in to comment.