def movie(data,aslice,plen,loop=1,direc='z',cmax=None,cmin=None): "movie(data,slice,pause,loop=1,direc='z')" gist.animate(1) if type(aslice) is types.IntType: num = aslice aslice = [slice(None)]*3 aslice[ord('x')-ord(direc)-1] = num for num in range(loop): for k in range(data.shape[0]): gist.fma() gist.pli(data[k][aslice],cmax=cmax,cmin=cmin) gist.pause(plen) gist.animate(0)
def imagesc(z,cmin=None,cmax=None,xryr=None,_style='default', palette=None, color='black',colormap=None): """Plot an image on axes. z -- The data cmin -- Value to map to lowest color in palette (min(z) if None) cmax -- Value to map to highest color in palette (max(z) if None) xryr -- (xmin, ymin, xmax, ymax) coordinates to print (0, 0, z.shape[1], z.shape[0]) if None _style -- A 'style-sheet' to use if desired (a default one will be used if 'default'). If None, then no style will be imposed. palette -- A string for a palette previously saved in a file (see write_palette) or an array specifying the red-green-blue values (2-d array N x 3) or gray-scale values (2-d array N x 1 or 1-d array). color -- The color to use for the axes. """ if xryr is None: xryr = (0,0,z.shape[1],z.shape[0]) try: _style = None saveval = gist.plsys(2) gist.plsys(saveval) except: _style = 'default' if not _hold: gist.fma() gist.animate(0) if _style is not None: if _style == "default": _style=os.path.join(_user_path,'image.gs') system = write_style.getsys(hticpos='below',vticpos='left',frame=1, color=color) fid = open(_style,'w') fid.write(write_style.style2string(system)) fid.close() gist.window(style=_style) _current_style=_style if cmax is None: cmax = max(ravel(z)) if cmin is None: cmin = min(ravel(z)) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(z,cmin=cmin,cmax=cmax) if (colormap is not None): palette=colormap change_palette(palette) gist.pli(byteimage,xryr[0],xryr[1],xryr[2],xryr[3]) return
def imagesc_cb(z,cmin=None,cmax=None,xryr=None,_style='default', zlabel=None,font='helvetica',fontsize=16,color='black', palette=None): """Plot an image on axes with a colorbar on the side. z -- The data cmin -- Value to map to lowest color in palette (min(z) if None) cmax -- Value to map to highest color in palette (max(z) if None) xryr -- (xmin, ymin, xmax, ymax) coordinates to print (0, 0, z.shape[1], z.shape[0]) if None _style -- A 'style-sheet' to use if desired (a default one will be used if 'default'). If None, then no style will be imposed. palette -- A string for a palette previously saved in a file (see write_palette) or an array specifying the red-green-blue values (2-d array N x 3) or gray-scale values (2-d array N x 1 or 1-d array). zlabel -- The label to attach to the colorbar (font, fontsize, and color match this). color -- The color to use for the ticks and frame. """ if xryr is None: xryr = (0,0,z.shape[1],z.shape[0]) if not _hold: gist.fma() gist.animate(0) if _style is not None: if _style == 'default': _style=os.path.join(_user_path,"colorbar.gs") system = write_style.getsys(hticpos='below',vticpos='left',frame=1,color=color) fid = open(_style,'w') fid.write(write_style.style2string(system)) fid.close() gist.window(style=_style) _current_style=_style if cmax is None: cmax = max(ravel(z)) if cmin is None: cmin = min(ravel(z)) cmax = float(cmax) cmin = float(cmin) change_palette(palette) byteimage = gist.bytscl(z,cmin=cmin,cmax=cmax) gist.pli(byteimage,xryr[0],xryr[1],xryr[2],xryr[3]) colorbar.color_bar(cmin,cmax,ncol=240,zlabel=zlabel,font=font,fontsize=fontsize,color=color)
def getFocusCents(zernlist={3: 1.}, nact=9, readnoise=10., usePoisson=1, sig=500. / 64, plot=0, fullpupil=0): """Compute centroids that would be obtained for a focus zernike term. zernlist can also be a phasescreen... """ import util.zernikeMod, util.centroid, util.tel nphs = (nact - 1) * 8 pupil = util.tel.Pupil(nphs, nphs / 2, 0) if fullpupil: pupil.fn[:] = 1 avphase = numpy.zeros((nact - 1, nact - 1), numpy.float64) if type(zernlist) == numpy.ndarray: phase = zernlist else: zern = util.zernikeMod.Zernike(pupil, max(zernlist.keys()) + 1) phase = numpy.zeros((nphs, nphs), "d") for key in zernlist.keys(): phase += zernlist[key] * zern.zern[key] #focus zernike for i in range(nact - 1): for j in range(nact - 1): avphase[i, j] = numpy.average( numpy.array(phase[i * 8:i * 8 + 8, j * 8:j * 8 + 8].flat)) c = util.centroid.centroid(nact - 1, pupil.fn, readnoise=readnoise, addPoisson=usePoisson, readbg=0., sig=sig) c.printmax = 1 cents = c.calc(phase) if plot: print "Max counts: %g, max, min per subap %g %g, plotting SHS image..." % ( max(c.tile.flat), max(c.photPerSubap.flat), min( c.photPerSubap.flat)) gist.fma() gist.pli(c.tile) #cents=util.centroid.calc(phase,8,pupil.fn) return c, phase, avphase
def matview(A,cmax=None,cmin=None,palette=None,color='black'): """Plot an image of a matrix. """ A = Numeric.asarray(A) if A.dtype.char in ['D','F']: print "Warning: complex array given, plotting magnitude." A = abs(A) M,N = A.shape A = A[::-1,:] if cmax is None: cmax = max(ravel(A)) if cmin is None: cmin = min(ravel(A)) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(A,cmin=cmin,cmax=cmax) change_palette(palette) gist.window(style='nobox.gs') _current_style='nobox.gs' gist.pli(byteimage) old_vals = gist.limits(square=1) vals = gist.limits(square=1) if color is None: return vp = gist.viewport() axv,bxv,ayv,byv = vp axs,bxs,ays,bys = vals[:4] # bottom left corner column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = -axs*(bxv-axv)/(bxs-axs) + axv gist.plt('b',posx,posy-0.005,justify='LT',color=color) # bottom left corner row gist.plt(str(M),posx-0.005,posy,justify='RB',color=color) # top left corner row posy = (M-ays)*(byv-ayv)/(bys-ays) + ayv gist.plt('b',posx-0.005,posy,justify='RT',color=color) # bottom right column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = (N-axs)*(bxv-axv)/(bxs-axs) + axv gist.plt(str(N),posx,posy-0.005,justify='RT',color=color)
def matview(A,cmax=None,cmin=None,palette=None,color='black'): """Plot an image of a matrix. """ A = numpy.asarray(A) if A.dtype.char in ['D','F']: print "Warning: complex array given, plotting magnitude." A = abs(A) M,N = A.shape A = A[::-1,:] if cmax is None: cmax = max(ravel(A)) if cmin is None: cmin = min(ravel(A)) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(A,cmin=cmin,cmax=cmax) change_palette(palette) gist.window(style='nobox.gs') _current_style='nobox.gs' gist.pli(byteimage) old_vals = gist.limits(square=1) vals = gist.limits(square=1) if color is None: return vp = gist.viewport() axv,bxv,ayv,byv = vp axs,bxs,ays,bys = vals[:4] # bottom left corner column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = -axs*(bxv-axv)/(bxs-axs) + axv gist.plt('b',posx,posy-0.005,justify='LT',color=color) # bottom left corner row gist.plt(str(M),posx-0.005,posy,justify='RB',color=color) # top left corner row posy = (M-ays)*(byv-ayv)/(bys-ays) + ayv gist.plt('b',posx-0.005,posy,justify='RT',color=color) # bottom right column posy = -ays*(byv-ayv)/(bys-ays) + ayv posx = (N-axs)*(bxv-axv)/(bxs-axs) + axv gist.plt(str(N),posx,posy-0.005,justify='RT',color=color)
def handle(self, data): """Handle data returned from the simulation""" if data[1] == "warning" or data[1] == "error": print "Error retrieving data", data[1:], data[0] elif len(self.gettype()) == 0: #not doing anything with it... pass else: if self.when[:3] != "rpt" or self.repeating == 1: #still expecting data if self.ret != None and data[3].has_key(self.ret): data = data[3][self.ret] else: data = None ret = self.ret if ret == None: ret = "None" if self.button == None: d = {ret: data, "button": None} else: d = {ret: data, "button": self.button[0]} try: exec self.preprocess in d except: pass if self.button != None: self.button[0] = d["button"] data = d[ret] dim = self.dim xaxis = self.xaxis if dim == None: if type(data) == numpy.ndarray: if len(data.shape) > 1: dim = 2 elif len(data.shape) == 1: dim = 1 else: dim = 0 else: dim = 0 if dim == 1: if type(self.xaxis) == types.NoneType: if len(data.shape) > 1: xaxis = data[0] data = data[1:] else: xaxis = numpy.arange(data.shape[0]) data = data else: if type(self.xaxis) == types.StringType: xaxis = eval(self.xaxis) if self.gisttype: if type(data) == numpy.ndarray: if not self.info.has_key("window"): self.info["window"] = 0 if not self.info.has_key("palette"): self.info["palette"] = "gray.gp" if not self.info.has_key("gistdpi"): self.info["gistdpi"] = 75 if self.gistWindow == None: self.gistWindow = gist.window( self.info["window"], wait=1, dpi=self.info["gistdpi"]) gist.animate(0) gist.animate(1) gist.palette(self.info["palette"]) else: gist.window(self.gistWindow) #gist.fma() if dim == 1: for i in range(data.shape[0]): gist.plg(data[i], xaxis) else: gist.pli(data) gist.fma() else: print "Cannot display type %s with gist" % str( type(data)) if self.pylabtype: if type(data) == numpy.ndarray: if not self.info.has_key("palette"): self.info["palette"] = "gray" if not self.info.has_key("interp"): self.info["interp"] = "nearest" if not self.info.has_key("plotwin"): self.info["plotwin"] = mypylab.plot() p = self.info["plotwin"] p.win.set_title(self.title) p.newPalette(self.info["palette"]) p.newInterpolation(self.info["interp"]) p.deactivatefn = self.cancel #deactivate p = self.info["plotwin"] if dim == 1: p.dims = 1 axis = xaxis else: p.dims = 2 axis = None if p.active: p.plot(data, axis=axis) else: if self.button != None: self.button[0] = 0 #print "Not expecting this data any more... (simdata.handle, type=pylab)" self.repeating = 0 else: print "Cannot display type %s with pylab" % str( type(data)) if self.texttype: #self.info["texttype"]=="ownwindow, mainwindow", default own #self.info["replace"]==1 or 0, default 0 if not self.info.has_key("wintype"): self.info["wintype"] = "ownwindow" if not self.info.has_key("textreplace"): self.info["textreplace"] = 0 if self.info["wintype"] == "ownwindow": if self.textWindow == None: self.textWindow = textbox(self.title) self.textWindow.closeFunc = self.cancel #deactivate if self.textWindow.destroyed == 0: #print "adding text",str(data) self.textWindow.addText( str(data) + "\n", replace=self.info["textreplace"]) else: #tell simulation not to send... print "Not expecting this data any more... (simdata.handle, type=text)" self.textWindow = None self.repeating = 0 else: print str(data) if self.savetype: if not self.info.has_key("filetype"): self.info["filetype"] = "fits" if not self.info.has_key("filename"): self.info["filename"] = "tmp.fits" if not self.info.has_key("filereplace"): self.info["filereplace"] = 0 if self.info["filetype"] == "fits": if type(data) == numpy.ndarray: print "WARNING - depreciated - use util.FITS instead (code needs updating)" if self.info["filereplace"]: imghdu = util.pyfits.PrimaryHDU( numarray.array(data)) imghdu.header.update("DATE", time.asctime()) imghdu.header.update("USER", os.environ["USER"]) imghdu.header.update( "CREATOR", "simctrl.py simulation control") imghdu.header.update("TITLE", str(self.title)) imghdu.header.update("COMMAND", str(self.cmd)) imghdu.header.update("RETURN", str(self.ret)) imghdu.header.update("TYPE", self.gettype()) imghdu.header.update("PREPROC", str(self.preprocess)) imghdu.header.update("DIMS", str(self.dim)) imghdu.header.update("XAXIS", str(self.xaxis)) imghdu.header.update("WHEN", str(self.when)) imghdu.header.update("INFO", str(self.info)) hdulist = util.pyfits.HDUList([imghdu]) hdulist.writeto(self.info["filename"], clobber=True) else: f = util.pyfits.open(self.info["filename"], mode="update") imghdu = util.pyfits.ImageHDU( numarray.array(data)) imghdu.header.update("DATE", time.asctime()) imghdu.header.update("USER", os.environ["USER"]) imghdu.header.update( "CREATOR", "simctrl.py simulation control") imghdu.header.update("TITLE", str(self.title)) imghdu.header.update("COMMAND", str(self.cmd)) imghdu.header.update("RETURN", str(self.ret)) imghdu.header.update("TYPE", self.gettype()) imghdu.header.update("PREPROC", str(self.preprocess)) imghdu.header.update("DIMS", str(self.dim)) imghdu.header.update("XAXIS", str(self.xaxis)) imghdu.header.update("WHEN", str(self.when)) imghdu.header.update("INFO", str(self.info)) f.append(imghdu) f.close() else: print "Cannot save fits data of this format:", type( data) elif self.info["filetype"] == "csv": if self.info["filereplace"]: mode = "w" else: mode = "a" f = open(self.info["filename"], mode) f.write( "#Date\t%s\n#User\t%s\n#Creator\tsimctrl.py simulation control\n#Title\t%s\n#Command\t%s\n#Return\t%s\n#Type\t%s\n#Preprocess\t%s\n#Dims\t%s\n#Xaxis\t%s\n#When\t%s\n#Info\t%s\n" % (time.asctime(), os.environ["USER"], str(self.title), str(self.cmd), str(self.ret), self.gettype(), str(self.preprocess), str(self.dim), str(self.xaxis), str( self.when), str(self.info))) if dim == 1: try: for i in range(xaxis.shape[0]): f.write("%g" % float(xaxis[i])) for j in range(data.shape[0]): f.write("\t%g" % float(data[j][i])) f.write("\n") f.write("\n") except: print "Data not in correct 1D format - can't save as csv" f.write(str(data)) f.write("\n\n") else: print "Can't save 2D data as csv... using text instead" f.write(str(data)) f.write("\n\n") f.close() elif self.info["filetype"] == "text": if self.info["filereplace"]: mode = "w" else: mode = "a" f = open(self.info["filename"], mode) f.write( "#Date\t%s\n#User\t%s\n#Creator\tsimctrl.py simulation control\n#Title\t%s\n#Command\t%s\n#Return\t%s\n#Type\t%s\n#Preprocess\t%s\n#Dims\t%s\n#Xaxis\t%s\n#When\t%s\n#Info\t%s\n" % (time.asctime(), os.environ["USER"], str(self.title), str(self.cmd), str(self.ret), self.gettype(), str(self.preprocess), str(self.dim), str(self.xaxis), str( self.when), str(self.info))) f.write(str(data)) f.write("\n\n") f.close() else: print "Unrecognised filetype - not saving" if self.feedbacktype: try: d = {"feedback": data} exec self.info["feedbackmsg"] in d msg = d["msg"] except: msg = "Feedback data:" + str(data) print msg exec self.post else: print "Warning: No longer expecting data for", self.cmd
def plotImg(img): import gist im=img[256*256:] im.shape=128,128 gist.fma() gist.pli(im)
spotpsf=numpy.zeros((fftsize,fftsize),"f") spotpsf[fftsize/2-5:fftsize/2+5,fftsize/2-5:fftsize/2+5]=1 spotpsf[fftsize/2-7:fftsize/2-3,fftsize/2-7:fftsize/2-3]=1 spotpsf[fftsize/2+3:fftsize/2+7,fftsize/2+3:fftsize/2+7]=1 elif spotpsfdim==4: spotpsf=numpy.zeros((nsubx,nsubx,fftsize,fftsize),"f") spotpsf[:,:,fftsize/2-5:fftsize/2+5,fftsize/2-5:fftsize/2+5]=1 spotpsf[:,:,fftsize/2-7:fftsize/2-3,fftsize/2-7:fftsize/2-3]=1 spotpsf[:,:,fftsize/2+3:fftsize/2+7,fftsize/2+3:fftsize/2+7]=1 spotpsf[2,2,fftsize/2-4:fftsize/2+4,fftsize/2-4:fftsize/2+4]=0 #spotpsf[2,2]=0. else: spotpsf=None if type(sig)==numpy.ArrayType: sig=sig.flat bimg=numpy.zeros((nsubx,nsubx,nimg,nimg),numpy.float32) print "Initialising" cc=util.centcmod.centcmod(nthreads,nsubx,ncen,fftsize,nimg,phasesize,readnoise,readbg,addPoisson,noiseFloor,sig,skybrightness,calsource,pxlPower,nintegrations,seed,reorderedPhs,pup,spotpsf,cents,bimg) print "Running" t=cc.run(calsource) print "Time taken",t def makeImage(bimg): img=numpy.zeros((nsubx*nimg,nsubx*nimg),numpy.float32) for i in range(nsubx): for j in range(nsubx): img[i*nimg:(i+1)*nimg,j*nimg:(j+1)*nimg]=bimg[i,j] return img gist.fma();gist.pli(makeImage(bimg))
import gist def plot_cross(x,y,sz=1,color='red'): gist.pldj([x],[y-sz],[x],[y+sz],color=color) gist.pldj([x-sz],[y],[x+sz],[y],color=color) file=os.path.join(os.path.dirname(__file__),'ascam1_20080710T230802.fits') data=pyfits.open(file)[0].data z=data[686-4-1-5-5:686+4-1+5-5,711-4-1-1-5:711+4-1-1+5] ##z=numpy.flipud(z) ana=iqe(z) gist.fma() gist.pli(z) plot_cross(ana[0]+.5,ana[1]+.5) ## sub-image Z = z[10:18,6:14].copy() ana=iqe(Z) gist.fma() gist.pli(Z) plot_cross(ana[0]+.5,ana[1]+.5) ## add hotspot Z = z[10:18,6:14].copy() Z[3,2]=10.*Z.max() anah=iqe(Z) gist.fma() gist.pli(Z)
def doit(zernlist=None, nact=9, cents=None, avphase=None, readnoise=10., usePoisson=1, sig=1000., fullpupil=0, monteNoiseCovariance=0, phaseCov="bccb", diagonaliseinvChatReordered=1, diagonaliseA=0.5, useChatFromDiagonalisedA=1, oversampleFFT=0, fft2d=1, oversampleAndBinFFTofr=0, removeHiFreqZ=0, removeHiFreqP=0, removeHiFreqX=0, convToPxl=1): """Create a zernike mode and get the centroids for this. Put these centroids into the PCG algorithm, and recreate the phase, and then compare with the original input phase defaultOptions are: diagonaliseinvChatReordered:1#should we diagonlise C-1, or use whole MX? diagonaliseA:0#should we diagonalise A or use the whole MX. useChatFromDiagonalisedA:1#should we compute invChat using a diagonalised chat or not? zernlist can be a dict of zernikes eg {3:1} would be focus, amplitude 1... or it can be the phase, or it can be none (in which case a phasescreen is created). This now seems to be working fairly well, iterates to an exact solution after about 10 iters, and 4-5 should be sufficient for a good solution. """ options = { "diagonaliseinvChatReordered": diagonaliseinvChatReordered, "diagonaliseA": diagonaliseA, "useChatFromDiagonalisedA": useChatFromDiagonalisedA, "oversampleFFT": oversampleFFT, "2dfft": fft2d, "oversampleAndBinFFTofr": oversampleAndBinFFTofr, "removeHiFreqZ": removeHiFreqZ, "removeHiFreqP": removeHiFreqP, "removeHiFreqX": removeHiFreqX } gist.window(0) gist.palette("gray.gp") pupfn = util.tel.Pupil(nact - 1, (nact - 1) / 2., 0).fn actfn = util.tel.Pupil(nact, nact / 2., 0).fn noiseCov = None if type(cents) == type(None): if type(zernlist) in [type(1), type(1.)]: zernlist = {zernlist: 1.} elif type(zernlist) == type([]): tmp = {} for i in zernlist: tmp[i] = 1. zernlist = tmp elif type(zernlist) == type(None): zernlist = science.infScrn.makeInitialScreen(dpix=(nact - 1) * 8, Dtel=4.2, L0=30., scrnXPxls=None, scrnYPxls=None, seed=None, tstep=0.05, globR0=0.2, strLayer=1., natype=numpy.float64, windDirection=0., vWind=10.)[:-1, 1:].copy() c, phase, avphase = getFocusCents(zernlist, nact=nact, readnoise=readnoise, usePoisson=usePoisson, sig=sig, plot=1, fullpupil=fullpupil) print phase.shape cents = c.cent if monteNoiseCovariance: noiseCov = c.computeNoiseCovariance(20, convertToRad=1) if convToPxl: #convert from radians to pixel values for the noises... radToPxlFactor = 1. / c.convFactor**2 else: radToPxlFactor = 1. Pcg = testfull(fromdisk=0, nact=nact, pupfn=pupfn, actfn=actfn, fullpmx=1, noiseCov=noiseCov, phaseCov=phaseCov, options=options, radToPxlFactor=radToPxlFactor) #agbhome Pcg.newCentroids(cents) Pcg.initialise() #now inverse A, multiply with b, to get the MVM reconstructed phase... invA = numpy.linalg.inv(Pcg.A) gist.fma() gist.pli(invA) raw_input("Displaying inverse of A... press return") gist.fma() gist.pli(phase) raw_input("The phase... press a key") recphase = quick.dot(invA, Pcg.b) print "Reconstructed phase min/max:", min(recphase.flat), max( recphase.flat) recphase.shape = (9, 9) gist.window(4) gist.palette("gray.gp") gist.fma() gist.pli(recphase) gist.palette("gray.gp") gist.window(0) chires = numpy.zeros((100, ), "d") #also compute what a traditional MVM with pokemx would give... #invpokemx=numpy.linalg.pinv(Pcg.pokemx)#same as generalised_inverse #pmphase=quick.dot(invpokemx,cents) print "Press return for next iteration or key+return to quit" #gist.fma() #gist.pli(numpy.reshape(pmphase,(nact,nact))) if type(avphase) != type(None): print "press a key" raw_input() gist.fma() gist.pli(avphase) actphase = phase2acts(avphase) actphase -= numpy.average(actphase.flat) #remove piston smallpupfn = util.tel.Pupil(nact, nact / 2. - 2, 0).fn raw_input("press return (min, max actphase is %g %g" % (min(actphase.flat), max(actphase.flat))) gist.fma() gist.pli(actphase) gist.window(1) gist.palette("gray.gp") gist.window(2) gist.palette("gray.gp") niter = 0 while len(raw_input()) == 0: niter += 1 gist.window(1) gist.fma() img = numpy.reshape(Pcg.x.real, (nact, nact)) gist.pli(img) gist.window(2) gist.fma() img = smallpupfn * img #gist.pli(numpy.where(img==0,min(img.flat),img)) gist.pli(numpy.reshape(Pcg.p, (nact, nact))) gist.window(3) gist.fma() fftimg = numpy.fft.fft2(numpy.reshape(Pcg.x, (nact, nact))) gist.pli(fftimg.real) Pcg.nextIter() chirespos = niter - 1 if chirespos > 99: chirespos = 99 chires[chirespos] = chi2(Pcg.x, recphase, scale=0) #changed from actphase Pcg.alphaHist[chirespos] = Pcg.alpha Pcg.betaHist[chirespos] = Pcg.beta Pcg.tolerance[chirespos] = max(numpy.fabs(Pcg.xprev - Pcg.x)) print niter, Pcg.tolerance[chirespos], chires[chirespos], min( Pcg.x.real), max(Pcg.x.real), min(Pcg.p), max( Pcg.p), Pcg.alphaHist[chirespos], Pcg.betaHist[chirespos] print "Press return for next iteration or key+return to quit" gist.fma() gist.plg(chires[:chirespos]) gist.window(2) gist.fma() gist.plg(Pcg.tolerance[:niter]) gist.window(0) return Pcg, actphase, phase, recphase, c
def twoplane(DATA,slice1,slice2,dx=[1,1,1],cmin=None,cmax=None,xb=None,xe=None, xlab="",ylab="",zlab="",clab="",titl="", totalheight=0.5,space=0.02, medfilt=5, font='helvetica',fontsize=16,color='black',lcolor='white', fcolor='black', cb=1, line=1, palette=None): """ Visualize a 3d volume as a two connected slices. The slices are given in the 2-tuple slice1 and slice2. These give the dimension and corresponding slice numbers to plot. The unchosen slice is the common dimension in the images. twoplane(img3d,(0,12),(2,60)) plots two images with a common "x"-axis as the first dimension. The lower plot is img3d[12,:,:] with a line through row 60 corresponding to the slice transpose(img3d[:,:,60]) plotted above this first plot. """ if xb is None: xb = [0,0,0] if xe is None: xe = DATA.shape # get two image slices # make special style file so that pixels are square getdx = array([1,1,1]) imgsl1 = [slice(None,None),slice(None,None),slice(None,None)] imgsl1[slice1[0]] = slice1[1] img1 = DATA[imgsl1] getdx1 = getdx.__copy__() getdx1[slice1[0]] = 0 dx1 = compress(getdx1,dx,axis=-1) xb1 = compress(getdx1,xb,axis=-1) xe1 = compress(getdx1,xe,axis=-1) imgsl2 = [slice(None,None),slice(None,None),slice(None,None)] imgsl2[slice2[0]] = slice2[1] img2 = DATA[imgsl2] getdx2 = getdx.__copy__() getdx2[slice2[0]] = 0 dx2 = compress(getdx2,dx,axis=-1) xb2 = compress(getdx2,xb,axis=-1) xe2 = compress(getdx2,xe,axis=-1) if (slice1[0] == slice2[0]): raise ValueError, "Same slice dimension.." for k in range(3): if k not in [slice1[0],slice2[0]]: samedim = k break if samedim == 2: pass elif samedim == 1: if samedim > slice1[0]: img1 = transpose(img1) dx1 = dx1[::-1] xb1 = xb1[::-1] xe1 = xe1[::-1] if samedim > slice2[0]: img2 = transpose(img2) dx2 = dx2[::-1] xb2 = xb2[::-1] xe2 = xe2[::-1] else: img1 = transpose(img1) dx1 = dx1[::-1] xb1 = xb1[::-1] xe1 = xe1[::-1] img2 = transpose(img2) dx2 = dx2[::-1] xb2 = xb2[::-1] xe2 = xe2[::-1] assert(img1.shape[1] == img2.shape[1]) units = totalheight - space totaldist = img1.shape[0]*dx1[0] + img2.shape[0]*dx2[0] convfactor = units / float(totaldist) height1 = img1.shape[0]*dx1[0] * convfactor xwidth = img1.shape[1]*dx1[1]*convfactor if xwidth > 0.6: rescale = 0.6 / xwidth xwidth = rescale * xwidth height1 = rescale * height1 totalheight = totalheight * rescale print xwidth, height1 else: print xwidth ystart = 0.5 - totalheight / 2 ypos1 = [ystart, ystart+height1] ypos2 = [ystart+height1+space,ystart+totalheight] xpos = [0.395-xwidth/2.0, 0.395+xwidth/2.0] systems = [] system = write_style.getsys(hticpos='', vticpos='left') system['viewport'] = [xpos[0],xpos[1],ypos2[0],ypos2[1]] if fcolor not in ['black',None]: _add_color(system, _colornum[color]) systems.append(system) system = write_style.getsys(hticpos='below', vticpos='left') system['viewport'] = [xpos[0],xpos[1],ypos1[0],ypos1[1]] if fcolor not in ['black',None]: _add_color(system, _colornum[color]) systems.append(system) the_style = os.path.join(_user_path,"two-plane.gs") write_style.writestyle(the_style,systems) gist.window(style=the_style) _current_style = the_style change_palette(palette) gist.plsys(1) if medfilt > 1: img1 = signal.medfilt(img1,[medfilt,medfilt]) img2 = signal.medfilt(img2,[medfilt,medfilt]) if cmax is None: cmax = max(max(ravel(img1)),max(ravel(img2))) if cmin is None: cmin = min(min(ravel(img1)),min(ravel(img2))) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(img2,cmin=cmin,cmax=cmax) gist.pli(byteimage,xb2[1],xb2[0],xe2[1],xe2[0]) ylabel(zlab,color=color) if titl != "": title(titl,color=color) if line: xstart = xb2[1] xstop = xe2[1] yval = slice1[1]*(xe2[0] - xb2[0])/(img2.shape[0]) + xb2[0] gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white') gist.plsys(2) ylabel(ylab,color=color) xlabel(xlab,color=color) byteimage = gist.bytscl(img1,cmin=cmin,cmax=cmax) gist.pli(byteimage,xb1[1],xb1[0],xe1[1],xe1[0]) if line: xstart = xb1[1] xstop = xe1[1] yval = slice2[1]*(xe1[0] - xb1[0])/(img1.shape[0]) + xb1[0] gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white') if cb: colorbar.color_bar(cmin,cmax,ncol=240,zlabel=clab,font=font,fontsize=fontsize,color=color,ymin=ystart,ymax=ystart+totalheight,xmin0=xpos[1]+0.02,xmax0=xpos[1]+0.04)
def twoplane(DATA,slice1,slice2,dx=[1,1,1],cmin=None,cmax=None,xb=None,xe=None, xlab="",ylab="",zlab="",clab="",titl="", totalheight=0.5,space=0.02, medfilt=5, font='helvetica',fontsize=16,color='black',lcolor='white', fcolor='black', cb=1, line=1, palette=None): """ Visualize a 3d volume as a two connected slices. The slices are given in the 2-tuple slice1 and slice2. These give the dimension and corresponding slice numbers to plot. The unchosen slice is the common dimension in the images. twoplane(img3d,(0,12),(2,60)) plots two images with a common "x"-axis as the first dimension. The lower plot is img3d[12,:,:] with a line through row 60 corresponding to the slice transpose(img3d[:,:,60]) plotted above this first plot. """ if xb is None: xb = [0,0,0] if xe is None: xe = DATA.shape # get two image slices # make special style file so that pixels are square getdx = array([1,1,1]) imgsl1 = [slice(None,None),slice(None,None),slice(None,None)] imgsl1[slice1[0]] = slice1[1] img1 = DATA[imgsl1] getdx1 = getdx.__copy__() getdx1[slice1[0]] = 0 dx1 = compress(getdx1,dx,axis=-1) xb1 = compress(getdx1,xb,axis=-1) xe1 = compress(getdx1,xe,axis=-1) imgsl2 = [slice(None,None),slice(None,None),slice(None,None)] imgsl2[slice2[0]] = slice2[1] img2 = DATA[imgsl2] getdx2 = getdx.__copy__() getdx2[slice2[0]] = 0 dx2 = compress(getdx2,dx,axis=-1) xb2 = compress(getdx2,xb,axis=-1) xe2 = compress(getdx2,xe,axis=-1) if (slice1[0] == slice2[0]): raise ValueError, "Same slice dimension.." for k in range(3): if k not in [slice1[0],slice2[0]]: samedim = k break if samedim == 2: pass elif samedim == 1: if samedim > slice1[0]: img1 = transpose(img1) dx1 = dx1[::-1] xb1 = xb1[::-1] xe1 = xe1[::-1] if samedim > slice2[0]: img2 = transpose(img2) dx2 = dx2[::-1] xb2 = xb2[::-1] xe2 = xe2[::-1] else: img1 = transpose(img1) dx1 = dx1[::-1] xb1 = xb1[::-1] xe1 = xe1[::-1] img2 = transpose(img2) dx2 = dx2[::-1] xb2 = xb2[::-1] xe2 = xe2[::-1] assert(img1.shape[1] == img2.shape[1]) units = totalheight - space totaldist = img1.shape[0]*dx1[0] + img2.shape[0]*dx2[0] convfactor = units / float(totaldist) height1 = img1.shape[0]*dx1[0] * convfactor xwidth = img1.shape[1]*dx1[1]*convfactor if xwidth > 0.6: rescale = 0.6 / xwidth xwidth = rescale * xwidth height1 = rescale * height1 totalheight = totalheight * rescale print xwidth, height1 else: print xwidth ystart = 0.5 - totalheight / 2 ypos1 = [ystart, ystart+height1] ypos2 = [ystart+height1+space,ystart+totalheight] xpos = [0.395-xwidth/2.0, 0.395+xwidth/2.0] systems = [] system = write_style.getsys(hticpos='', vticpos='left') system['viewport'] = [xpos[0],xpos[1],ypos2[0],ypos2[1]] if fcolor not in ['black',None]: _add_color(system, _colornum[color]) systems.append(system) system = write_style.getsys(hticpos='below', vticpos='left') system['viewport'] = [xpos[0],xpos[1],ypos1[0],ypos1[1]] if fcolor not in ['black',None]: _add_color(system, _colornum[color]) systems.append(system) the_style = os.path.join(_user_path,"two-plane.gs") write_style.writestyle(the_style,systems) gist.window(style=the_style) _current_style = the_style change_palette(palette) gist.plsys(1) if medfilt > 1: import scipy.signal img1 = scipy.signal.medfilt(img1,[medfilt,medfilt]) img2 = scipy.signal.medfilt(img2,[medfilt,medfilt]) if cmax is None: cmax = max(max(ravel(img1)),max(ravel(img2))) if cmin is None: cmin = min(min(ravel(img1)),min(ravel(img2))) cmax = float(cmax) cmin = float(cmin) byteimage = gist.bytscl(img2,cmin=cmin,cmax=cmax) gist.pli(byteimage,xb2[1],xb2[0],xe2[1],xe2[0]) ylabel(zlab,color=color) if titl != "": title(titl,color=color) if line: xstart = xb2[1] xstop = xe2[1] yval = slice1[1]*(xe2[0] - xb2[0])/(img2.shape[0]) + xb2[0] gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white') gist.plsys(2) ylabel(ylab,color=color) xlabel(xlab,color=color) byteimage = gist.bytscl(img1,cmin=cmin,cmax=cmax) gist.pli(byteimage,xb1[1],xb1[0],xe1[1],xe1[0]) if line: xstart = xb1[1] xstop = xe1[1] yval = slice2[1]*(xe1[0] - xb1[0])/(img1.shape[0]) + xb1[0] gist.pldj([xstart],[yval],[xstop],[yval],type='dash',width=2,color='white') if cb: colorbar.color_bar(cmin,cmax,ncol=240,zlabel=clab,font=font,fontsize=fontsize,color=color,ymin=ystart,ymax=ystart+totalheight,xmin0=xpos[1]+0.02,xmax0=xpos[1]+0.04)