def generate_U(no_voxels, sgi): ''' generate random U (orientations) for no_voxels voxels All U must be in same fundamental zone, thus trace of U must be maximal using the allowed permutations INPUT: no_voxels OUTPUT: [[U11 U12 U13],[U21 U22 U23],[U31 U32 U33]] for each voxel ''' print('voxel orientations will be randomly generated\n') U = n.zeros((no_voxels, 3, 3)) Urot = n.zeros((3, 3)) for i in range(no_voxels): #http://www.cognitive-antics.net/mw/index.php?title=Uniform_random_orientation tilt_z = n.random.rand() * 2 * n.pi tilt_y = n.arcsin(n.random.rand()) tilt_x = n.pi * (2 * n.random.rand() * n.pi - 1) U[i] = tools.detect_tilt(tilt_x, tilt_y, tilt_z) t = 0 Ut = U[i].copy() symmetries = [ 'triclinic', 'monoclinic', 'orthorhombic', 'tetragonal', 'trigonal', 'hexagonal', 'cubic' ] crystal_system = symmetries.index(sgi.crystal_system) + 1 rot = symmetry.rotations(crystal_system) for j in range(len(rot)): Urot = n.dot(U[i], rot[j]) trace = Urot.trace() if trace > t: t = trace Ut = Urot U[i] = Ut return U
def test_compare_calc(self): tth = 21.836334 * n.pi / 180. omega = -89.247851 * n.pi / 180. eta = 45.480703 * n.pi / 180. (dety_orig, detz_orig) = (109.418256, 925.772491) gv = n.dot(tools.form_omega_mat(omega), n.array([3.260078, -0.928075, 3.217533])) wavelength = 0.5092836 # in angstrom distance = 135.00 # sample-detector distance (mm) dety_center = 521.5 # beamcenter, y in pixel coordinatees detz_center = 531.5 # beamcenter, z in pixel coordinatees y_size = 0.0936 # Pixel size y (mm) z_size = 0.0962 # Pixel size z (mm) dety_size = 1024.0 # detector y size (pixels) detz_size = 1024.0 # detector z size (pixels) tilt_x = 0.0 # detector tilt counterclockwise around lab x axis in rad tilt_y = 0.0 # detector tilt counterclockwise around lab y axis in rad tilt_z = 0.0 # detector tilt counterclockwise around lab z axis in rad tx = 0 ty = 0 tz = 0 R_tilt = tools.detect_tilt(tilt_x, tilt_y, tilt_z) costth = n.cos(tth) (dety1, detz1) = detector.det_coor(gv, costth, wavelength, distance, y_size, z_size, dety_center, detz_center, R_tilt, tx, ty, tz) #print dety1,detz1 (dety2, detz2) = detector.det_coor2(tth, eta, distance, y_size, z_size, dety_center, detz_center, R_tilt, tx, ty, tz) #print dety2,detz2 self.assertAlmostEqual(dety1, dety2, 4) self.assertAlmostEqual(detz1, detz2, 4)
def __init__(self, param, hkl, killfile=None): self.killfile = killfile self.param = param self.hkl = hkl self.grain = [] # Simple transforms of input and set constants self.K = -2 * n.pi / self.param['wavelength'] self.S = n.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # Detector tilt correction matrix self.R = tools.detect_tilt(self.param['tilt_x'], self.param['tilt_y'], self.param['tilt_z']) # wedge NB! wedge is in degrees # The sign is reversed for wedge as the parameter in # tools.find_omega_general is right handed and in ImageD11 # it is left-handed (at this point wedge is defined as in ImageD11) self.wy = -1. * self.param['wedge'] * n.pi / 180. self.wx = 0. # Spatial distortion if self.param['spatial'] != None: from ImageD11 import blobcorrector self.spatial = blobcorrector.correctorclass(self.param['spatial']) # %No of images self.nframes = (self.param['omega_end'] - self.param['omega_start']) / self.param['omega_step'] # Generate Miller indices for reflections within a certain resolution print('Generating reflections') print('Finished generating reflections\n')
def forw_proj(xyz_s,phi_up,phi_lo,omega,theta,M,t_x,t_y,t_z,mode="horizontal",detect="ideal"): """ Calculate the detector coordinate [x_d,0,z_d] hit by the diffracted beam from a given volume element [x_s,y_s,z_s] with a specific orientation [omega,phi_lo,phi_up] at diffraction angle 2theta using a setup of type mode ("horizontal"/"vertical") with magnification M and detector tilt [t_x,t_y,tz] on a detector that is either in the ideal or real system Usage: [x_d,0,z_d] = forw_proj([x_s,y_s,z_s],omega,alpha,beta,M,t_x,t_y,t_z,mode="horizontal") """ det_tilt = tools.detect_tilt(t_x,t_y,t_z) th = n.pi*theta/180. if detect=="ideal": det_tilt_frame = n.eye(3) elif mode=="horizontal": det_tilt_frame = n.array([[ n.cos(th), -n.sin(th), 0], [ n.sin(th), n.cos(th), 0], [ 0, 0, 1]]) elif mode=="vertical": det_tilt_frame = n.array([[ 1, 0, 0], [ 0, n.cos(th), -n.sin(th)], [ 0, n.sin(th), n.cos(th)]]) xyz_d = -M*n.dot(det_tilt,n.dot(det_tilt_frame,n.dot(trans_sample_to_image(phi_up,phi_lo,omega,theta,mode),n.array(xyz_s)))) return [xyz_d[0],0,xyz_d[2]]
def gexp(w, dety, detz, wx, wy, tx, ty, tz, py, pz, cy, cz, L, x, y, z): """ Experimental g-vector calculation Input: observables: w,dety,detz global parameters: wx,wy,tx,ty,tz,py,pz,cy,cz,L grain position: x,y,z Output: vars, vector of propagated errors Jette Oddershede, July 2008 """ Omega = tools.quart_to_omega(w, wx * n.pi / 180, wy * n.pi / 180) R = tools.detect_tilt(tx, ty, tz) d = n.dot(R, n.array([[0], [(dety + cy) * py], [(detz - cz) * pz]])) d = d + n.array([[L], [0], [0]]) - n.dot(Omega, n.array([[x], [y], [z]])) gexp = n.dot(n.transpose(Omega), (d / n.sqrt(n.sum(d**2)) - n.array([[1], [0], [0]]))) return gexp
def __init__(self,param,hkl,killfile=None): ''' A find_refl object is used to hold information that otherwise would have to be recomputed for during the algorithm execution in run(). ''' self.killfile = killfile self.param = param self.hkl = hkl self.voxel = [None]*self.param['no_voxels'] # Simple transforms of input and set constants self.K = -2*np.pi/self.param['wavelength'] self.S = np.array([[1, 0, 0],[0, 1, 0],[0, 0, 1]]) # Detector tilt correction matrix self.R = tools.detect_tilt(self.param['tilt_x'], self.param['tilt_y'], self.param['tilt_z']) # wedge NB! wedge is in degrees # The sign is reversed for wedge as the parameter in # tools.find_omega_general is right handed and in ImageD11 # it is left-handed (at this point wedge is defined as in ImageD11) self.wy = -1.*self.param['wedge']*np.pi/180. self.wx = 0. w_mat_x = np.array([[1, 0 , 0 ], [0, np.cos(self.wx), -np.sin(self.wx)], [0, np.sin(self.wx), np.cos(self.wx)]]) w_mat_y = np.array([[ np.cos(self.wy), 0, np.sin(self.wy)], [0 , 1, 0 ], [-np.sin(self.wy), 0, np.cos(self.wy)]]) self.r_mat = np.dot(w_mat_x,w_mat_y) # Spatial distortion if self.param['spatial'] != None: from ImageD11 import blobcorrector self.spatial = blobcorrector.correctorclass(self.param['spatial']) # %No of images self.nframes = (self.param['omega_end']-self.param['omega_start'])/self.param['omega_step'] self.peak_merger = cms_peak_compute.PeakMerger( self.param )
def write_gve(param, grain, hkl): """ Write gvector (gve) file, for format see http://fable.wiki.sourceforge.net/imaged11+-+file+formats Henning Osholm Sorensen, RisoeDTU, 2008. python translation: Jette Oddershede, Risoe DTU, March 31 2008 changed October 1, 2008 to new .gve format including detector.par and [xl,yl,zl] """ A = grain[0].refs for grainno in range(1, param['no_grains']): A = n.concatenate((A, grain[grainno].refs)) nrefl = A.shape[0] # from detector.par (z_center, y_center) = detector.detyz_to_xy( [param['dety_center'], param['detz_center']], param['o11'], param['o12'], param['o21'], param['o22'], param['dety_size'], param['detz_size']) dout = "# chi 0.0\n" dout = dout + "# distance %f\n" % (param['distance'] * 1000.) dout = dout + "# fit_tolerance 0.5\n" dout = dout + "# o11 %i\n" % param['o11'] dout = dout + "# o12 %i\n" % param['o12'] dout = dout + "# o21 %i\n" % param['o21'] dout = dout + "# o22 %i\n" % param['o22'] dout = dout + "# omegasign %f\n" % param['omega_sign'] dout = dout + "# t_x 0\n" dout = dout + "# t_y 0\n" dout = dout + "# t_z 0\n" dout = dout + "# tilt_x %f\n" % param['tilt_x'] dout = dout + "# tilt_y %f\n" % param['tilt_y'] dout = dout + "# tilt_z %f\n" % param['tilt_z'] dout = dout + "# y_center %f\n" % y_center dout = dout + "# y_size %f\n" % (param['y_size'] * 1000.) dout = dout + "# z_center %f\n" % z_center dout = dout + "# z_size %f\n" % (param['z_size'] * 1000.) for phase in param['phase_list']: if param['no_phases'] > 1: filename = '%s/%s_phase_%i.gve' % (param['direc'], param['stem'], phase) else: filename = '%s/%s.gve' % (param['direc'], param['stem']) f = open(filename, 'w') lattice = param['sgname_phase_%i' % phase][0] format = "%f " * 6 + "%s " * 1 + "\n" unit_cell = param['unit_cell_phase_%i' % phase] out = format % (unit_cell[0], unit_cell[1], unit_cell[2], unit_cell[3], unit_cell[4], unit_cell[5], lattice) out = out + "# wavelength = %s\n" % (param['wavelength']) out = out + "# wedge = %f\n" % (param['wedge']) out = out + "# axis = 0.000 0.0000 1.0000\n" # insert detector.par as comment out = out + "# cell__a %s\n" % unit_cell[0] out = out + "# cell__b %s\n" % unit_cell[1] out = out + "# cell__c %s\n" % unit_cell[2] out = out + "# cell_alpha %s\n" % unit_cell[3] out = out + "# cell_beta %s\n" % unit_cell[4] out = out + "# cell_gamma %s\n" % unit_cell[5] out = out + "# cell_lattice_[P,A,B,C,I,F,R] %s\n" % param[ 'sgname_phase_%i' % phase][0] out = out + dout # continue with gve format out = out + "# ds h k l\n" f.write(out) thkl = hkl[param['phase_list'].index(phase)].copy() ds = n.zeros((thkl.shape[0], 1)) for i in range(thkl.shape[0]): ds[i] = 2 * tools.sintl(unit_cell, thkl[i, 0:3]) #Add ds values to the thkl array thkl = n.concatenate((thkl, ds), 1) # sort rows according to ds, descending thkl = thkl[n.argsort(thkl, 0)[:, 4], :] # Output format format = "%f " * 1 + "%d " * 3 + "\n" for i in range(thkl.shape[0]): out = format % (thkl[i, 4], thkl[i, 0], thkl[i, 1], thkl[i, 2]) f.write(out) R_tilt = tools.detect_tilt(param['tilt_x'], param['tilt_y'], param['tilt_z']) out = "# xr yr zr xc yc ds eta omega spot3d_id xl yl zl\n" f.write(out) format = "%f " * 8 + "%i " * 1 + "%f " * 3 + "\n" for i in range(nrefl): (sc, fc) = detector.detyz_to_xy( [A[i, A_id['dety']], A[i, A_id['detz']]], param['o11'], param['o12'], param['o21'], param['o22'], param['dety_size'], param['detz_size']) [xl, yl, zl] = detector.detector_to_lab(A[i, A_id['dety']], A[i, A_id['detz']], param['distance'], param['y_size'], param['z_size'], param['dety_center'], param['detz_center'], R_tilt) out = format % ( A[i, A_id['gv1']] / (2 * n.pi), A[i, A_id['gv2']] / (2 * n.pi), A[i, A_id['gv3']] / (2 * n.pi), sc, #A[i,A_id['detz']], fc, #param['dety_size']-A[i,A_id['dety']], (2 * n.sin(.5 * A[i, A_id['tth']]) / param['wavelength']), A[i, A_id['eta']] * 180 / n.pi, A[i, A_id['omega']] * 180 / n.pi, A[i, A_id['spot_id']], xl * 1000., yl * 1000., zl * 1000.) f.write(out) f.close()
def intensity(inp): """ Reject peaks based on intensity Jette Oddershede, August 27 2008 Absorption correction added December 2011 """ if inp.files['structure_file'] != None: inp.param['structure_phase_0'] = inp.files['structure_file'] xtal_structure = reflections.open_structure(inp.param,0) hkl = reflections.gen_miller(inp.param,0) hkl = reflections.calc_intensity(hkl,xtal_structure) # print hkl if inp.fit['abs_mu'] > 0: xmin = min(inp.fit['abs_xlim'])*1e3 xmax = max(inp.fit['abs_xlim'])*1e3 ymin = min(inp.fit['abs_ylim'])*1e3 ymax = max(inp.fit['abs_ylim'])*1e3 for i in range(inp.no_grains): x = deepcopy(inp.values['x%s' %i]) y = deepcopy(inp.values['y%s' %i]) z = deepcopy(inp.values['z%s' %i]) #Make sure that grain not outside of bounds for doing the correction if inp.fit['abs_mu'] > 0: if x < xmin: x = xmin elif x > xmax: x = xmax if y < ymin: y = ymin elif y > ymax: y = ymax for j in range(inp.nrefl[i]): h = inp.h[i][j] k = inp.k[i][j] l = inp.l[i][j] # Absorption correction start if inp.fit['abs_mu'] > 0: w = inp.w[inp.id[i][j]] dety = inp.dety[inp.id[i][j]] detz = inp.detz[inp.id[i][j]] Omega = tools.form_omega_mat_general(w*n.pi/180.,inp.values['wx']*n.pi/180.,inp.values['wy']*n.pi/180.) R = tools.detect_tilt(inp.values['tx'],inp.values['ty'],inp.values['tz']) d_out = n.dot(R,n.array([[0], [(dety-inp.values['cy'])*inp.values['py']], [(detz-inp.values['cz'])*inp.values['pz']]])) d_out = d_out + n.array([[inp.values['L']],[0],[0]]) - n.dot(Omega,n.array([[x],[y],[z]])) d_out = n.dot(n.transpose(Omega),d_out/n.sqrt(n.sum(d_out**2))) d_in = n.dot(n.transpose(Omega),n.array([[-1],[0],[0]])) #from grain to source! # distance to bounding planes assuming d_in and d_out unit vectors xdist_in = 1e6 xdist_out = 1e6 ydist_in = 1e6 ydist_out = 1e6 if d_in[0] < 0: xdist_in = (x-xmin)/abs(d_in[0,0]) elif d_in[0] > 0: xdist_in = (xmax-x)/abs(d_in[0,0]) if d_in[1] < 0: ydist_in = (y-ymin)/abs(d_in[1,0]) elif d_in[1] > 0: ydist_in = (ymax-y)/abs(d_in[1,0]) dist_in = min(xdist_in,ydist_in) if d_out[0] < 0: xdist_out = (x-xmin)/abs(d_out[0,0]) elif d_out[0] > 0: xdist_out = (xmax-x)/abs(d_out[0,0]) if d_out[1] < 0: ydist_out = (y-ymin)/abs(d_out[1,0]) elif d_out[1] > 0: ydist_out = (ymax-y)/abs(d_out[1,0]) dist_out = min(xdist_out,ydist_out) dist = dist_in + dist_out # abs_mu in mm-1 and dist in microns exponential = n.exp(inp.fit['abs_mu']*dist*1e-3) #print h,k,l,w,x,y,z,dist_in*1e-3,dist_out*1e-3,dist*1e-3,exponential else: exponential = 1. # Absorption correction end value = False for m in range(len(hkl)): if hkl[m][0] == h and hkl[m][1] == k and hkl[m][2] == l: inp.volume[i][j] = inp.F2vol[inp.id[i][j]]/hkl[m][3]*exponential value = True break else: pass if value == False: # print i+1,j+1,h,k,l,'should never go here, ask osho for help...' inp.volume[i][j] = -1 data = deepcopy(inp.volume) minvol = [] maxvol = [] for i in range(inp.no_grains): if i+1 in inp.fit['skip']: pass else: rej = [] newreject = 1 while newreject > 0: tmp = len(rej) mad(data[i],rej,inp.fit['rej_vol']) newreject = len(rej) - tmp avgdata = n.sum(data[i])/len(data[i]) sigdata = spread(data[i]) if len(rej) > 1: avgrej = n.sum(rej)/len(rej) sigrej = spread(rej) elif len(rej) == 1: avgrej = rej[0] sigrej = 0 else: avgrej = 0 sigrej = 0 if len(data[i]) > 0: minvol.append(max(0,min(data[i]))) maxvol.append(max(data[i])) else: minvol.append(0) maxvol.append(-1) if i+1 not in inp.fit['skip']: inp.fit['skip'].append(i+1) # print '\n',i, avgdata, sigdata, len(data[i]), minvol[i], maxvol[i],'\n ',avgrej, sigrej, len(reject)#,'\n',data[i],'\n',reject delete = 0 for i in range(inp.no_grains): if i+1 in inp.fit['skip']: pass else: for j in range(inp.nrefl[i]-1,-1,-1): if inp.volume[i][j] < minvol[i] or inp.volume[i][j] > maxvol[i]: reject(inp,i,j,'intensity') delete = delete + 1 print 'Rejected', delete, 'peaks because of different intensity scales' insignificant(inp)
def find_refl(inp): """ From U, (x,y,z) and B determined for the far-field case calculate the possible reflection on the near-field detector output[grainno][reflno]=[h,k,l,omega,dety,detz,tth,eta] """ S = n.array([[1, 0, 0],[0, 1, 0],[0, 0, 1]]) R = tools.detect_tilt(inp.param['tilt_x'], inp.param['tilt_y'], inp.param['tilt_z']) inp.possible = [] # if structure info is given use this if inp.files['structure_file'] != None: inp.param['structure_phase_0'] = inp.files['structure_file'] xtal_structure = reflections.open_structure(inp.param,0) HKL = reflections.gen_miller(inp.param,0) else: inp.param['unit_cell_phase_0'] = inp.unit_cell inp.param['sgno_phase_0'] = inp.fit['sgno'] HKL = reflections.gen_miller(inp.param,0) for grainno in range(inp.no_grains): inp.possible.append([]) if grainno+1 not in inp.fit['skip']: B = tools.epsilon_to_b(n.array([inp.values['epsaa%s' %grainno], inp.values['epsab%s' %grainno], inp.values['epsac%s' %grainno], inp.values['epsbb%s' %grainno], inp.values['epsbc%s' %grainno], inp.values['epscc%s' %grainno]]), inp.unit_cell) U = tools.rod_to_u([inp.rod[grainno][0]+inp.values['rodx%s' %grainno], inp.rod[grainno][1]+inp.values['rody%s' %grainno], inp.rod[grainno][2]+inp.values['rodz%s' %grainno]]) gr_pos = n.array([inp.values['x%s' %grainno], inp.values['y%s' %grainno], inp.values['z%s' %grainno]]) for hkl in HKL: Gc = n.dot(B,hkl[0:3]) Gw = n.dot(S,n.dot(U,Gc)) tth = tools.tth2(Gw,inp.param['wavelength']) # print hkl[0:3],tth*180./n.pi costth = n.cos(tth) (Omega, Eta) = tools.find_omega_general(inp.param['wavelength']/(4.*n.pi)*Gw, tth, inp.values['wx']*n.pi/180, inp.values['wy']*n.pi/180) if len(Omega) > 0: for solution in range(len(Omega)): omega = Omega[solution] eta = Eta[solution] for i in range(len(inp.fit['w_limit'])//2): if (inp.fit['w_limit'][2*i]*n.pi/180) < omega and\ omega < (inp.fit['w_limit'][2*i+1]*n.pi/180): # form Omega rotation matrix Om = tools.form_omega_mat_general(omega,inp.values['wx']*n.pi/180,inp.values['wy']*n.pi/180) Gt = n.dot(Om,Gw) # Calc crystal position at present omega [tx,ty,tz]= n.dot(Om,gr_pos) # Calc detector coordinate for peak (dety, detz) = detector.det_coor(Gt,costth, inp.param['wavelength'], inp.param['distance'], inp.param['y_size'], inp.param['z_size'], inp.param['y_center'], inp.param['z_center'], R,tx,ty,tz) #If peak within detector frame store it in possible if (-0.5 < dety) and\ (dety < inp.fit['dety_size']-0.5) and\ (-0.5 < detz) and\ (detz < inp.fit['detz_size']-0.5): inp.possible[grainno].append([hkl[0], hkl[1], hkl[2], omega*180/n.pi, dety, detz, tth, eta])
def write_delta_gve(param,voxel,hkl): if not memory_safety_check(param): return """ Write gvector (gve) file, for format see http://fable.wiki.sourceforge.net/imaged11+-+file+formats python translation: March 31 2008 changed October 1, 2008 to new .gve format including detector.par and [xl,yl,zl] """ # from detector.par (z_center, y_center) = detector.detyz_to_xy([param['dety_center'],param['detz_center']], param['o11'], param['o12'], param['o21'], param['o22'], param['dety_size'], param['detz_size']) dout = "# chi 0.0\n" dout = dout + "# distance %f\n" %(param['distance']*1000.) dout = dout + "# fit_tolerance 0.5\n" dout = dout + "# o11 %i\n" %param['o11'] dout = dout + "# o12 %i\n" %param['o12'] dout = dout + "# o21 %i\n" %param['o21'] dout = dout + "# o22 %i\n" %param['o22'] dout = dout + "# omegasign %f\n" %param['omega_sign'] dout = dout + "# t_x 0\n" dout = dout + "# t_y 0\n" dout = dout + "# t_z 0\n" dout = dout + "# tilt_x %f\n" %param['tilt_x'] dout = dout + "# tilt_y %f\n" %param['tilt_y'] dout = dout + "# tilt_z %f\n" %param['tilt_z'] dout = dout + "# y_center %f\n" %y_center dout = dout + "# y_size %f\n" %(param['y_size']*1000.) dout = dout + "# z_center %f\n" %z_center dout = dout + "# z_size %f\n" %(param['z_size']*1000.) for phase in param['phase_list']: if param['no_phases'] > 1: filename = '%s/%s%s_phase_%i.gve' %(param['direc'],'delta_peaks_',param['stem'],phase) else: filename = '%s/%s%s.gve' %(param['direc'],'delta_peaks_',param['stem']) with open(filename,'w') as f: lattice = param['sgname_phase_%i' %phase][0] format = "%f "*6 + "%s "*1 +"\n" unit_cell = param['unit_cell_phase_%i' %phase] out = format %(unit_cell[0],unit_cell[1],unit_cell[2], unit_cell[3],unit_cell[4],unit_cell[5], lattice) out = out + "# wavelength = %s\n" %(param['wavelength']) out = out + "# wedge = %f\n" %(param['wedge']) out = out + "# axis = 0.000 0.0000 1.0000\n" # insert detector.par as comment out = out + "# cell__a %s\n" %unit_cell[0] out = out + "# cell__b %s\n" %unit_cell[1] out = out + "# cell__c %s\n" %unit_cell[2] out = out + "# cell_alpha %s\n" %unit_cell[3] out = out + "# cell_beta %s\n" %unit_cell[4] out = out + "# cell_gamma %s\n" %unit_cell[5] out = out + "# cell_lattice_[P,A,B,C,I,F,R] %s\n" %param['sgname_phase_%i' %phase][0] out = out + dout # continue with gve format out = out +"# ds h k l\n" f.write(out) thkl = hkl[param['phase_list'].index(phase)].copy() ds = n.zeros((thkl.shape[0],1)) for i in range(thkl.shape[0]): ds[i] = 2*tools.sintl(unit_cell,thkl[i,0:3]) #Add ds values to the thkl array thkl = n.concatenate((thkl,ds),1) # sort rows according to ds, descending thkl = thkl[n.argsort(thkl,0)[:,4],:] # Output format format = "%f "*1 + "%d "*3 +"\n" for i in range(thkl.shape[0]): out = format %(thkl[i,4], thkl[i,0], thkl[i,1], thkl[i,2] ) f.write(out) R_tilt = tools.detect_tilt(param['tilt_x'],param['tilt_y'],param['tilt_z']) out = "# xr yr zr xc yc ds eta omega spot3d_id xl yl zl\n" f.write(out) # TODO: if we are writing huge files we need to be a little # bit tender with the ram usage. Which is still kinda stupid # as whoever tries to read such a file to RAM will get a # nasty suprise. Perhaps a better solution is to write several .flt files # Anyway, this should not be a problem once peakmerging is implemented if param['no_voxels']>100: collected_voxels = 0 ranges = [] while( True ): low_line = collected_voxels top_line = collected_voxels + 100 if top_line < param['no_voxels']: ranges.append([low_line,top_line]) else: ranges.append([low_line,param['no_voxels']]) break collected_voxels = top_line else: ranges = [[0,param['no_voxels']]] #Local implementation of detecter.detyz_to_xy() for speed #-------------------------------------------------------- if abs(param['o11']) == 1: if (abs(param['o22']) != 1) or (param['o12'] != 0) or (param['o21'] != 0): raise ValueError('detector orientation makes no sense 1') elif abs(param['o12']) == 1: if abs(param['o21']) != 1 or (param['o11'] != 0) or (param['o22'] != 0): raise ValueError('detector orientation makes no sense 2') else: raise ValueError('detector orientation makes no sense 3') omat = n.array([[param['o11'], param['o12']], [param['o21'], param['o22']]]) omat = n.linalg.inv(omat) det_size = n.array([param['detz_size']-1, param['dety_size']-1]) term2 = n.clip(n.dot(omat, det_size),-n.max(det_size), 0) def detyz_to_xy(coor,omat,det_size,term2): coor = n.array([coor[1], coor[0]]) coor = n.dot(omat, coor) - term2 return coor #------------------------------------------------------------- format = "%f "*8 + "%i "*1+ "%f "*3+"\n" nrefl = 0 for ran in ranges: out="" A = voxel[ ran[0] ].refs for voxelno in range(ran[0]+1,ran[1]): A = n.concatenate((A,voxel[voxelno].refs)) for i in range(A.shape[0]): (sc, fc) = detector.detyz_to_xy([A[i,A_id['dety']],A[i,A_id['detz']]], param['o11'], param['o12'], param['o21'], param['o22'], param['dety_size'], param['detz_size']) [xl,yl,zl] = detector.detector_to_lab(A[i,A_id['dety']],A[i,A_id['detz']], param['distance'], param['y_size'],param['z_size'], param['dety_center'],param['detz_center'], R_tilt) out = out + (format %(A[i,A_id['gv1']]/(2*n.pi), A[i,A_id['gv2']]/(2*n.pi), A[i,A_id['gv3']]/(2*n.pi), sc,#A[i,A_id['detz']], fc,#param['dety_size']-A[i,A_id['dety']], (2*n.sin(.5*A[i,A_id['tth']])/param['wavelength']), A[i,A_id['eta']]*180/n.pi, A[i,A_id['omega']]*180/n.pi, A[i,A_id['spot_id']], xl*1000., yl*1000., zl*1000. ) ) f.write(out) nrefl = nrefl + A.shape[0] print('\rFinished %3i of %3i voxels. Written %3i reflections to file' %(ran[1],param['no_voxels'],nrefl), end=' ') sys.stdout.flush() print("\n")
def __init__(self,param,hkl,voxel_positions,measured_data, unit_cell, initial_guess, ymin, no_yscans, C, constraint, save_dir=None): ''' A find_refl object is used to hold information that otherwise would have to be recomputed for during the algorithm execution in run(). ''' # print(voxel_positions) # raise self.C = C self.constraint = constraint self.count=0 self.no_yscans = no_yscans self.save_dir = save_dir self.steplength_termination = 10**(-8) self.maxiter = 50 self.initial_guess = initial_guess self.UB_matrices = None self.no_voxels = param['no_voxels'] self.beam_width = param['beam_width'] self.omega_start = param['omega_start']*np.pi/180 self.omega_end = param['omega_end']*np.pi/180 self.omega_step = param['omega_step'] self.omega_sign = param['omega_sign'] self.wavelength = param['wavelength'] self.scale_Gw = self.wavelength/(4.*np.pi) self.detz_center = param['detz_center'] self.dety_center = param['dety_center'] self.z_size = param['z_size'] self.y_size = param['y_size'] self.distance = param['distance'] self.o11 = param['o11'] self.o12 = param['o12'] self.o21 = param['o21'] self.o22 = param['o22'] self.dety_size = param['dety_size'] self.detz_size = param['detz_size'] self.lorentz_apply = param['lorentz_apply'] self.tilt_x = param['tilt_x'] self.tilt_y = param['tilt_y'] self.tilt_z = param['tilt_z'] self.wedge = param['wedge'] self.voxel_positions = voxel_positions #should be np array self.voxel = [None]*self.no_voxels # Simple transforms of input and set constants self.S = np.array([[1, 0, 0],[0, 1, 0],[0, 0, 1]]) # Detector tilt correction matrix self.R = tools.detect_tilt(self.tilt_x, self.tilt_y, self.tilt_z) # wedge NB! wedge is in degrees # The sign is reversed for wedge as the parameter in # tools.find_omega_general is right handed and in ImageD11 # it is left-handed (at this point wedge is defined as in ImageD11) self.wy = -1.*self.wedge*np.pi/180. self.wx = 0. w_mat_x = np.array([[1, 0 , 0 ], [0, np.cos(self.wx), -np.sin(self.wx)], [0, np.sin(self.wx), np.cos(self.wx)]]) w_mat_y = np.array([[ np.cos(self.wy), 0, np.sin(self.wy)], [0 , 1, 0 ], [-np.sin(self.wy), 0, np.cos(self.wy)]]) self.r_mat = np.dot(w_mat_x,w_mat_y) self.original_measured_data = copy.deepcopy(measured_data) self.measured_data = measured_data # numpy array, first index is dty, then a nx3 list of (sc,fc,omega) self.ymin = ymin #microns (same as self.measured_data) self.total_number_of_measured_peaks=0 for dty in self.measured_data: self.total_number_of_measured_peaks+=len(dty) self.iter = 0 # Used for merging delta peaks into clusters dety_tol, detz_tol, om_tol = self.pick_merge_tolerance() self.dety_tol = dety_tol self.detz_tol = detz_tol self.om_tol = om_tol self.nmedian = 5 self.threshold = self.form_weighted_error([self.dety_tol/2.,self.detz_tol/2.,self.om_tol/2.],[0,0,0]) self.peak_merger = cms_peak_compute.PeakMerger( param, self.voxel, self.voxel_positions, dety_tol, detz_tol, om_tol, self.ymin ) # weigth to make all units in units of pixels/voxels in framestack # self.dety_weight = self.omega_step / np.degrees( np.arctan( self.y_size/self.distance ) ) # self.detz_weight = self.omega_step / np.degrees( np.arctan( self.z_size/self.distance ) ) # self.omega_weight = 1 self.unit_cell = unit_cell self.hkl = hkl self.half_pixel_error = self.form_weighted_error([np.sqrt(0.5)]*3,[0]*3) if self.save_dir is not None: self.write_meta_data(param) self.iterations_info = np.zeros( (self.maxiter+1, 7) ) self.headers = ["iteration", "cost", "gamma","norm of step","worst fitted peak","peaks used (%)","time (min)"] self.iteration_file = 'iteration_info' self.solutions = 'solutions' if self.save_dir is not None: with open(self.save_dir +"/"+ self.iteration_file, 'w') as fn: for i,head in enumerate(self.headers): fn.write(head.replace(" ","")+"="+str(i)+"\n") fn.write("\n") os.mkdir(self.save_dir+'/'+self.solutions) np.save( self.save_dir+'/'+self.solutions+'/initial_guess', np.asarray(self.initial_guess) )