def MC_make_angles_nrb(R,U,pVec,detectorGeom,planeData,omeMin,omeMax,tweak = False, stdev = rad(.1)): angl,axxx = Rotations.angleAxisOfRotMat(R) Rparams0 = (angl*axxx).flatten() #import uncertainty_analysis tmpDG = detector.DetectorGeomGE(detectorGeom, pVec=pVec) #print 'recip vects...', recips = planeData.makeRecipVectors(R = R, U = U) #print 'made' wavelength = planeData.wavelength nvecs = recips.shape[1] from data_class import inv_dict #allangs = inv_dict() allangs = [] #import sys #print "nvecs",nvecs for j in range(10): print j, #print "done" for i in range(nvecs): #print i #sys.stdout.write(str(i)+ " ") rI = recips[:,i] #print "rI",rI,tweak if tweak: Rparams_tweak = numpy.random.normal([0,0,0],[stdev,stdev,stdev]) #Rparams = Rparams0 + Rparams_tweak Rtweak = Rotations.rotMatOfExpMap(Rparams_tweak) #print Rparams0, Rparams rI = num.dot(Rtweak,rI) angle_sols = Get_LLNL_Angles(rI,wavelength) #print rI, angle_sols for key in angle_sols.keys(): tth,eta,w = angle_sols[key] w = mapOme(w,-num.pi,num.pi) if eta!=num.pi and eta!=-num.pi: eta = mapOme(eta,-num.pi,num.pi) if w<omeMin.getVal('radians') or w>omeMax.getVal('radians'): continue if w is not None: #pred_angle_vector = num.array(detectorGeom.xyoToAng(*(px,py,w))) tmpX, tmpY, tmpO = tmpDG.angToXYO([tth,tth],[eta,eta],[w,w]) tmpX = tmpX[0] tmpY = tmpY[0] tmpO = tmpO[0] tmpTTh, tmpEta, tmpOme = detectorGeom.xyoToAng(tmpX, tmpY, tmpO) tmpAngs = num.vstack([tmpTTh, tmpEta, tmpOme]) #allangs.Add((i,key),(num.array((tmpTTh,tmpEta,tmpOme)),(stdev,stdev,stdev))) allangs.append([tmpTTh,tmpEta,tmpOme]) return num.array(allangs)
def _fitRotation_lsq(Rparams, gIs,angles0, U,wavelength): out = [] Rmat = Rotations.rotMatOfExpMap(Rparams) Fmat = dot(Rmat,U) for i in range(len(gIs)): gI,angles = gIs[i], angles0[i] r_i = _fitR_residual(angles,gI, Fmat, wavelength) if weighting: weight = uncertainty_analysis.propagateUncertainty(_fitR_residual, weighting[i], 1e-8,angles,gI,Fmat,wavelength) maxiter = 100 ct = 0 while weight==0: weight = uncertainty_analysis.propagateUncertainty(_fitR_residual, weighting[i], 1e-8,angles,gI,Fmat,wavelength) ct+=1 if ct>=maxiter: print 'zero weight error, i = ',i weight = 1 break else: weight = 1. out.append(r_i/weight) if weight == 0: print 'wefiht0',i,weighting[i],Fmat out = num.array(out) # print out return out
def MC_fitAll_Angles_wrap(allparams,agrain,wmin,wmax,angles, weighting = True): pVec = allparams[0:3] Rparams = allparams[3:6] Uparams = allparams[6:12] U = gw.vec_to_sym(Uparams) R = Rotations.rotMatOfExpMap(Rparams) #angles = MC_make_angles_from_spots_grain(R,U,agrain,pVec,wmin,wmax,tweak = False) return MC_Angle_Fit(R,U,agrain,pVec,wmin,wmax,angles,weighting)
def MC_make_rIs(Rparams, gIs, sigma): rIs = [] R = Rotations.rotMatOfExpMap(Rparams) for i in range(len(gIs)): gI = gIs[i] rI_mus = num.dot(R,gI) errors = numpy.random.normal(0, sigma, 3) rI = rI_mus + errors rIs.append(rI) return rIs
def fitOrientation_func(Rparams, gIs, rIs): R = Rotations.rotMatOfExpMap(Rparams) residual = [] for i in range(len(gIs)): gI = gIs[i] rI = rIs[i] diff = num.dot(R,gI) - rI residual.append(diff[0]) residual.append(diff[1]) residual.append(diff[2]) residual = num.array(residual) return residual
def misorientationGrain(kocks, angs, frames, kor, gr_mis=False): ''' It takes in the mesh, the grain number of interest, the angles output from FePX and then the number of frames. It outputs the misorientations angles calculated for that specific grain by using the built in misorientation function within the ODFPF library. Input: kocks - the kocks angle of the the grain being examined grNum - an integer of the grain that you want to find the misorientation for each element angs - a numpy array 3xnxnframes of the angles output from FePX frames - list of frames your interested in examining Output: misAngs - a numpy array of nxframes that contains the angle of misorientation for each element with respect to the original orientation of the grain misQuat - a numpy array of 4xnxnframes that contains the misorientation quaternion for each element with respect to the original orientation of the grain ''' angs = np.atleast_3d(angs) if angs.shape[0] == 1: angs = angs.T lenQuat = angs.shape[1] deg = 'degrees' misAngs = np.zeros((lenQuat, len(frames))) misQuat = np.zeros((4, lenQuat, len(frames))) misQuat[0, :, :] = 1 if (gr_mis): origQuat = rot.OrientConvert(kocks, 'rod', 'quat', deg, deg) else: origQuat = rot.OrientConvert(kocks, 'kocks', 'quat', deg, deg) csym = rot.CubSymmetries() j = 0 for i in frames: if kor == 'axis' or kor == 'axisangle': tQuat = rot.QuatOfAngleAxis(np.squeeze(angs[0, :, i]), np.squeeze(angs[1:4, :, i])) else: tQuat = rot.OrientConvert(np.squeeze(angs[:, :, i]), kor, 'quat', deg, deg) misAngs[:, j], misQuat[:, :, j] = rot.Misorientation(origQuat, tQuat, csym) j += 1 return (misAngs, misQuat)
def MC_make_rIs_grain(Rparams, grainInstance, scale = 1, sigma = 0): rIs = [] R = Rotations.rotMatOfExpMap(Rparams) masterReflInfo = grainInstance.grainSpots hitRelfId = num.where(masterReflInfo['iRefl'] >= 0)[0] measHKLs = masterReflInfo['hkl'][hitRelfId, :] #measAngs = masterReflInfo['measAngles'][hitRelfId, :] #measQvec = grain.makeScatteringVectors(measAngs[:, 0], measAngs[:, 1], measAngs[:, 2]) #predQvec = num.dot( R, mUtil.unitVector( num.dot(grainInstance.bMat, measHKLs.T) ) ) pred_rIs = num.dot( R, num.dot(grainInstance.bMat, measHKLs.T) ) pred_rIs = UnMatlab(pred_rIs) err_rIs = [] for i in range(len(pred_rIs)): rI = pred_rIs[i] if sigma == 0: errors = num.zeros(3) else: errors = numpy.random.normal(0, sigma, 3) rI = rI + errors err_rIs.append(rI/scale) #rIS_2 = grainInstance.planeData.makeRecipVectors(R = R) return err_rIs
def main(): file_name, figure, book_color = Rotations.get_program_parameters() # Set up for six rotations about the y-axis. figure = 2 book_color = True Rotations.rotate(file_name, figure, book_color)
#Legacy code but just setting our deformation gradient to the identity array defgrad = np.swapaxes(np.tile(np.atleast_3d(np.identity(3)), (1,1,nel)), 0, 2) #A list holding our deformation stats for the discrete and lofem methods deflist = [] ldeflist = [] #el_angs is a temporary variable that will hold the grain values that go into misoriD el_angs = np.zeros((3,nel,nsteps)) #Our difference quats, lofem quaternion at nodes, lofem quaternion at the centroid of the element, and discrete method quats diff_misQuats = np.zeros((4,nel,nsteps)) lQuats = np.zeros((4, npts, nsteps)) leQuats = np.zeros((4, nel, nsteps)) dQuats = np.zeros((4, nel, nsteps)) #Just converting from our inputted orientation data to quaternions for j in range(nsteps): el_angs[:,:,j] = fe.elem_fe_cen_val(ldata['angs'][:,indlog2,j], lcon2) lQuats[:,:,j] = rot.QuatOfRod(np.squeeze(ldata['angs'][:,indlog2,j])) leQuats[:,:,j] = rot.QuatOfRod(np.squeeze(el_angs[:,:,j])) dQuats[:,:,j] = rot.OrientConvert(np.squeeze(data['angs'][:,indlog,j]), 'kocks', 'quat', 'degrees', 'radians') #Here we're getting the misorientation angle and quaternion for our angles when taken with respect the original orientation #for the lofem method lemisAngs, lemisQuats = mis.misorientationGrain(mesh['kocks'][:,i-1], el_angs, frames, kor) for j in range(nsteps): #Getting misorientation between the lofem and disc elements temp2, tempQ = mis.misorientationGrain(data['angs'][:,indlog, j], el_angs[:,:,j], [0], kor) diff_misQuats[:,:,j] = np.squeeze(tempQ) misoriD[indlog, j] = np.squeeze(temp2) crd = np.squeeze(data['coord'][:,ucon, j]) #Getting strain data epsVec = np.squeeze(ldata['strain'][:, indlog, j])
def MC_fitC_angle_weights(Rparams, Uparams, gIs,angles0, wavelength, weighting = False, report = True, evaluate = False): """ alternate fitting approach for U, uses no Rotation information. Cparams: [C11,C22,C33,C12,C23,C13] """ from Vector_funcs import Mag from numpy import dot,sqrt import uncertainty_analysis 'internal objective function' def _fitC_residual(angles, r0, invCmat, wavelength): rI = gw.makeARecipVector(angles, wavelength) #print rI df = 1./Mag(rI) d0 = 1./Mag(r0) gii_0 = dot(r0,r0) gii = dot(dot(invCmat,r0),r0) r_i = df/d0 - sqrt(gii_0)/(sqrt(gii)) return r_i def _fitC(Cparams,gIs,angles,wavelength): Cmat = gw.vec_to_sym(Cparams) invCmat = inv(Cmat) out = [] for i in range(len(gIs)): gI = gIs[i] angCOM = angles[i] #, spot in gI_spots: r_i = _fitC_residual(angCOM,gI, invCmat, wavelength) if weighting: weight = uncertainty_analysis.propagateUncertainty(_fitC_residual, weighting[i], 1e-8,angCOM,gI,invCmat,wavelength) else: weight = 1 out.append(r_i/weight) return num.array(out) if Rparams == 'default': angl,axxx = Rotations.angleAxisOfRotMat(num.eye(3)) Rparams = (angl*axxx).flatten() else: Rparams = Rparams if Uparams=='default': Uparams = sym_to_vec(num.eye(3)) else: Uparams = Uparams U = gw.vec_to_sym(Uparams) R = Rotations.rotMatOfExpMap(Rparams) F = num.dot(R,U) C_ = num.dot(F.T,F) Cparams = gw.sym_to_vec(C_) if evaluate: return _fitC(Cparams,gIs,angles0,wavelength) optResults = optimize.leastsq(_fitC, x0 = Cparams, args = (gIs,angles0,wavelength), full_output = 1) Cparams = optResults[0] C = gw.vec_to_sym(Cparams) from scipy.linalg import eig 'spectral decomposition to get U' eval,evec = eig(C) l1_sqr,l2_sqr,l3_sqr = num.asarray(eval,dtype = 'float') u1,u2,u3 = evec[:,0],evec[:,1],evec[:,2] U = sqrt(l1_sqr)*num.outer(u1,u1) + sqrt(l2_sqr)*num.outer(u2,u2) + sqrt(l3_sqr)*num.outer(u3,u3) if report: print "refined stretch matrix: \n%g, %g, %g\n%g, %g, %g\n%g, %g, %g\n" \ % (U[0, 0], U[0, 1], U[0, 2], \ U[1, 0], U[1, 1], U[1, 2], \ U[2, 0], U[2, 1], U[2, 2], ) return optResults
def MC_fitR_Angle_wrap(Rparams,U,agrain,pVec,wmin,wmax,angles,weighting = True): R = Rotations.rotMatOfExpMap(Rparams) #angles = MC_make_angles_from_spots_grain(R,U,agrain,pVec,wmin,wmax,tweak = False) return MC_Angle_Fit(R,U,agrain,pVec,wmin,wmax,angles,weighting)
def MC_fitRotation_angles(Rparams, Uparams, gIs,angles0, wavelength, weighting = False, report = True,evaluate = False): assert len(gIs)==len(angles0), 'different lengths' def _fitR_residual(angles, r0, Fmat, wavelength): Cmat = dot(Fmat.T,Fmat) rI = gw.makeARecipVector(angles,wavelength) n = Unit(rI) N = Unit(r0) #print Fmat,Cmat alpha_ = sqrt(Inner_Prod(Star(Cmat),N,N)) #print alpha_ r_i = Inner_Prod(Star(Fmat),n,N) - alpha_ #print 'r_i' return r_i def _fitRotation_lsq(Rparams, gIs,angles0, U,wavelength): out = [] Rmat = Rotations.rotMatOfExpMap(Rparams) Fmat = dot(Rmat,U) for i in range(len(gIs)): gI,angles = gIs[i], angles0[i] r_i = _fitR_residual(angles,gI, Fmat, wavelength) if weighting: weight = uncertainty_analysis.propagateUncertainty(_fitR_residual, weighting[i], 1e-8,angles,gI,Fmat,wavelength) maxiter = 100 ct = 0 while weight==0: weight = uncertainty_analysis.propagateUncertainty(_fitR_residual, weighting[i], 1e-8,angles,gI,Fmat,wavelength) ct+=1 if ct>=maxiter: print 'zero weight error, i = ',i weight = 1 break else: weight = 1. out.append(r_i/weight) if weight == 0: print 'wefiht0',i,weighting[i],Fmat out = num.array(out) # print out return out if Rparams == 'default': angl,axxx = Rotations.angleAxisOfRotMat(num.eye(3)) Rparams = (angl*axxx).flatten() else: Rparams = Rparams if Uparams=='default': Uparams = sym_to_vec(num.eye(3)) else: Uparams = Uparams U = gw.vec_to_sym(Uparams) if evaluate: return _fitRotation_lsq(Rparams,gIs,angles0,U,wavelength) optResults = optimize.leastsq(_fitRotation_lsq, x0 = Rparams, args = (gIs,angles0, U, wavelength), full_output = 1) r1 = optResults[0] U1 = Rotations.rotMatOfExpMap(r1) if report: print "refined orientation matrix: \n%g, %g, %g\n%g, %g, %g\n%g, %g, %g\n" \ % (U1[0, 0], U1[0, 1], U1[0, 2], \ U1[1, 0], U1[1, 1], U1[1, 2], \ U1[2, 0], U1[2, 1], U1[2, 2], ) return optResults
crd = np.zeros((ncrd, dim), dtype='float64', order='F') el_vec = np.zeros((dim, nnpe, nel), dtype='float64', order='F') vec_grad = np.zeros((dim, dim, nel), dtype='float64', order='F') nye_ten = np.zeros((dim, dim, nel), dtype='float64', order='F') density = np.zeros((ngdot, nel), dtype='float64', order='F') loc_dndx = np.zeros((dim, nnpe, nel), dtype='float64', order='F') det_qpt = np.zeros((nel), dtype='float64', order='F') ang_axis = np.zeros((dim, ncrd, nsteps), dtype='float64', order='F') #The Nye Tensor is based on our angle axis representation so we need #to rotate from a rod vec to angle axis for j in range(nsteps): ang_axis[:,:,j] = rot.AngleAxisOfRod(ldata['angs'][:,indlog2,j]) for j in range(nsteps): crd[:,:] = np.squeeze(data['coord'][:,ucon, j]).T #Creating an array that contains our coords for each element #Creates an array that has an array of our orientations for each element for k in range(nel): elem_crd[:, :, k] = crd[lcon[:, k], :] el_vec[:, :, k] = ang_axis[:, lcon2[:, k], j] #Here we're obtaining our local dN/dX versions of our shape function along with our # jacobian at the middle quadrature point loc_dndx[:,:,:], det_qpt[:] = fe.local_gradient_shape_func(iso_dndx, elem_crd, 4) #Here we're getting the gradient of our vector data and from that the Nye tensor vec_grad = fe.get_vec_grad(el_vec, loc_dndx) nye_ten = fe.get_nye_tensor(vec_grad)
dim = 3 nnpe = 9 kdim1 = 29 deflist = [] ldeflist = [] el_angs = np.zeros((3,nel,nsteps)) diff_misQuats = np.zeros((4,nel,nsteps)) lQuats = np.zeros((4, npts, nsteps)) leQuats = np.zeros((4, nel, nsteps)) dQuats = np.zeros((4, nel, nsteps)) for j in range(nsteps): el_angs[:,:,j] = fe.elem_fe_cen_val(gdata['angs'][:,:,j], lcon) lQuats[:,:,j] = rot.OrientConvert(np.squeeze(gdata['angs'][:,:,j]), 'rod', 'quat', 'radians', 'radians') leQuats[:,:,j] = rot.OrientConvert(np.squeeze(el_angs[:,:,j]), 'rod', 'quat', 'radians', 'radians') dQuats[:,:,j] = rot.OrientConvert(np.squeeze(data['angs'][:,indlog,j]), 'kocks', 'quat', 'degrees', 'radians') lemisAngs, lemisQuats = mis.misorientationGrain(mesh['kocks'][:,i-1], el_angs, frames, kor) for j in range(nsteps): #Getting misorientation between the lofem and disc elements temp2, tempQ = mis.misorientationGrain(data['angs'][:,indlog, j], el_angs[:,:,j], [0], kor) diff_misQuats[:,:,j] = np.squeeze(tempQ) misoriD[indlog, j] = np.squeeze(temp2) crd = np.squeeze(data['coord'][:,ucon, j]) epsVec = np.squeeze(ldata['strain'][:, indlog, j]).T strain = fepxDM.fixStrain(epsVec)
def main(): file_name, figure, book_color = Rotations.get_program_parameters() # First a rotation about the x-axis, then six rotations about the y-axis. figure = 4 book_color = True Rotations.rotate(file_name, figure, book_color)