def getRefdataMask(self,*args): flt = 1 if 'step' in args: flt *= (self.data.ones()*self.data.scan[0]).filter().ones() fig,ax = plt.subplots(1,2,num=fig.number,sharex=True,sharey=True) tools.imagesc(((it/np.mean(it,0))-1).reshape(it.shape[0],-1)) self.refDataFilter = flt
def _plotStripe(self,points,i,rmin,rmax): ax = self.xpx ay = self.ypx #find closest points to find limits m = np.diff(points[:,1])/np.diff(points[:,0]) c = points[0,1] - points[0,0]*m m_ = -1/m dist_perp = (ay-m*ax-c)/np.sqrt(m**2+1) dist_par = (ay-m_*ax)/np.sqrt(m_**2+1) distparrange = dist_par[np.abs(dist_perp)<=rmax] distparrange = [np.min(distparrange),np.max(distparrange)] i[np.abs(dist_perp)<rmin] = np.nan tperpvec = np.arange(-rmax,rmax,110.*np.sqrt(2)) tparvec = np.arange(distparrange[0],distparrange[1],110.*np.sqrt(2)) perpind = np.digitize(dist_perp.ravel(),tperpvec) parind = np.digitize(dist_par.ravel(),tparvec) binning = np.ravel_multi_index((perpind,parind),(len(tperpvec)+1,len(tparvec)+1)) numperbin = np.bincount(binning) wireROI = np.bincount(binning, weights=np.asfarray(i.ravel())) wireROI = wireROI/numperbin P = np.zeros((len(tperpvec)+1) * (len(tparvec)+1)) P[:len(wireROI)] = wireROI P = np.reshape(P,(len(tperpvec)+1,len(tparvec)+1)) pl.clf() tools.imagesc(tparvec[:-1]+np.mean(np.diff(tparvec)), tperpvec[:-1]+np.mean(np.diff(tperpvec)), P[1:-1,1:-1]) tools.clim_std() pl.axis('normal') pl.draw()
def _refinePoints(self,points,i,refinerad=5000): #refine points newpoints = [] reffig = pl.figure() for point in points: xind = (point[0]-refinerad <= self.xVec) & (self.xVec <= point[0]+refinerad) yind = (point[1]-refinerad <= self.yVec) & (self.yVec <= point[1]+refinerad) pl.clf() tools.imagesc(self.xVec[xind],self.yVec[yind], i[np.min(yind.nonzero()):np.max(yind.nonzero())+1,np.min(xind.nonzero()):np.max(xind.nonzero())+1]) pl.plot(point[0],point[1],'go') tools.clim_std() pl.draw() newpoints.append(pl.ginput(1)[0]) points = np.array(newpoints) return points
def testCorrfunc(self,order=5,ic=None): fig = tools.nfigure('test_correction_func_order_%d'%order) plt.clf() fig,ax = plt.subplots(1,2,num=fig.number) plt.axes(ax[0]) it = (self.Imat.T/self.I0).T tools.imagesc(np.arange(np.shape(self.Imat)[1]),self.I0,(it/np.mean(it,0))-1) tools.clim_std(2) plt.colorbar() plt.draw() cf = self.getCorrFunc(order=order,i0_wp=ic,wrapit=False) Icorr = cf(self.Imat,self.I0) plt.axes(ax[1]) it = (Icorr.T/self.I0).T tools.imagesc((it/np.mean(it,0))-1) tools.clim_std(2) plt.colorbar()
def createWireMask(self,data=None): if data==None: import ixppy d = ixppy.dataset('/reg/g/xpp/data/example_data/cspad/liquid_scattering/hdf5/xpp43512-r0004.h5',['cspad']) data = d.cspad.rdStepData(0,range(10)) i = np.mean(data,axis=0) ib = self.bin(i) tools.imagesc(self.xVec,self.yVec,ib) tools.clim_std() pl.draw() print "Roughly select wire end pairs, press middle mouse button when finished." wires = [] tpos = np.array(pl.ginput(2)) pointno = 0 while not tpos==[]: tpos = np.array(tpos) pl.plot(tpos[:,0],tpos[:,1],'go-') for pno in range(2):pl.text(tpos[pno,0],tpos[pno,1],str(pointno),color='r') wires.append(tpos) pointno += 1 tpos = pl.ginput(2) refwires = [] for pos in wires: refwires.append(self._refinePoints(pos,ib)) wirewidths = [] print refwires for refwire in refwires: trad = self._getOneWire(refwire,i,rmax=1000) wirewidths.append(trad) masked = np.zeros(np.shape(i),dtype=bool) ax = self.xpx ay = self.ypx for refwire,wirewidth in zip(refwires,wirewidths): points = refwire m = np.diff(points[:,1])/np.diff(points[:,0]) c = points[0,1] - points[0,0]*m m_ = -1/m dist_perp = (ay-m*ax-c)/np.sqrt(m**2+1) dist_par = (ay-m_*ax)/np.sqrt(m_**2+1) masked[np.abs(dist_perp)<wirewidth] = True np.save('cspad_last_pixel_mask.npy',masked)
def getCorr(order=5,i0=None,Imat=None,i0_wp=1e6,fraclims_dc=[.9,1.1]): """ Getting nonlinear correction factors form a calibration dataset consiting of: i0 array of intensities the calibration has been made for Imat 2D array of the corresponding reference patterns, in each row there is one ravelled array of each intensity bin in i0. i0_wp a working point around which a correction polynomial will be developed for each pixel. order the polynomial order up to which will be deveoped. fraclims_dc relative factor for the i0,Imat data limits which are used to determine the working point location. Returns """ #i0,Imat = getData() msk = tools.filtvec(i0,i0_wp*np.asarray(fraclims_dc)) p0 = tools.polyFit(i0[msk],Imat[msk,:],2) dc = tools.polyVal(p0,i0_wp) comps = tools.polyFit(i0-i0_wp,Imat-dc,order,removeOrders=[0]) compsder = tools.polyDer(comps) c = lambda(i): tools.polyVal(comps,i-np.asarray(tools.iterfy(i0_wp)))+dc c_prime = lambda(i): tools.polyVal(compsder,i-np.asarray(tools.iterfy(i0_wp))) t = lambda(i): (c_prime(i0_wp).T * (i-i0_wp)).T + dc cprimeic = c_prime(i0_wp) dcorr_const = -cprimeic*i0_wp + c(i0_wp) - t(0) def dcorr(i,D): return (i*cprimeic.T + dcorr_const.T + ((D-c(i))*cprimeic/c_prime(i)).T).T #return (i*cprimeic.T + dcorr_const.T ).T return dcorr,comps,t tools.nfigure('testplot') plt.clf() plt.subplot(1,2,1) Imean = (Imat.T/i0).T tools.imagesc(np.asarray([ti / np.mean(Imean[-10:,:],0) for ti in Imean])) tools.clim_std(6) cl = plt.gci().get_clim() plt.colorbar() plt.set_cmap(plt.cm.RdBu_r) plt.subplot(1,2,2) cmps = copy.copy(comps) cmps[-2,:] = 0 cc = lambda(i): tools.polyVal(cmps,i-np.asarray(tools.iterfy(i0_wp))) Ir = Imat-c(i0)+t(i0)-t(0) Ir = dcorr(i0,Imat) #Ir = ((Imat-cc(i0)).T/i0).T #tools.imagesc(Ir) Ir = (Ir.T/i0).T tools.imagesc(np.asarray([ti / np.mean(Ir[-10:,:],0) for ti in Ir])) plt.clim(cl) plt.colorbar() plt.set_cmap(plt.cm.RdBu_r) plt.draw() tools.nfigure('testplot_components') plt.clf() ah = None for n,comp in enumerate(comps): if ah is None: ah = plt.subplot(len(comps),1,n+1) else: plt.subplot(len(comps),1,n+1,sharex=ah) plt.plot(comp) lims = np.percentile(comp,[1,99]) plt.ylim(lims) return c,c_prime
def makeplots(i0,Imat,mask,ind=[27, 29, 37, 67],order=6): Imatref = Imat[np.ix_([27, 29, 37, 67])] i0ref = i0[np.ix_([27, 29, 37, 67])] dcorr,comps,t = getCorr(order,i0,Imat,i0ref[0]) patt = cspad.CspadPattern(Nx=300,Ny=300) if 1: Dcorr = dcorr(i0ref,Imatref) DcorrNorm = (Dcorr.T/i0ref).T DcorrNorm = rearrangeData(DcorrNorm,mask) ImatrefNorm = (Imatref.T/i0ref).T ImatrefNorm = rearrangeData(ImatrefNorm,mask) fig = tools.nfigure('figure2') #fig.set_size_inches(3.5,3) plt.clf() ah = None for n in range(3): if ah is None: ah = plt.subplot(2,3,n+1) tah = ah else: tah = plt.subplot(2,3,n+1,sharex=ah,sharey=ah) patt.imageShow((ImatrefNorm[1+n]/ImatrefNorm[0]-1)*100) plt.set_cmap(plt.cm.RdBu_r) plt.clim([-5,5]) plt.axis('equal') plt.axis([60000,13e4,6e4,13e4]) plt.setp(tah.get_xticklabels(), visible=False) plt.setp(tah.get_yticklabels(), visible=False) plt.text(6.4e4,11.8e4,['(a)','(b)','(c)'][n],fontsize=20,bbox={'facecolor':'white', 'alpha':1, 'pad':10}) tah = plt.subplot(2,3,n+4,sharex=ah,sharey=ah) pp = patt.bin((DcorrNorm[1+n]/DcorrNorm[0]-1)*100) im = tools.imagesc(patt.xVec,patt.yVec,pp) plt.set_cmap(plt.cm.RdBu_r) plt.clim([-5,5]) plt.axis('equal') plt.axis([60000,13e4,6e4,13e4]) plt.setp(tah.get_xticklabels(), visible=False) plt.setp(tah.get_yticklabels(), visible=False) plt.text(6.4e4,11.8e4,['(d)','(e)','(f)'][n],fontsize=20,bbox={'facecolor':'white', 'alpha':1, 'pad':10}) fig.subplots_adjust(left=.05,top=.95,bottom=.05,right=0.85,hspace=.05,wspace=.05) cbar_ax = fig.add_axes([0.88, 0.05, 0.03, 0.9]) fig.colorbar(im, cax=cbar_ax,label='Percent') # FIGURE 4 fig = tools.nfigure('figure4') #fig.set_size_inches(3.5,1.5) plt.clf() ah = None count=1 toplot = [t(0),comps[-3],comps[-4]] for n,comp in enumerate(toplot): if ah is None: ah = plt.subplot(1,3,count) tah = ah else: tah = plt.subplot(1,3,count,sharex=ah,sharey=ah) timg = rearrangeData([comp],mask) patt.imageShow(timg) plt.set_cmap(plt.cm.RdBu_r) #plt.clim([-5,5]) plt.axis('equal') plt.axis([60000,13e4,6e4,13e4]) plt.setp(tah.get_xticklabels(), visible=False) plt.setp(tah.get_yticklabels(), visible=False) plt.text(6.4e4,11.8e4,['$t(0)$','$g=2$','$g=3$','d','e','f','g','h','i','j','k'][n],fontsize=20,bbox={'facecolor':'white', 'alpha':1, 'pad':10}) count += 1 fig.subplots_adjust(left=.05,top=.95,bottom=.05,right=0.95,hspace=.05,wspace=.05)
def refineCen(self,i,segments=16,Nrbins='auto',cycles=5): #def refineCen(x,y,i,cen,R0ring,Rsearchlims,segments=16,Nrbins='auto',cycles=5): self.imageShow(i) x = self.xpx.ravel() y = self.ypx.ravel() print "Select ring center..." cen = np.asarray(plt.ginput(1))[0] print "Select point on ring ..." por = np.asarray(plt.ginput(1))[0] R0ring = np.sqrt(np.sum((por-cen)**2)) print "Select search limits ..." rslc = np.asarray(plt.ginput(2)) Rslc = np.sqrt(np.sum((rslc-cen)**2,axis=1)).ravel() Rslc.sort() Rsearchlims = Rslc-R0ring azedges = np.arange(0,segments+1)*(2*np.pi/segments)-np.pi if Nrbins=='auto': rbinsz = np.max(np.diff(np.sort(x.ravel()))) Rsearchlims = np.asarray(Rsearchlims) mask = None for cycle in range(cycles): redges = np.arange(R0ring+Rsearchlims[0],R0ring+Rsearchlims[1],rbinsz) R = np.sqrt((x-cen[0])**2+(y-cen[1])**2) A = np.arctan2(y-cen[1],x-cen[0]) rd = np.digitize(R.ravel(),redges) azd = np.digitize(A.ravel(),azedges) plt.figure(5) plt.hold(0) self.imageShow(azd.reshape(x.shape)) idx = np.ravel_multi_index(np.vstack([rd,azd]), (len(redges)+1,len(azedges)+1)) mnl = (len(redges)+1)*(len(azedges)+1) res = (np.bincount(idx,weights=i.ravel(),minlength=mnl)/np.bincount(idx,minlength=mnl)).reshape(len(redges)+1,len(azedges)+1)[1:-1,1:-1] rvec = tools.histVecCenter(redges) avec = tools.histVecCenter(azedges) #fts = [np.polyfit(rvec[~np.isnan(tprof)],tprof[~np.isnan(tprof)],2) for tprof in res.T if np.sum(~np.isnan(tprof))>1 else np.array([np.nan]*3)] if False: fts = [np.polyfit(rvec[~np.isnan(tprof)],tprof[~np.isnan(tprof)],2) if np.sum(~np.isnan(tprof))>1 else np.array([np.nan]*3) for tprof in res.T ] rts = np.asarray([np.unique(np.roots(np.polyder(tp)))[0] if not np.isnan(tp).all() else np.nan for tp in fts]) else: rts = [] #rts = [tools.peakAna(rvec[~np.isnan(tprof)],tprof[~np.isnan(tprof)],3)[0] if np.sum(~np.isnan(tprof))>1 else np.nan for tprof in res.T ] for tprof in res.T: try: rts.append(np.float(tools.peakAna(rvec[~np.isnan(tprof)],tprof[~np.isnan(tprof)],3)[0])) except: rts.append(np.nan) plt.figure(100) plt.hold(0) plt.plot(rvec[~np.isnan(tprof)],tprof[~np.isnan(tprof)],'.-') plt.axvline(rts[-1]) plt.draw() plt.waitforbuttonpress() rts = np.asarray(rts) plt.figure(5) tools.imagesc(avec,rvec,res) plt.hold(1) if mask is None: plt.plot(avec,rts,'ow') mask = np.isnan(rts) mask[rts<np.min(rvec)] = True mask[rts>np.max(rvec)] = True mask[tools.maskPoints(avec,rts)] = True else: plt.plot(avec[~mask],rts[~mask],'ow') rts[mask] = np.nan plt.hold(0) #plt.figure(6) #for tp,pos,prf in zip(fts,rts,res.T): #plt.hold(0) # #plt.plot(rvec,prf,'k') #plt.hold(1) #plt.axvline(pos) #plt.plot(rvec,np.polyval(tp,rvec),'r') #sleep(.1) #plt.draw() xf,yf = tools.pol2cart(avec[~np.isnan(rts)],np.squeeze(rts[~np.isnan(rts)])) xc,yc,R0ring,chisq = tools.fitCircle(xf+cen[0],yf+cen[1],w=np.sum(~np.isnan(res),0)[~np.isnan(rts)]) plt.figure(1) plt.hold(1) plt.plot(xc,yc,'r+') plt.plot(xf+cen[0],yf+cen[1],'ow') plt.waitforbuttonpress() cen = [xc,yc] return cen,R0ring
def imageShow(self,I): img = self._bin(I) tools.imagesc(self.xVec,self.yVec,img)