def do_fit_trans(self): f = self.fit_trans p0 = self.p0.copy() # p0[:-3]=0.0 #print p0,"call d0" #d0 = f(p0) if 0: for i in range(len(p0)): pt = p0.copy() pt[i] = p0[i]+0.001 from matplotlib.pylab import clf, ion, title, plot, show print pt - p0, pt ion() clf() title("%d"%(i)) plot(d0, f(pt) - d0, ",") show() if raw_input()[0] != " ": break res = scipy.optimize.leastsq( f, p0, full_output=1) pfit, pcov, info, errmsg, ier = res if ier not in [1,2,3,4]: print s_sq, ier, errmsg else: residu = f(pfit) s_sq = (residu**2).sum()/(len(residu)-len(p0)) ubi = pfit[:9].reshape(3,3) print ("%.6f "*6)%(indexing.ubitocellpars(ubi)) print pfit[9:12] self.g = grain( ubi, pfit[9:12].copy())
def doindex(gve, x, y, z, w): global NUL global tmp global NPKS global UC global TOLSEQ ss = sys.stdout # turns of printing sys.stdout = NUL myindexer = indexing.indexer(wavelength=w, unitcell=UC, gv=gve.T) myindexer.ds = np.sqrt((gve * gve).sum(axis=0)) myindexer.ga = np.zeros(len(myindexer.ds), int) - 1 # Grain assignments # myindexer.readgvfile( gve ) for ring1 in RING1: for ring2 in RING2: myindexer.parameterobj.set_parameters({ 'ds_tol': DSTOL, 'minpks': NPKS, 'max_grains': 1000, 'hkl_tol': TOLSEQ[0], 'ring_1': ring1, 'ring_2': ring2 }) myindexer.loadpars() myindexer.assigntorings() myindexer.find() myindexer.scorethem() grains = [grain.grain(ubi, [x, y, z]) for ubi in myindexer.ubis] grain.write_grain_file("%s.ubi" % (tmp), grains) sys.stdout = ss return len(grains)
def doindex(gve, x, y, z): global NUL global tmp global NPKS ss = sys.stdout # turns of printing #sys.stdout = NUL myindexer = indexing.indexer() myindexer.readgvfile(gve) for ring1 in [1, 0, 2]: for ring2 in [1, 0]: myindexer.parameterobj.set_parameters({ 'ds_tol': 0.004, 'minpks': NPKS, 'max_grains': 1000, 'hkl_tol': 0.02, 'ring_1': ring1, 'ring_2': ring2 }) myindexer.loadpars() myindexer.assigntorings() myindexer.find() myindexer.scorethem() grains = [grain.grain(ubi, [x, y, z]) for ubi in myindexer.ubis] grain.write_grain_file("%s.ubi" % (tmp), grains) sys.stdout = ss return len(grains)
def run_asr(self, topology, ystep, number_y_scans, ymin, g, flt): origin = np.array([topology.shape[0] // 2, topology.shape[0] // 2]) mesh = mesher.create_pixel_mesh(topology, ystep, origin) distance = self.params.get('distance') pixelsize = (self.params.get('y_size') + self.params.get('z_size')) / 2.0 wavelength = self.params.get('wavelength') cell_original = [ self.params.get('cell__a'), self.params.get('cell__b'), self.params.get('cell__c'), self.params.get('cell_alpha'), self.params.get('cell_beta'), self.params.get('cell_gamma') ] strains, directions, omegas, dtys, weights, tths, etas, intensity, sc, G_omegas, hkl = mc.extract_strain_and_directions( cell_original, wavelength, distance, pixelsize, g, flt, ymin, ystep, self.omegastep, number_y_scans) # #With orient # UBs = asr.solve_with_orient( g, hkl, G_omegas, omegas, weights, mesh, dtys, ystep, cell_original ) # voxels = [] # coordinates = mesher.get_elm_centres( mesh ) # #print("UBs.shape",UBs.shape) # for i in range(UBs.shape[0]): # #print(UBs[i,:,:]) # UBI = np.linalg.inv(UBs[i,:,:]) # voxels.append( grain.grain( UBI ) ) # return voxels, coordinates # only strain # tikhonov_solve #eps_xx, eps_yy, eps_zz, eps_yz, eps_xz, eps_xy = asr.tikhonov_solve( mesh, directions, strains , omegas, dtys, weights, ystep, self.gradient_constraint ) #trust region eps_xx, eps_yy, eps_zz, eps_yz, eps_xz, eps_xy = asr.trust_constr_solve( mesh, etas, hkl, tths, intensity, directions, strains, omegas, dtys, weights, ystep, self.gradient_constraint, self.maxiter) voxels = [] coordinates = mesher.get_elm_centres(mesh) for i, elm in enumerate(mesh): # [e11, e12, e13, e22, e23, e33] epsilon_sample = np.array([[eps_xx[i], eps_xy[i], eps_xz[i]], [eps_xy[i], eps_yy[i], eps_yz[i]], [eps_xz[i], eps_yz[i], eps_zz[i]]]) eps_cry = np.dot(np.dot(np.transpose(g.u), epsilon_sample), g.u) eps_cry_flat = [ eps_cry[0, 0], eps_cry[0, 1], eps_cry[0, 2], eps_cry[1, 1], eps_cry[1, 2], eps_cry[2, 2] ] B = tools.epsilon_to_b(eps_cry_flat, cell_original) UBI = np.linalg.inv(np.dot(g.u, B)) * (2 * np.pi) voxels.append(grain.grain(UBI)) return voxels, coordinates
def generate_grains(self): t = numpy.array( [self.parameterobj.parameters[s] for s in ['t_x', 't_y', 't_z']]) for grainname in self.grainnames: for scanname in self.scannames: try: gr = self.grains[(grainname, scanname)] except KeyError: if self.translationsread[grainname] is None: self.grains[(grainname, scanname)] = grain.grain( self.ubisread[grainname], translation=t) self.grains[(grainname,scanname)].name = \ (str(grainname)+":"+scanname).replace(" ","_") else: self.grains[(grainname, scanname)] = grain.grain( self.ubisread[grainname], translation=self.translationsread[grainname]) self.grains[(grainname,scanname)].name = \ (str(grainname)+":"+scanname).replace(" ","_") for scanname in self.scannames: self.reset_labels(scanname)
def map_solution_to_voxels(solution, grain_mask, no_voxels, voxel_data, var_choice='strain'): ''' Take the solution array and create crystal grain objects mapping the right voxel to the proper UB. the output map gives the voxel of the index which is the key The index refers to the index of the grain_mask I.e. the thresholded reconstruction matrix from the FBP ''' #Convert to matrix format solution_as_matrices = [] #print(solution) #print(len(solution)) for i in range(len(solution) // 9): low = i * 9 mid = low + 6 high = low + 9 #print(solution[low:mid]) if var_choice == 'strain': UB = voxel_data.strain_and_euler_to_ub(solution[low:mid], solution[mid:high]) elif var_choice == 'cell': UB = voxel_data.cell_and_euler_to_ub(solution[low:mid], solution[mid:high]) solution_as_matrices.append(np.asarray(UB)) solution_as_matrices = np.asarray(solution_as_matrices) #solution_as_matrices = solution.reshape((no_voxels,3,3)) #Convert to ubi for i, ub in enumerate(solution_as_matrices): ubi = np.linalg.inv(ub) * ( 2 * np.pi) # U and B as defined in xfab.tools (not ID11 indexing) solution_as_matrices[i] = ubi voxels_as_grains = {} n = 0 for i in range(grain_mask.shape[0]): for j in range(grain_mask.shape[1]): if grain_mask[i, j] != 0: voxel = grain.grain(solution_as_matrices[n]) voxels_as_grains[i, j] = voxel n += 1 return voxels_as_grains
def doindex(gve, x, y, z, w, gridpars): """ Try to index some g-vectors """ NPKS = gridpars['NPKS'] UC = gridpars['UC'] TOLSEQ = gridpars['TOLSEQ'] COSTOL = gridpars['COSTOL'] DSTOL = gridpars['DSTOL'] if "2RFIT" in gridpars: DOFIT = gridpars['2RFIT'] else: DOFIT = False ss = sys.stdout # turns off printing if gridpars['NUL']: NUL = open(nulfile, "w") sys.stdout = NUL myindexer = indexing.indexer(wavelength=w, unitcell=UC, gv=gve.T) # added in indexer.__init__ #myindexer.ds = np.sqrt( (gve * gve).sum(axis=0) ) #myindexer.ga = np.zeros(len(myindexer.ds),int)-1 # Grain assignments for ring1 in gridpars['RING1']: for ring2 in gridpars['RING2']: myindexer.parameterobj.set_parameters({ 'cosine_tol': COSTOL, 'ds_tol': DSTOL, 'minpks': NPKS, 'max_grains': 1000, 'hkl_tol': TOLSEQ[0], 'ring_1': ring1, 'ring_2': ring2 }) myindexer.loadpars() myindexer.assigntorings() try: myindexer.find() myindexer.scorethem(fitb4=DOFIT) except: pass # filter out crap vol = 1 / np.linalg.det(UC.B) grains = [ grain.grain(ubi, [x, y, z]) for ubi in myindexer.ubis if np.linalg.det(ubi) > vol * 0.5 ] if gridpars['NUL']: sys.stdout = ss return grains
def makemap(self): """ Generate a map fit versus position - no args? """ for m in self.ubisread: g = grain(m) self.scandata=self.allscandata.copy() self.compute_gv(g) h=np.dot(g.ubi,np.transpose(self.gv)) hint=np.floor(h+0.5).astype(np.int) # rounds down diff=h-hint drlv=np.sqrt(np.sum(diff*diff,0)) indices = np.compress(drlv < 0.05, list(range(self.scandata.shape[0]))) print(indices.shape,"hello") self.scandata = self.allscandata[indices] npts = 10 for i in range(npts): for j in range(npts): x=(i-npts*0.5)*1000/npts y=(j-npts*0.5)*1000/npts g.translation[0]=x g.translation[1]=y self.compute_gv(g) for tol in [ 0.1]: mat = g.ubi.copy() npks = closest.score_and_refine(mat, self.gv, tol) # 2nd time with refined npks = closest.score_and_refine(mat, self.gv, tol) h=np.dot(mat,np.transpose(self.gv)) hint=np.floor(h+0.5).astype(np.int) # rounds down diff=h-hint drlv=np.sqrt(np.sum(diff*diff,0)) tthscore = np.sum(np.sum(hint*diff) * np.sum(hint*diff) / np.sum(h*h)) print(x,y, tol, "%5d"%(npks),sum(drlv)/drlv.shape[0],\ tthscore/drlv.shape[0],indexing.ubitocellpars(mat), end=' ') print() sys.stdout.flush() print() print() print()
def fit_trans(self, fp): ubi = fp[:9].reshape(3,3) t = fp[9:12] gr = grain( ubi, translation = t ) self.omegacalc_ub(fp) #print "self.romega[0]", self.romega[0] wripaca.rotate_vectors_axis_angle( self.cyf.axis, -self.romega, self.gcalc, self.kcalc) #print self.kcalc[0] #print self.kcalc.shape #print self.kcalc[0] # np.dot( self.cyf.posti.reshape(3,3), self.kcalc.T ) #print self.kcalc[0] w = self.cyf.pars.get('wavelength') np.add(self.kcalc[:,0],1./w,self.kcalc[:,0]) mk = np.sqrt((self.kcalc*self.kcalc).sum(axis=1)) np.divide(self.kcalc.T, mk, self.kcalc.T) lv=geometry.labvec( self.sc, self.fc, self.romegacalc*180/np.pi, gr, self.cyf.pars) modlv = np.sqrt((lv*lv).sum(axis=0)) kobs = lv/modlv #print "kobs",kobs.T[0] if 0: gr.translation[2]=0 lvt = geometry.labvec( self.sc, self.fc, self.romegacalc*180/np.pi, gr, self.cyf.pars) modlvt = np.sqrt((lvt*lvt).sum(axis=0)) kobst = lvt/modlv print kobs[:,:3] - kobst[:,:3] sys.exit() #print "obs",kobs.shape,"calc",kcalc.shape,self.diffs[:,:3].shape self.diffs[:,:3] = kobs.T - self.kcalc self.diffs[:,3] = self.romegaerr #print "diffs",self.diffs[0] return self.diffs.ravel().copy()
def fit_one_point(g, flt, pars, ix, iy, ystep): """ Take each time the nearest point in dty (not the mask!) """ om = np.radians(flt.omega[g.mask]) co = np.cos(om) so = np.sin(om) idtycalc = np.round(-ix * so + iy * co) idty = np.round(flt.dty[g.mask] / ystep) # m = abs(dty - dtycalc) < ystep*0.75 m = idtycalc == idty if 0: pl.figure() pl.plot(om, dty, ".") pl.plot(om, dtycalc, ".") pl.show() grfit = grain.grain(g.ubi) grfit.hkl = g.hkl[:, m] grfit.etasigns = g.etasigns[m] inds = np.arange(flt.nrows, dtype=int) grfit.mask = np.zeros(flt.nrows, np.bool) grfit.mask[inds[g.mask][m]] = True fit_one_grain(grfit, flt, pars) return grfit
def fit_one_point(self, gr, flt, pars, ix, iy, ystep): """ Take each time the nearest point in dty (not the mask!) """ om = np.radians(flt.omega[gr.mask]) co = np.cos(om) so = np.sin(om) #idtycalc = np.round(-ix * so + iy * co) # this seeems wrong?! why mirror across y!? idtycalc = np.round(ix * so + iy * co) idty = np.round(flt.dty[gr.mask] / ystep) # m = abs(dty - dtycalc) < ystep*0.75 m = idtycalc == idty voxel = grain.grain(gr.ubi) voxel.hkl = gr.hkl[:, m] voxel.etasigns = gr.etasigns[m] inds = np.arange(flt.nrows, dtype=int) voxel.mask = np.zeros(flt.nrows, np.bool) voxel.mask[inds[gr.mask][m]] = True self.grain_fitter.fit_one_grain(voxel, flt, pars) return voxel
matching = diffs < tol ubi = ubis[matching].mean(axis=0) remaining = ubis[~matching] return ubi, remaining, tol ubiall = ubis.copy() tol = None uniqs = [] while len(ubis > 0): uniq, ubis, tol = removeone(ubis, ubis[0], tol) print(uniq, len(ubis)) uniqs.append(uniq) # now check if any uniqs have a collision due to symmetry: uniqs = np.array(uniqs) for i in range(len(uniqs)): for operator in grp.group[1:]: # skip the identity symubi = np.dot(operator, uniqs[i].reshape(3, 3)).ravel() scors = abs(uniqs - symubi).sum(axis=1) found = scors < tol if found.sum() > 0: print("Symmetry collision!") print(i, operator.ravel(), scors[found], np.arange(len(uniqs))[found]) grain.write_grain_file( uniqfile, [grain.grain(ubi.reshape(3, 3), (0, 0, 0)) for ubi in uniqs])
self.compute_gv(g) for tol in [ 0.1]: mat = g.ubi.copy() npks = closest.score_and_refine(mat, self.gv, tol) # 2nd time with refined npks = closest.score_and_refine(mat, self.gv, tol) h=np.dot(mat,np.transpose(self.gv)) hint=np.floor(h+0.5).astype(np.int) # rounds down diff=h-hint drlv=np.sqrt(np.sum(diff*diff,0)) tthscore = np.sum(np.sum(hint*diff) * np.sum(hint*diff) / np.sum(h*h)) print(x,y, tol, "%5d"%(npks),sum(drlv)/drlv.shape[0],\ tthscore/drlv.shape[0],indexing.ubitocellpars(mat), end=' ') print() sys.stdout.flush() print() print() print() if __name__=="__main__": import sys o=fitgrainxy() o.loadparameters(sys.argv[1]) o.readubis(sys.argv[2]) o.loadfiltered(sys.argv[3]) o.compute_gv(grain(o.ubisread[0])) o.makemap()