def _plotArrays(self): import gist for array in self._getArrays(): gist.plg(*array) gist.logxy(self.xlog, self.ylog)
def bode(w,H,win=0,frame=0,lcolor='blue',color='black',tcolor='black',freq='rad'): """Plot a bode plot of the transfer function H as a function of w. """ if freq == 'Hz': w = w /2.0 / pi subplot(2,1,win,hsep=120,frame=frame,color=color) gist.plsys(1) gist.plg(20*numpy.log10(abs(H)),w,type='solid',color=lcolor,marks=0) gist.logxy(1,0) gist.gridxy(1,1) if freq == 'Hz': xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005) else: xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005) ylabel('Magnitude (dB)',color=tcolor,deltax=-0.005) title("Bode Plot",color=tcolor) gist.plsys(2) gist.plg(180/pi*numpy.unwrap(MLab.angle(H)),w,type='solid',color=lcolor,marks=0) gist.logxy(1,0) gist.gridxy(1,1) if freq == 'Hz': xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005) else: xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005) ylabel('Phase (deg.)',color=tcolor,deltax=-0.005)
def bode(w,H,win=0,frame=0,lcolor='blue',color='black',tcolor='black',freq='rad'): """Plot a bode plot of the transfer function H as a function of w. """ if freq == 'Hz': w = w /2.0 / pi subplot(2,1,win,hsep=120,frame=frame,color=color) gist.plsys(1) gist.plg(20*numpy.log10(abs(H)),w,type='solid',color=lcolor,marks=0) gist.logxy(1,0) gist.gridxy(1,1) if freq == 'Hz': xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005) else: xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005) ylabel('Magnitude (dB)',color=tcolor,deltax=-0.005) title("Bode Plot",color=tcolor) gist.plsys(2) gist.plg(180/pi*numpy.unwrap(numpy.angle(H)),w,type='solid',color=lcolor,marks=0) gist.logxy(1,0) gist.gridxy(1,1) if freq == 'Hz': xlabel('Frequency (Hz)',color=tcolor,deltay=-0.005) else: xlabel('Frequency (rad/s)',color=tcolor,deltay=-0.005) ylabel('Phase (deg.)',color=tcolor,deltax=-0.005)
def makeleg(leg,pos,lenx,dd,theight=12): # Place legend x0,y0 = pos dx,dy = dd for k in range(len(leg['txt'])): gist.plg([y0+k*dy]*2,[x0,x0+lenx],type=leg['sym'][k][1],marks=0) if leg['sym'][k][0] is not None: gist.plg([y0+k*dy]*2,[x0,x0+lenx],type='none',marks=1,marker=leg['sym'][k][0]) if leg['txt'][k] != "": gist.plt(leg['txt'][k],x0+lenx+dx,y0+k*dy,height=theight,tosys=1,justify='LH') return
def matplot(x,y=None,axis=-1): if y is None: # no axis data y = x x = numpy.arange(0,y.shape[axis]) x,y = numpy.asarray(x), numpy.asarray(y) assert(len(y.shape)==2) assert(len(x)==y.shape[axis]) otheraxis = (1+axis) % 2 sliceobj = [slice(None)]*2 if not _hold and gist.plsys() < 2: gist.fma() clear_global_linetype() for k in range(y.shape[otheraxis]): thiscolor = _colors[_corder[k % len(_corder)]] sliceobj[otheraxis] = k ysl = where(numpy.isfinite(y[sliceobj]),y[sliceobj],0) gist.plg(ysl,x,type='solid',color=thiscolor,marks=0) append_global_linetype(_rcolors[thiscolor]+'-')
def matplot(x,y=None,axis=-1): if y is None: # no axis data y = x x = Numeric.arange(0,y.shape[axis]) x,y = Numeric.asarray(x), Numeric.asarray(y) assert(len(y.shape)==2) assert(len(x)==y.shape[axis]) otheraxis = (1+axis) % 2 sliceobj = [slice(None)]*2 if not _hold and gist.plsys() < 2: gist.fma() clear_global_linetype() for k in range(y.shape[otheraxis]): thiscolor = _colors[_corder[k % len(_corder)]] sliceobj[otheraxis] = k ysl = where(numpy.isfinite(y[sliceobj]),y[sliceobj],0) gist.plg(ysl,x,type='solid',color=thiscolor,marks=0) append_global_linetype(_rcolors[thiscolor]+'-')
def errorbars(x,y,err,ptcolor='r',linecolor='B',pttype='o',linetype='-',fac=0.25): """Draw connected points with errorbars. Description: Plot connected points with errorbars. Inputs: x, y -- The points to plot. err -- The error in the y values. ptcolor -- The color for the points. linecolor -- The color of the connecting lines and error bars. pttype -- The type of point ('o', 'x', '+', '.', 'x', '*') linetype -- The type of line ('-', '|', ':', '-.', '-:') fac -- Adjusts how long the horizontal lines are which make the top and bottom of the error bars. """ # create line arrays yb = y - err ye = y + err try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 if _hold or override: pass else: gist.fma() y = where(numpy.isfinite(y),y,0) gist.plg(y,x,color=_colors[ptcolor],marker=_markers[pttype],type='none') gist.pldj(x,yb,x,ye,color=_colors[linecolor],type=_types[linetype]) viewp = gist.viewport() plotlims = gist.limits() conv_factorx = (viewp[1] - viewp[0]) / (plotlims[1]-plotlims[0]) conv_factory = (viewp[3] - viewp[2]) / (plotlims[3]-plotlims[2]) width = fac*(x[1]-x[0]) x0 = x-width/2.0 x1 = x+width/2.0 gist.pldj(x0,ye,x1,ye,color=_colors[linecolor],type=_types[linetype]) gist.pldj(x0,yb,x1,yb,color=_colors[linecolor],type=_types[linetype]) return
def stem(m, y, linetype='b-', mtype='mo', shift=0.013): y0 = Numeric.zeros(len(y),y.dtype.char) y1 = y x0 = m x1 = m try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 if not (_hold or override): gist.fma() thetype,thecolor,themarker,tomark = _parse_type_arg(linetype,0) lcolor = thecolor gist.pldj(x0, y0, x1, y1, color=thecolor, type=thetype) thetype,thecolor,themarker,tomark = _parse_type_arg(mtype,0) if themarker not in ['o','x','.','*']: themarker = 'o' y = where(numpy.isfinite(y),y,0) gist.plg(y,m,color=thecolor,marker=themarker,type='none') gist.plg(Numeric.zeros(len(m)),m,color=lcolor,marks=0) gist.limits() lims = gist.limits() newlims = [None]*4 vp = gist.viewport() factor1 = vp[1] - vp[0] factor2 = vp[3] - vp[2] cfactx = factor1 / (lims[1] - lims[0]) cfacty = factor2 / (lims[3] - lims[2]) d1 = shift / cfactx d2 = shift / cfacty newlims[0] = lims[0] - d1 newlims[1] = lims[1] + d1 newlims[2] = lims[2] - d2 newlims[3] = lims[3] + d2 gist.limits(*newlims) return
def stem(m, y, linetype='b-', mtype='mo', shift=0.013): y0 = numpy.zeros(len(y),y.dtype.char) y1 = y x0 = m x1 = m try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 if not (_hold or override): gist.fma() thetype,thecolor,themarker,tomark = _parse_type_arg(linetype,0) lcolor = thecolor gist.pldj(x0, y0, x1, y1, color=thecolor, type=thetype) thetype,thecolor,themarker,tomark = _parse_type_arg(mtype,0) if themarker not in ['o','x','.','*']: themarker = 'o' y = where(numpy.isfinite(y),y,0) gist.plg(y,m,color=thecolor,marker=themarker,type='none') gist.plg(numpy.zeros(len(m)),m,color=lcolor,marks=0) gist.limits() lims = gist.limits() newlims = [None]*4 vp = gist.viewport() factor1 = vp[1] - vp[0] factor2 = vp[3] - vp[2] cfactx = factor1 / (lims[1] - lims[0]) cfacty = factor2 / (lims[3] - lims[2]) d1 = shift / cfactx d2 = shift / cfacty newlims[0] = lims[0] - d1 newlims[1] = lims[1] + d1 newlims[2] = lims[2] - d2 newlims[3] = lims[3] + d2 gist.limits(*newlims) return
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 onGist ( self, event ): # print "... Gist button pressed" self.isGistWindowOn = 1 gist.plg([0,1])
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 try: msize = float(keywds['msize']) except KeyError: msize=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys >= 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = _minsqueeze(x) x = numpy.arange(0,len(y)) if numpy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(numpy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if numpy.iscomplexobj(x) or numpy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = numpy.real(x) y = numpy.real(y) y = where(numpy.isfinite(y),y,0) y = _minsqueeze(y) x = _minsqueeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,msize=msize,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
def plot(x,*args,**keywds): """Plot curves. Description: Plot one or more curves on the same graph. Inputs: There can be a variable number of inputs which consist of pairs or triples. The second variable is plotted against the first using the linetype specified by the optional third variable in the triple. If only two plots are being compared, the x-axis does not have to be repeated. """ try: override = 1 savesys = gist.plsys(2) gist.plsys(savesys) except: override = 0 global _hold try: _hold=keywds['hold'] except KeyError: pass try: linewidth=float(keywds['width']) except KeyError: linewidth=1.0 try: msize = float(keywds['msize']) except KeyError: msize=1.0 if _hold or override: pass else: gist.fma() gist.animate(0) savesys = gist.plsys() winnum = gist.window() if winnum < 0: gist.window(0) if savesys >= 0: gist.plsys(savesys) nargs = len(args) if nargs == 0: y = _minsqueeze(x) x = Numeric.arange(0,len(y)) if numpy.iscomplexobj(y): print "Warning: complex data plotting real part." y = y.real y = where(numpy.isfinite(y),y,0) gist.plg(y,x,type='solid',color='blue',marks=0,width=linewidth) return y = args[0] argpos = 1 nowplotting = 0 clear_global_linetype() while 1: try: thearg = args[argpos] except IndexError: thearg = 0 thetype,thecolor,themarker,tomark = _parse_type_arg(thearg,nowplotting) if themarker == 'Z': # args[argpos] was data or non-existent. pass append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) else: # args[argpos] was a string argpos = argpos + 1 if tomark: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]+_rmarkers[themarker]) else: append_global_linetype(_rtypes[thetype]+_rcolors[thecolor]) if numpy.iscomplexobj(x) or numpy.iscomplexobj(y): print "Warning: complex data provided, using only real part." x = numpy.real(x) y = numpy.real(y) y = where(numpy.isfinite(y),y,0) y = _minsqueeze(y) x = _minsqueeze(x) gist.plg(y,x,type=thetype,color=thecolor,marker=themarker,marks=tomark,msize=msize,width=linewidth) nowplotting = nowplotting + 1 ## Argpos is pointing to the next potential triple of data. ## Now one of four things can happen: ## ## 1: argpos points to data, argpos+1 is a string ## 2: argpos points to data, end ## 3: argpos points to data, argpos+1 is data ## 4: argpos points to data, argpos+1 is data, argpos+2 is a string if argpos >= nargs: break # no more data if argpos == nargs-1: # this is a single data value. x = x y = args[argpos] argpos = argpos+1 elif type(args[argpos+1]) is types.StringType: x = x y = args[argpos] argpos = argpos+1 else: # 3 x = args[argpos] y = args[argpos+1] argpos = argpos+2 return
import gist gist.pldefault(marks=0) n = 5000 t = 0.001 v = numpy.empty(n) for i in range(n): a = time.time() time.sleep(t) v[i] = time.time() - a print v.min(), v.max(), v.std() gist.plg(v, color="red") tt = long(1e9 * t) v = numpy.empty(n) rt.sched_setscheduler() time.sleep(1) for i in range(n): a = time.time() rt.clock_nanosleep(tt) v[i] = time.time() - a print v.min(), v.max(), v.std() gist.plg(v, color="blue")
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