Example #1
0
def plot_header(fname, ff, iod_line):
    # ppgplot arrays
    heat_l = np.array([0.0, 0.2, 0.4, 0.6, 1.0])
    heat_r = np.array([0.0, 0.5, 1.0, 1.0, 1.0])
    heat_g = np.array([0.0, 0.0, 0.5, 1.0, 1.0])
    heat_b = np.array([0.0, 0.0, 0.0, 0.3, 1.0])

    # Plot
    ppg.pgopen(fname)
    ppg.pgpap(0.0, 1.0)
    ppg.pgsvp(0.1, 0.95, 0.1, 0.8)

    ppg.pgsch(0.8)
    ppg.pgmtxt("T", 6.0, 0.0, 0.0,
               "UT Date: %.23s  COSPAR ID: %04d" % (ff.nfd, ff.site_id))
    if is_calibrated(ff):
        ppg.pgsci(1)
    else:
        ppg.pgsci(2)
    ppg.pgmtxt(
        "T", 4.8, 0.0, 0.0, "R.A.: %10.5f (%4.1f'') Decl.: %10.5f (%4.1f'')" %
        (ff.crval[0], 3600.0 * ff.crres[0], ff.crval[1], 3600.0 * ff.crres[1]))
    ppg.pgsci(1)
    ppg.pgmtxt("T", 3.6, 0.0, 0.0, ("FoV: %.2f\\(2218)x%.2f\\(2218) "
                                    "Scale: %.2f''x%.2f'' pix\\u-1\\d") %
               (ff.wx, ff.wy, 3600.0 * ff.sx, 3600.0 * ff.sy))
    ppg.pgmtxt(
        "T", 2.4, 0.0, 0.0, "Stat: %5.1f+-%.1f (%.1f-%.1f)" %
        (np.mean(ff.zmax), np.std(ff.zmax), ff.zmaxmin, ff.zmaxmax))
    ppg.pgmtxt("T", 0.3, 0.0, 0.0, iod_line)

    ppg.pgsch(1.0)
    ppg.pgwnad(0.0, ff.nx, 0.0, ff.ny)
    ppg.pglab("x (pix)", "y (pix)", " ")
    ppg.pgctab(heat_l, heat_r, heat_g, heat_b, 5, 1.0, 0.5)
Example #2
0
 def ok():
     if not with_pg:
         return True
     pg.pgopen('/null')
     self.ccd.plot(5, 95)
     pg.pgclos()
     return True
Example #3
0
 def ok():
     if not with_pg:
         return True
     pg.pgopen('/null')
     self.ccd.plot(5,95)
     pg.pgclos()
     return True
Example #4
0
def createPGplotWindow(handle, width, height):
    """ Set up the PGPLOT windows """

    newPlot = {}
    newPlot["pgplotHandle"] = ppgplot.pgopen("/xs")
    ppgplot.pgpap(2, 1)
    ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
    ppgplot.pgswin(0, width, 0, height)

    return newPlot
Example #5
0
def createPGplotWindow(handle, width, height):
    """ Set up the PGPLOT windows """

    newPlot = {}
    newPlot['pgplotHandle'] = ppgplot.pgopen('/xs')
    ppgplot.pgpap(2, 1)
    ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
    ppgplot.pgswin(0, width, 0, height)

    return newPlot
Example #6
0
def drawMask(mask):
    print ("Drawing the mask.")
    if "pgplotHandle" not in maskPlot.keys():
        maskPlot["pgplotHandle"] = ppgplot.pgopen("/xs")
        maskPlot["pgPlotTransform"] = [0, 1, 0, 0, 0, 1]
    else:
        ppgplot.pgslct(maskPlot["pgplotHandle"])
    ppgplot.pgpap(paperSize, aspectRatio)
    ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
    ppgplot.pgswin(0, width, 0, height)
    ppgplot.pggray(mask, 0, width - 1, 0, height - 1, 0, 255, maskPlot["pgPlotTransform"])
    ppgplot.pgslct(imagePlot["pgplotHandle"])
Example #7
0
def drawMask(mask):
    print("Drawing the mask.")
    if 'pgplotHandle' not in maskPlot.keys():
        maskPlot['pgplotHandle'] = ppgplot.pgopen('/xs')
        maskPlot['pgPlotTransform'] = [0, 1, 0, 0, 0, 1]
    else:
        ppgplot.pgslct(maskPlot['pgplotHandle'])
    ppgplot.pgpap(paperSize, aspectRatio)
    ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
    ppgplot.pgswin(0, width, 0, height)
    ppgplot.pggray(mask, 0, width - 1, 0, height - 1, 0, 255,
                   maskPlot['pgPlotTransform'])
    ppgplot.pgslct(imagePlot['pgplotHandle'])
Example #8
0
def openDev(type='/XWINDOW'):
    """
  DES: open a device, return the device id
  INP: (string) type = pgplot device type 
  """

    global CurrentDev, DevList

    if isinstance(type, str):
        CurrentDev = ppgplot.pgopen(type)
        ppgplot.pgask(0)
        DevList.append(CurrentDev)
    else:
        __MessHand.setMess(0, "openDev: string argument required ")
    __queryDev()
def pgplot(slot, plotterHandle):
	print "We are about to plot: %s"%(slot)
	
	lightcurveView = ppgplot.pgopen('/xs')
	
	xValues = slot.photometry.times
	xValues = numpy.arange(0, len(xValues))
	yValues = slot.getColumn("Counts")
	
	ppgplot.pgenv(min(xValues), max(xValues), min(yValues), max(yValues), 0, 0)
	ppgplot.pgask(False)
	
	ppgplot.pgsci(2)	
	ppgplot.pgpt(xValues, yValues, 1)

	ppgplot.pgclos()
	return
	
Example #10
0
    def startPlotter(self):
        if self.plotDeviceIsOpened:
            raise ValueError("You already started a plot!")

        devId = pgplot.pgopen(self.deviceName)
        self.plotDeviceIsOpened = True

        if not self.widthInches is None:
            pgplot.pgpap(self.widthInches, self.yOnXRatio)

        # For devices /xs, /xw, /png etc, should make the paper white and the ink black. Only for /ps does pgplot default to that.
        #
        deviceWithoutFile = self.deviceName.split('/')[-1]
        if deviceWithoutFile == 'xs' or deviceWithoutFile == 'xw' or deviceWithoutFile == 'png':
            pgplot.pgscr(0, 1.0, 1.0, 1.0)
            pgplot.pgscr(1, 0.0, 0.0, 0.0)

        pgplot.pgsvp(self._vXLo, self._vXHi, self._vYLo, self._vYHi)

        if self.fixAspect:
            pgplot.pgwnad(self.worldXLo, self.worldXHi, self.worldYLo,
                          self.worldYHi)
        else:
            pgplot.pgswin(self.worldXLo, self.worldXHi, self.worldYLo,
                          self.worldYHi)
        pgplot.pgsfs(2)

        pgplot.pgslw(1)
        pgplot.pgsch(self._charHeight)

        self._setColourRepresentations()

        # Set up things so calling pgplot.pggray() won't overwrite the CR of any of the colours in self.colours.
        #
        (minCI, maxCI) = pgplot.pgqcir()
        if minCI <= self.maxCI:
            pgplot.pgscir(self.maxCI + 1, maxCI)

        (xLoPixels, xHiPixels, yLoPixels, yHiPixels) = pgplot.pgqvsz(3)
        (xLoInches, xHiInches, yLoInches, yHiInches) = pgplot.pgqvsz(1)
        self.xPixelWorld = (xHiInches - xLoInches) / (xHiPixels - xLoPixels)
        self.yPixelWorld = (yHiInches - yLoInches) / (yHiPixels - yLoPixels)
Example #11
0
			if r.has_mask: print "Mask found"
			spectrum = spectrumClasses.spectrumObject()
			npoints = spectrum.setData(wavelengths, flux)
			targetName = spectrum.parseHeaderInfo(head)
			print "Parsed headers of", targetName
			print r.oneLine()
			if fileIndex == 0:
				spectra.append(spectrum)
			else:
				spectra[index].appendNewData(spectrum)
				
	numSpectra = len(spectra)

	print "%d spectra have been loaded."%numSpectra

	mainPGPlotWindow = ppgplot.pgopen('/xs')	
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgask(False)
	ppgplot.pglab("wavelength", "flux", "spectrum")
	phases = []
	rvs = []
	wvshifts = []
	wvshiftErrors = []
	previousWavelengthFit = 8173.0
	for spectrum in spectra:
		spectrum.trimWavelengthRange(8000, 8400)
		lowerWavelength = min(spectrum.wavelengths)
		upperWavelength = max(spectrum.wavelengths)
		lowerFlux = min(spectrum.flux)
		upperFlux = max(spectrum.flux)
		ppgplot.pgsci(1)
Example #12
0
#/usr/bin/env python
#
#  pgex1: freely taken after PGDEMO1.F
#
import ppgplot, Numeric
import sys

# create an array 
xs=Numeric.array([1.,2.,3.,4.,5.])
ys=Numeric.array([1.,4.,9.,16.,25.])

# creat another array
yr = 0.1*Numeric.array(range(0,60))
xr = yr*yr


# pgplotting
if len(sys.argv) > 1: # if we got an argument use the argument as devicename
	ppgplot.pgopen(sys.argv[1])
else:
	ppgplot.pgopen('?')
ppgplot.pgenv(0.,10.,0.,20.,0,1)
ppgplot.pglab('(x)', '(y)', 'PGPLOT Example 1:  y = x\u2')
ppgplot.pgpt(xs,ys,9)
ppgplot.pgline(xr,yr)
ppgplot.pgclos()
Example #13
0
    def plot(self, vlo=2., vhi=98., nc=-1, method='p', mpl=False, cmap=CMDEF, \
                 close=True, x1=None, x2=None, y1=None, y2=None, sepmin=1.):
        """
        Plots an MCCD using pgplot or matplotlib if preferred.

        :Parameters:
         vlo : float
            number specifying the lowest level to plot (default as a percentile)
         vhi : float
            number specifying the lowest level to plot (default as a percentile)
         nc : int
            CCD number (starting from 0, -1 for all)
         method : string
            how vlo and vhi are to be interpreted. 'p' = percentile, 'a' = automatic (min to max,
            vlo and vhi are irrelevant), 'd' = direct, i.e. just take the values given.
         mpl : bool
            True to prefer matplotlib over pgplot (which may not even be an option)
         cmap : matplotlib.cm.binary
            colour map if using matplotlib
         close : bool
            close (pgplot) or 'show' (matplotlib) the plot at the end (or not, to allow 
            you to plot something else, use a cursor etc). In the case of pgplot, this also
            implies opening the plot at the start, i.e. a self-contained quick plot.
         x1 : float
            left-hand plot limit. Defaults to 0.5
         x2 : float
             right-hand plot limit. Defaults to nxmax+0.5
         y1 : float
            lower plot limit. Defaults to 0.5
         y2 : float
             upper plot limit. Defaults to nymax+0.5
         sepmin : float
             minimum separation between intensity limits (> 0 to stop PGPLOT complaining)

        :Returns:
         range(s) : tuple or list
            the plot range(s) used either as a single 2-element tuple, or
            a list of them, one per CCD plotted.
        """

        if nc == -1:
            nc1 = 0
            nc2 = len(self)
        else:
            nc1 = nc
            nc2 = nc + 1

        if not mpl:
            if close: pg.pgopen('/xs')
            if nc2 - nc1 > 1: pg.pgsubp(nc2 - nc1, 1)

        prange = []
        for nc, ccd in enumerate(self._data[nc1:nc2]):

            # Determine intensity range to display
            if method == 'p':
                vmin, vmax = ccd.centile((vlo, vhi))
            elif method == 'a':
                vmin, vmax = ccd.min(), ccd.max()
            elif method == 'd':
                vmin, vmax = vlo, vhi
            else:
                raise UltracamError(
                    'MCCD.plot: method must be one of p, a or d.')

            if vmin == vmax:
                vmin -= sepmin / 2.
                vmax += sepmin / 2.
            prange.append((vmin, vmax))

            # start
            nxmax, nymax = ccd.nxmax, ccd.nymax
            x1 = 0.5 if x1 is None else x1
            x2 = nxmax + 0.5 if x2 is None else x2
            y1 = 0.5 if y1 is None else y1
            y2 = nymax + 0.5 if y2 is None else y2

            if mpl:
                if nc2 - nc1 > 1:
                    plt.subplot(1, nc2 - nc1, nc + 1)
                plt.axis('equal')
            else:
                if nc2 - nc1 > 1: pg.pgpanl(nc - nc1 + 1, 1)
                pg.pgwnad(x1, x2, y1, y2)

            # plot CCD
            ccd.plot(vmin, vmax, mpl, cmap)

            # per-frame finishing-off
            if mpl:
                plt.xlim(x1, x2)
                plt.ylim(y1, y2)
            else:
                pg.pgbox('bcnst', 0, 0, 'bcnst', 0, 0)
                pg.pglab('X', 'Y', '')

        if close:
            if mpl:
                plt.show()
            else:
                pg.pgclos()

        # return intensity range(s) used
        if len(prange) == 1:
            return prange[0]
        else:
            return tuple(prange)
def main():
    parser = OptionParser(usage)
    parser.add_option("-x", "--xwin", action="store_true", dest="xwin",
                      default=False, help="Don't make a postscript plot, just use an X-window")
    parser.add_option("-p", "--noplot", action="store_false", dest="makeplot",
                      default=True, help="Look for pulses but do not generate a plot")
    parser.add_option("-m", "--maxwidth", type="float", dest="maxwidth", default=0.0,
                      help="Set the max downsampling in sec (see below for default)")
    parser.add_option("-t", "--threshold", type="float", dest="threshold", default=5.0,
                      help="Set a different threshold SNR (default=5.0)")
    parser.add_option("-s", "--start", type="float", dest="T_start", default=0.0,
                      help="Only plot events occuring after this time (s)")
    parser.add_option("-e", "--end", type="float", dest="T_end", default=1e9,
                      help="Only plot events occuring before this time (s)")
    parser.add_option("-g", "--glob", type="string", dest="globexp", default=None,
                      help="Process the files from this glob expression")
    parser.add_option("-f", "--fast", action="store_true", dest="fast",
                      default=False, help="Use a faster method of de-trending (2x speedup)")
    parser.add_option("-b", "--nobadblocks", action="store_false", dest="badblocks",
                      default=True, help="Don't check for bad-blocks (may save strong pulses)")
    parser.add_option("-d", "--detrendlen", type="int", dest="detrendfact", default=1,
                      help="Chunksize for detrending (pow-of-2 in 1000s)")
    (opts, args) = parser.parse_args()
    if len(args)==0:
        if opts.globexp==None:
            print full_usage
            sys.exit(0)
        else:
            args = []
            for globexp in opts.globexp.split():
                args += glob.glob(globexp)
    useffts = True
    dosearch = True
    if opts.xwin:
        pgplot_device = "/XWIN"
    else:
        pgplot_device = ""

    fftlen = 8192     # Should be a power-of-two for best speed
    chunklen = 8000   # Must be at least max_downfact less than fftlen
    assert(opts.detrendfact in [1,2,4,8,16,32])
    detrendlen = opts.detrendfact*1000
    if (detrendlen > chunklen):
        chunklen = detrendlen
        fftlen = int(next2_to_n(chunklen))
    blocks_per_chunk = chunklen / detrendlen
    overlap = (fftlen - chunklen)/2
    worklen = chunklen + 2*overlap  # currently it is fftlen...

    max_downfact = 30
    default_downfacts = [2, 3, 4, 6, 9, 14, 20, 30, 45, 70, 100, 150, 220, 300]

    if args[0].endswith(".singlepulse"):
        filenmbase = args[0][:args[0].rfind(".singlepulse")]
        dosearch = False
    elif args[0].endswith(".dat"):
        filenmbase = args[0][:args[0].rfind(".dat")]
    else:
        filenmbase = args[0]

    # Don't do a search, just read results and plot
    if not dosearch:
        info, DMs, candlist, num_v_DMstr = \
              read_singlepulse_files(args, opts.threshold, opts.T_start, opts.T_end)
        orig_N, orig_dt = int(info.N), info.dt
        obstime = orig_N * orig_dt
    else:
        DMs = []
        candlist = []
        num_v_DMstr = {}

        # Loop over the input files
        for filenm in args:
            if filenm.endswith(".dat"):
                filenmbase = filenm[:filenm.rfind(".dat")]
            else:
                filenmbase = filenm
            info = infodata.infodata(filenmbase+".inf")
            DMstr = "%.2f"%info.DM
            DMs.append(info.DM)
            N, dt = int(info.N), info.dt
            obstime = N * dt
            # Choose the maximum width to search based on time instead
            # of bins.  This helps prevent increased S/N when the downsampling
            # changes as the DM gets larger.
            if opts.maxwidth > 0.0:
                downfacts = [x for x in default_downfacts if x*dt <= opts.maxwidth]
            else:
                downfacts = [x for x in default_downfacts if x <= max_downfact]
            if len(downfacts) == 0:
                downfacts = [default_downfacts[0]]
            if (filenm == args[0]):
                orig_N = N
                orig_dt = dt

            if info.breaks:
                offregions = zip([x[1] for x in info.onoff[:-1]],
                                 [x[0] for x in info.onoff[1:]])

                # If last break spans to end of file, don't read it in (its just padding)
                if offregions[-1][1] == N - 1:
                    N = offregions[-1][0] + 1

            outfile = open(filenmbase+'.singlepulse', mode='w')

            # Compute the file length in detrendlens
            roundN = N/detrendlen * detrendlen
            numchunks = roundN / chunklen
            # Read in the file
            print 'Reading "%s"...'%filenm
            timeseries = Num.fromfile(filenm, dtype=Num.float32, count=roundN)
            # Split the timeseries into chunks for detrending
            numblocks = roundN/detrendlen
            timeseries.shape = (numblocks, detrendlen)
            stds = Num.zeros(numblocks, dtype=Num.float64)
            # de-trend the data one chunk at a time
            print '  De-trending the data and computing statistics...'
            for ii, chunk in enumerate(timeseries):
                if opts.fast:  # use median removal instead of detrending (2x speedup)
                    tmpchunk = chunk.copy()
                    tmpchunk.sort()
                    med = tmpchunk[detrendlen/2]
                    chunk -= med
                    tmpchunk -= med
                else:
                    # The detrend calls are the most expensive in the program
                    timeseries[ii] = scipy.signal.detrend(chunk, type='linear')
                    tmpchunk = timeseries[ii].copy()
                    tmpchunk.sort()
                # The following gets rid of (hopefully) most of the 
                # outlying values (i.e. power dropouts and single pulses)
                # If you throw out 5% (2.5% at bottom and 2.5% at top)
                # of random gaussian deviates, the measured stdev is ~0.871
                # of the true stdev.  Thus the 1.0/0.871=1.148 correction below.
                # The following is roughly .std() since we already removed the median
                stds[ii] = Num.sqrt((tmpchunk[detrendlen/40:-detrendlen/40]**2.0).sum() /
                                    (0.95*detrendlen))
            stds *= 1.148
            # sort the standard deviations and separate those with
            # very low or very high values
            sort_stds = stds.copy()
            sort_stds.sort()
            # identify the differences with the larges values (this
            # will split off the chunks with very low and very high stds
            locut = (sort_stds[1:numblocks/2+1] -
                     sort_stds[:numblocks/2]).argmax() + 1
            hicut = (sort_stds[numblocks/2+1:] -
                     sort_stds[numblocks/2:-1]).argmax() + numblocks/2 - 2
            std_stds = scipy.std(sort_stds[locut:hicut])
            median_stds = sort_stds[(locut+hicut)/2]
            print "    pseudo-median block standard deviation = %.2f" % (median_stds)
            if (opts.badblocks):
                lo_std = median_stds - 4.0 * std_stds
                hi_std = median_stds + 4.0 * std_stds
                # Determine a list of "bad" chunks.  We will not search these.
                bad_blocks = Num.nonzero((stds < lo_std) | (stds > hi_std))[0]
                print "    identified %d bad blocks out of %d (i.e. %.2f%%)" % \
                      (len(bad_blocks), len(stds),
                       100.0*float(len(bad_blocks))/float(len(stds)))
                stds[bad_blocks] = median_stds
            else:
                bad_blocks = []
            print "  Now searching..."

            # Now normalize all of the data and reshape it to 1-D
            timeseries /= stds[:,Num.newaxis]
            timeseries.shape = (roundN,)
            # And set the data in the bad blocks to zeros
            # Even though we don't search these parts, it is important
            # because of the overlaps for the convolutions
            for bad_block in bad_blocks:
                loind, hiind = bad_block*detrendlen, (bad_block+1)*detrendlen
                timeseries[loind:hiind] = 0.0
            # Convert to a set for faster lookups below
            bad_blocks = set(bad_blocks)

            # Step through the data
            dm_candlist = []
            for chunknum in xrange(numchunks):
                loind = chunknum*chunklen-overlap
                hiind = (chunknum+1)*chunklen+overlap
                # Take care of beginning and end of file overlap issues
                if (chunknum==0): # Beginning of file
                    chunk = Num.zeros(worklen, dtype=Num.float32)
                    chunk[overlap:] = timeseries[loind+overlap:hiind]
                elif (chunknum==numchunks-1): # end of the timeseries
                    chunk = Num.zeros(worklen, dtype=Num.float32)
                    chunk[:-overlap] = timeseries[loind:hiind-overlap]
                else:
                    chunk = timeseries[loind:hiind]

                # Make a set with the current block numbers
                lowblock = blocks_per_chunk * chunknum
                currentblocks = set(Num.arange(blocks_per_chunk) + lowblock)
                localgoodblocks = Num.asarray(list(currentblocks -
                                                   bad_blocks)) - lowblock
                # Search this chunk if it is not all bad
                if len(localgoodblocks):
                    # This is the good part of the data (end effects removed)
                    goodchunk = chunk[overlap:-overlap]

                    # need to pass blocks/chunklen, localgoodblocks
                    # dm_candlist, dt, opts.threshold to cython routine

                    # Search non-downsampled data first
                    # NOTE:  these nonzero() calls are some of the most
                    #        expensive calls in the program.  Best bet would 
                    #        probably be to simply iterate over the goodchunk
                    #        in C and append to the candlist there.
                    hibins = Num.flatnonzero(goodchunk>opts.threshold)
                    hivals = goodchunk[hibins]
                    hibins += chunknum * chunklen
                    hiblocks = hibins/detrendlen
                    # Add the candidates (which are sorted by bin)
                    for bin, val, block in zip(hibins, hivals, hiblocks):
                        if block not in bad_blocks:
                            time = bin * dt
                            dm_candlist.append(candidate(info.DM, val, time, bin, 1))

                    # Now do the downsampling...
                    for downfact in downfacts:
                        if useffts: 
                            # Note:  FFT convolution is faster for _all_ downfacts, even 2
                            chunk2 = Num.concatenate((Num.zeros(1000), chunk, Num.zeros(1000)))
                            goodchunk = Num.convolve(chunk2, Num.ones(downfact), mode='same') / Num.sqrt(downfact)
                            goodchunk = goodchunk[overlap:-overlap]
                            #O qualcosa di simile, altrimenti non so perche' trova piu' candidati! Controllare!
                        else:
                            # The normalization of this kernel keeps the post-smoothing RMS = 1
                            kernel = Num.ones(downfact, dtype=Num.float32) / \
                                     Num.sqrt(downfact)
                            smoothed_chunk = scipy.signal.convolve(chunk, kernel, 1)
                            goodchunk = smoothed_chunk[overlap:-overlap]
                        #hibins = Num.nonzero(goodchunk>opts.threshold)[0]
                        hibins = Num.flatnonzero(goodchunk>opts.threshold)
                        hivals = goodchunk[hibins]
                        hibins += chunknum * chunklen
                        hiblocks = hibins/detrendlen
                        hibins = hibins.tolist()
                        hivals = hivals.tolist()
                        # Now walk through the new candidates and remove those
                        # that are not the highest but are within downfact/2
                        # bins of a higher signal pulse
                        hibins, hivals = prune_related1(hibins, hivals, downfact)
                        # Insert the new candidates into the candlist, but
                        # keep it sorted...
                        for bin, val, block in zip(hibins, hivals, hiblocks):
                            if block not in bad_blocks:
                                time = bin * dt
                                bisect.insort(dm_candlist,
                                              candidate(info.DM, val, time, bin, downfact))

            # Now walk through the dm_candlist and remove the ones that
            # are within the downsample proximity of a higher
            # signal-to-noise pulse
            dm_candlist = prune_related2(dm_candlist, downfacts)
            print "  Found %d pulse candidates"%len(dm_candlist)
            
            # Get rid of those near padding regions
            if info.breaks: prune_border_cases(dm_candlist, offregions)

            # Write the pulses to an ASCII output file
            if len(dm_candlist):
                #dm_candlist.sort(cmp_sigma)
                outfile.write("# DM      Sigma      Time (s)     Sample    Downfact\n")
                for cand in dm_candlist:
                    outfile.write(str(cand))
            outfile.close()

            # Add these candidates to the overall candidate list
            for cand in dm_candlist:
                candlist.append(cand)
            num_v_DMstr[DMstr] = len(dm_candlist)

    if (opts.makeplot):

        # Step through the candidates to make a SNR list
        DMs.sort()
        snrs = []
        for cand in candlist:
            if not Num.isinf(cand.sigma):
                snrs.append(cand.sigma)
        if snrs:
            maxsnr = max(int(max(snrs)), int(opts.threshold)) + 3
        else:
            maxsnr = int(opts.threshold) + 3

        # Generate the SNR histogram
        snrs = Num.asarray(snrs)
        (num_v_snr, lo_snr, d_snr, num_out_of_range) = \
                    scipy.stats.histogram(snrs,
                                          int(maxsnr-opts.threshold+1),
                                          [opts.threshold, maxsnr])
        snrs = Num.arange(maxsnr-opts.threshold+1, dtype=Num.float64) * d_snr \
               + lo_snr + 0.5*d_snr
        num_v_snr = num_v_snr.astype(Num.float32)
        num_v_snr[num_v_snr==0.0] = 0.001

        # Generate the DM histogram
        num_v_DM = Num.zeros(len(DMs))
        for ii, DM in enumerate(DMs):
            num_v_DM[ii] = num_v_DMstr["%.2f"%DM]
        DMs = Num.asarray(DMs)

        # open the plot device
        short_filenmbase = filenmbase[:filenmbase.find("_DM")]
        if opts.T_end > obstime:
            opts.T_end = obstime
        if pgplot_device:
            ppgplot.pgopen(pgplot_device)
        else:
            if (opts.T_start > 0.0 or opts.T_end < obstime):
                ppgplot.pgopen(short_filenmbase+'_%.0f-%.0fs_singlepulse.ps/VPS'%
                               (opts.T_start, opts.T_end))
            else:
                ppgplot.pgopen(short_filenmbase+'_singlepulse.ps/VPS')
        ppgplot.pgpap(7.5, 1.0)  # Width in inches, aspect

        # plot the SNR histogram
        ppgplot.pgsvp(0.06, 0.31, 0.6, 0.87)
        ppgplot.pgswin(opts.threshold, maxsnr,
                       Num.log10(0.5), Num.log10(2*max(num_v_snr)))
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCLNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "Signal-to-Noise")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "Number of Pulses")
        ppgplot.pgsch(1.0)
        ppgplot.pgbin(snrs, Num.log10(num_v_snr), 1)

        # plot the DM histogram
        ppgplot.pgsvp(0.39, 0.64, 0.6, 0.87)
        # Add [1] to num_v_DM in YMAX below so that YMIN != YMAX when max(num_v_DM)==0
        ppgplot.pgswin(min(DMs)-0.5, max(DMs)+0.5, 0.0, 1.1*max(num_v_DM+[1]))
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "DM (pc cm\u-3\d)")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "Number of Pulses")
        ppgplot.pgsch(1.0)
        ppgplot.pgbin(DMs, num_v_DM, 1)

        # plot the SNR vs DM plot 
        ppgplot.pgsvp(0.72, 0.97, 0.6, 0.87)
        ppgplot.pgswin(min(DMs)-0.5, max(DMs)+0.5, opts.threshold, maxsnr)
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "DM (pc cm\u-3\d)")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "Signal-to-Noise")
        ppgplot.pgsch(1.0)
        cand_ts = Num.zeros(len(candlist), dtype=Num.float32)
        cand_SNRs = Num.zeros(len(candlist), dtype=Num.float32)
        cand_DMs = Num.zeros(len(candlist), dtype=Num.float32)
        for ii, cand in enumerate(candlist):
            cand_ts[ii], cand_SNRs[ii], cand_DMs[ii] = \
                         cand.time, cand.sigma, cand.DM
        ppgplot.pgpt(cand_DMs, cand_SNRs, 20)

        # plot the DM vs Time plot
        ppgplot.pgsvp(0.06, 0.97, 0.08, 0.52)
        ppgplot.pgswin(opts.T_start, opts.T_end, min(DMs)-0.5, max(DMs)+0.5)
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "Time (s)")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "DM (pc cm\u-3\d)")
        # Circles are symbols 20-26 in increasing order
        snr_range = 12.0
        cand_symbols = (cand_SNRs-opts.threshold)/snr_range * 6.0 + 20.5
        cand_symbols = cand_symbols.astype(Num.int32)
        cand_symbols[cand_symbols>26] = 26
        for ii in [26, 25, 24, 23, 22, 21, 20]:
            inds = Num.nonzero(cand_symbols==ii)[0]
            ppgplot.pgpt(cand_ts[inds], cand_DMs[inds], ii)

        # Now fill the infomation area
        ppgplot.pgsvp(0.05, 0.95, 0.87, 0.97)
        ppgplot.pgsch(1.0)
        ppgplot.pgmtxt('T', 0.5, 0.0, 0.0,
                       "Single pulse results for '%s'"%short_filenmbase)
        ppgplot.pgsch(0.8)
        # first row
        ppgplot.pgmtxt('T', -1.1, 0.02, 0.0, 'Source: %s'%\
                       info.object)
        ppgplot.pgmtxt('T', -1.1, 0.33, 0.0, 'RA (J2000):')
        ppgplot.pgmtxt('T', -1.1, 0.5, 0.0, info.RA)
        ppgplot.pgmtxt('T', -1.1, 0.73, 0.0, 'N samples: %.0f'%orig_N)
        # second row
        ppgplot.pgmtxt('T', -2.4, 0.02, 0.0, 'Telescope: %s'%\
                       info.telescope)
        ppgplot.pgmtxt('T', -2.4, 0.33, 0.0, 'DEC (J2000):')
        ppgplot.pgmtxt('T', -2.4, 0.5, 0.0, info.DEC)
        ppgplot.pgmtxt('T', -2.4, 0.73, 0.0, 'Sampling time: %.2f \gms'%\
                       (orig_dt*1e6))
        # third row
        if info.instrument.find("pigot") >= 0:
            instrument = "Spigot"
        else:
            instrument = info.instrument
        ppgplot.pgmtxt('T', -3.7, 0.02, 0.0, 'Instrument: %s'%instrument)
        if (info.bary):
            ppgplot.pgmtxt('T', -3.7, 0.33, 0.0, 'MJD\dbary\u: %.12f'%info.epoch)
        else:
            ppgplot.pgmtxt('T', -3.7, 0.33, 0.0, 'MJD\dtopo\u: %.12f'%info.epoch)
        ppgplot.pgmtxt('T', -3.7, 0.73, 0.0, 'Freq\dctr\u: %.1f MHz'%\
                       ((info.numchan/2-0.5)*info.chan_width+info.lofreq))
        ppgplot.pgiden()
        ppgplot.pgend()
	
	xLabel = xColumn
	yLabel = "flux ratio"
	
	# Find the best y-limits
	lowerY = 1E8
	upperY = -1E8
	for photometry in allData:
		yData = photometry[yColumn]
		if max(yData)>upperY: upperY = max(yData)
		if min(yData)<lowerY: lowerY = min(yData)
	
	# Initialise the plot environment 
	plotDevices = ["/xs"]
	for plotDevice in plotDevices:
		mainPGPlotWindow = ppgplot.pgopen(plotDevice)
		pgPlotTransform = [0, 1, 0, 0, 0, 1]
		ppgplot.pgpap(10, 0.618)
		ppgplot.pgask(arg.ask)
		
		for index, photometry in enumerate(allData):
			x_values = photometry[xColumn]
			y_values = photometry[yColumn]
			y_errors = photometry[yErrors]
			x_lower, x_upper = (min(x_values), max(x_values))
			numpoints = len(x_values)
			if "JD" in xColumn:
				x_offset = int(x_lower)
				x_values = [(x-x_offset) for x in x_values]
				xLabel= xColumn + " - %d"%x_lower
			ppgplot.pgsci(1)
		sys.exit()
		
	phase = phaseAngle
		
	
	# Snip out Halpha 
	spectrum.snipWavelengthRange(6550, 6570)
	
	lowerWavelength = min(spectrum.wavelengths)
	upperWavelength = max(spectrum.wavelengths)
	observedSpectrumRange = (lowerWavelength, upperWavelength)
	lowerFlux = min(spectrum.flux)
	upperFlux = max(spectrum.flux)
	lowerFlux = 0
	
	mainPlotWindow = ppgplot.pgopen(arg.device)	
	ppgplot.pgask(False)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgsci(1)
	ppgplot.pgenv(lowerWavelength, upperWavelength, lowerFlux, upperFlux, 0, 0)
	ppgplot.pgline(spectrum.wavelengths, spectrum.flux)
	ppgplot.pglab("wavelength", "flux", spectrum.objectName)
	
	observedArea = spectrum.integrate()
	print "Wavelength range of observations:", observedSpectrumRange
		
	# modelPlotWindow = ppgplot.pgopen(arg.device)	
	# pgPlotTransform = [0, 1, 0, 0, 0, 1]	
	# ppgplot.pgask(False)
	
	currentPlotWindow = ppgplot.pgopen(arg.device)	
Example #17
0
                filter = card.header[key]

    imageData = hdulist[1].data
    savedImageData = numpy.copy(imageData)

    wcsSolution = WCS(hdulist[1].header)

    hdulist.close()

    (height, width) = numpy.shape(imageData)

    aspectRatio = float(height) / float(width)
    print(aspectRatio)
    """ Set up the PGPLOT windows """
    imagePlot = {}
    imagePlot['pgplotHandle'] = ppgplot.pgopen('/xs')
    ppgplot.pgpap(paperSize, aspectRatio)
    ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
    ppgplot.pgswin(0, width, 0, height)

    # ppgplot.pgenv(0., width,0., height, 1, -2)
    imagePlot['pgPlotTransform'] = [0, 1, 0, 0, 0, 1]

    boostedImage = generalUtils.percentiles(imageData, 20, 99)
    ppgplot.pggray(boostedImage, 0, width - 1, 0, height - 1, 0, 255,
                   imagePlot['pgPlotTransform'])

    # Determine the RA, DEC of the centre of the image, using the WCS solution found in the FITS header
    imageCentre = [width / 2, height / 2]

    ra, dec = wcsSolution.all_pix2world([imageCentre], 1)[0]
Example #18
0
				target.appendData(data)
		ptfFile.close()
		objects.append(target)


	

	
	print "%d targets loaded"%len(objects)

	#for o in objects:
	#	o.filterData('mag', 10, 16.5)

	if arg.ps: device = "lightcurves.ps/ps"
	else: device = "/xs"
	PGPlotWindow = ppgplot.pgopen(device) 
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgslct(PGPlotWindow)   
	ppgplot.pgsci(1)
	ppgplot.pgask(False)
	for index, o in enumerate(objects):
		HJD = o.getColumn('HJD')
		mag = o.getColumn('mag')
		err = o.getColumn('err')
		startDate = numpy.min(HJD)
		dates = [ d - startDate for d in HJD]
		endDate = numpy.max(HJD)
		magMax = numpy.max(mag) + err[numpy.argmax(mag)]
		magMin = numpy.min(mag) - err[numpy.argmin(mag)]
		meanError = numpy.mean(err)
		print "%s Start date: %f, End date: %f"%(o.id, startDate, endDate)
Example #19
0
def extract_tracks(fname, trkrmin, drdtmin, trksig, ntrkmin):
    # Read four frame
    ff = fourframe(fname)

    # Skip saturated frames
    if np.sum(ff.zavg > 240.0) / float(ff.nx * ff.ny) > 0.95:
        return

    # Read satelite IDs
    try:
        f = open(fname + ".id")
    except OSError:
        print("Cannot open", fname + ".id")
    else:
        lines = f.readlines()
        f.close()

    # ppgplot arrays
    tr = np.array([-0.5, 1.0, 0.0, -0.5, 0.0, 1.0])
    heat_l = np.array([0.0, 0.2, 0.4, 0.6, 1.0])
    heat_r = np.array([0.0, 0.5, 1.0, 1.0, 1.0])
    heat_g = np.array([0.0, 0.0, 0.5, 1.0, 1.0])
    heat_b = np.array([0.0, 0.0, 0.0, 0.3, 1.0])

    # Loop over identifications
    for line in lines:
        # Decode
        id = satid(line)

        # Skip slow moving objects
        drdt = np.sqrt(id.dxdt**2 + id.dydt**2)
        if drdt < drdtmin:
            continue

        # Extract significant pixels
        x, y, t, sig = ff.significant(trksig, id.x0, id.y0, id.dxdt, id.dydt,
                                      trkrmin)

        # Fit tracks
        if len(t) > ntrkmin:
            # Get times
            tmin = np.min(t)
            tmax = np.max(t)
            tmid = 0.5 * (tmax + tmin)
            mjd = ff.mjd + tmid / 86400.0

            # Skip if no variance in time
            if np.std(t - tmid) == 0.0:
                continue

            # Very simple polynomial fit; no weighting, no cleaning
            px = np.polyfit(t - tmid, x, 1)
            py = np.polyfit(t - tmid, y, 1)

            # Extract results
            x0, y0 = px[1], py[1]
            dxdt, dydt = px[0], py[0]
            xmin = x0 + dxdt * (tmin - tmid)
            ymin = y0 + dydt * (tmin - tmid)
            xmax = x0 + dxdt * (tmax - tmid)
            ymax = y0 + dydt * (tmax - tmid)

            cospar = get_cospar(id.norad)
            obs = observation(ff, mjd, x0, y0)
            iod_line = "%s" % format_iod_line(id.norad, cospar, ff.site_id,
                                              obs.nfd, obs.ra, obs.de)

            print(iod_line)

            if id.catalog.find("classfd.tle") > 0:
                outfname = "classfd.dat"
            elif id.catalog.find("inttles.tle") > 0:
                outfname = "inttles.dat"
            else:
                outfname = "catalog.dat"

            f = open(outfname, "a")
            f.write("%s\n" % iod_line)
            f.close()

            # Plot
            ppgplot.pgopen(
                fname.replace(".fits", "") + "_%05d.png/png" % id.norad)
            #ppgplot.pgopen("/xs")
            ppgplot.pgpap(0.0, 1.0)
            ppgplot.pgsvp(0.1, 0.95, 0.1, 0.8)

            ppgplot.pgsch(0.8)
            ppgplot.pgmtxt(
                "T", 6.0, 0.0, 0.0,
                "UT Date: %.23s  COSPAR ID: %04d" % (ff.nfd, ff.site_id))
            if (3600.0 * ff.crres[0] < 1e-3
                ) | (3600.0 * ff.crres[1] < 1e-3) | (
                    ff.crres[0] / ff.sx > 2.0) | (ff.crres[1] / ff.sy > 2.0):
                ppgplot.pgsci(2)
            else:
                ppgplot.pgsci(1)
            ppgplot.pgmtxt(
                "T", 4.8, 0.0, 0.0,
                "R.A.: %10.5f (%4.1f'') Decl.: %10.5f (%4.1f'')" %
                (ff.crval[0], 3600.0 * ff.crres[0], ff.crval[1],
                 3600.0 * ff.crres[1]))
            ppgplot.pgsci(1)
            ppgplot.pgmtxt(
                "T", 3.6, 0.0, 0.0,
                "FoV: %.2f\\(2218)x%.2f\\(2218) Scale: %.2f''x%.2f'' pix\\u-1\\d"
                % (ff.wx, ff.wy, 3600.0 * ff.sx, 3600.0 * ff.sy))
            ppgplot.pgmtxt(
                "T", 2.4, 0.0, 0.0, "Stat: %5.1f+-%.1f (%.1f-%.1f)" %
                (np.mean(ff.zmax), np.std(ff.zmax), ff.vmin, ff.vmax))
            ppgplot.pgmtxt("T", 0.3, 0.0, 0.0, iod_line)

            ppgplot.pgsch(1.0)
            ppgplot.pgwnad(0.0, ff.nx, 0.0, ff.ny)
            ppgplot.pglab("x (pix)", "y (pix)", " ")
            ppgplot.pgctab(heat_l, heat_r, heat_g, heat_b, 5, 1.0, 0.5)

            ppgplot.pgimag(ff.zmax, ff.nx, ff.ny, 0, ff.nx - 1, 0, ff.ny - 1,
                           ff.vmax, ff.vmin, tr)
            ppgplot.pgbox("BCTSNI", 0., 0, "BCTSNI", 0., 0)
            ppgplot.pgstbg(1)

            ppgplot.pgsci(0)
            if id.catalog.find("classfd.tle") > 0:
                ppgplot.pgsci(4)
            elif id.catalog.find("inttles.tle") > 0:
                ppgplot.pgsci(3)
            ppgplot.pgpt(np.array([x0]), np.array([y0]), 4)
            ppgplot.pgmove(xmin, ymin)
            ppgplot.pgdraw(xmax, ymax)
            ppgplot.pgsch(0.65)
            ppgplot.pgtext(np.array([x0]), np.array([y0]), " %05d" % id.norad)
            ppgplot.pgsch(1.0)
            ppgplot.pgsci(1)

            ppgplot.pgend()

        elif id.catalog.find("classfd.tle") > 0:
            # Track and stack
            t = np.linspace(0.0, ff.texp)
            x, y = id.x0 + id.dxdt * t, id.y0 + id.dydt * t
            c = (x > 0) & (x < ff.nx) & (y > 0) & (y < ff.ny)

            # Skip if no points selected
            if np.sum(c) == 0:
                continue

            # Compute track
            tmid = np.mean(t[c])
            mjd = ff.mjd + tmid / 86400.0
            xmid = id.x0 + id.dxdt * tmid
            ymid = id.y0 + id.dydt * tmid
            ztrk = ndimage.gaussian_filter(ff.track(id.dxdt, id.dydt, tmid),
                                           1.0)
            vmin = np.mean(ztrk) - 2.0 * np.std(ztrk)
            vmax = np.mean(ztrk) + 6.0 * np.std(ztrk)

            # Select region
            xmin = int(xmid - 100)
            xmax = int(xmid + 100)
            ymin = int(ymid - 100)
            ymax = int(ymid + 100)
            if xmin < 0: xmin = 0
            if ymin < 0: ymin = 0
            if xmax > ff.nx: xmax = ff.nx - 1
            if ymax > ff.ny: ymax = ff.ny - 1

            # Find peak
            x0, y0, w, sigma = peakfind(ztrk[ymin:ymax, xmin:xmax])
            x0 += xmin
            y0 += ymin

            # Skip if peak is not significant
            if sigma < trksig:
                continue

            # Skip if point is outside selection area
            if inside_selection(id, xmid, ymid, x0, y0) == False:
                continue

            # Format IOD line
            cospar = get_cospar(id.norad)
            obs = observation(ff, mjd, x0, y0)
            iod_line = "%s" % format_iod_line(id.norad, cospar, ff.site_id,
                                              obs.nfd, obs.ra, obs.de)

            print(iod_line)

            if id.catalog.find("classfd.tle") > 0:
                outfname = "classfd.dat"
            elif id.catalog.find("inttles.tle") > 0:
                outfname = "inttles.dat"
            else:
                outfname = "catalog.dat"

            f = open(outfname, "a")
            f.write("%s\n" % iod_line)
            f.close()

            # Plot
            ppgplot.pgopen(
                fname.replace(".fits", "") + "_%05d.png/png" % id.norad)
            ppgplot.pgpap(0.0, 1.0)
            ppgplot.pgsvp(0.1, 0.95, 0.1, 0.8)

            ppgplot.pgsch(0.8)
            ppgplot.pgmtxt(
                "T", 6.0, 0.0, 0.0,
                "UT Date: %.23s  COSPAR ID: %04d" % (ff.nfd, ff.site_id))
            ppgplot.pgmtxt(
                "T", 4.8, 0.0, 0.0,
                "R.A.: %10.5f (%4.1f'') Decl.: %10.5f (%4.1f'')" %
                (ff.crval[0], 3600.0 * ff.crres[0], ff.crval[1],
                 3600.0 * ff.crres[1]))
            ppgplot.pgmtxt(
                "T", 3.6, 0.0, 0.0,
                "FoV: %.2f\\(2218)x%.2f\\(2218) Scale: %.2f''x%.2f'' pix\\u-1\\d"
                % (ff.wx, ff.wy, 3600.0 * ff.sx, 3600.0 * ff.sy))
            ppgplot.pgmtxt(
                "T", 2.4, 0.0, 0.0, "Stat: %5.1f+-%.1f (%.1f-%.1f)" %
                (np.mean(ff.zmax), np.std(ff.zmax), ff.vmin, ff.vmax))
            ppgplot.pgmtxt("T", 0.3, 0.0, 0.0, iod_line)

            ppgplot.pgsch(1.0)
            ppgplot.pgwnad(0.0, ff.nx, 0.0, ff.ny)
            ppgplot.pglab("x (pix)", "y (pix)", " ")
            ppgplot.pgctab(heat_l, heat_r, heat_g, heat_b, 5, 1.0, 0.5)

            ppgplot.pgimag(ztrk, ff.nx, ff.ny, 0, ff.nx - 1, 0, ff.ny - 1,
                           vmax, vmin, tr)
            ppgplot.pgbox("BCTSNI", 0., 0, "BCTSNI", 0., 0)
            ppgplot.pgstbg(1)

            plot_selection(id, xmid, ymid)

            ppgplot.pgsci(0)
            if id.catalog.find("classfd.tle") > 0:
                ppgplot.pgsci(4)
            elif id.catalog.find("inttles.tle") > 0:
                ppgplot.pgsci(3)
            ppgplot.pgpt(np.array([id.x0]), np.array([id.y0]), 17)
            ppgplot.pgmove(id.x0, id.y0)
            ppgplot.pgdraw(id.x1, id.y1)
            ppgplot.pgpt(np.array([x0]), np.array([y0]), 4)
            ppgplot.pgsch(0.65)
            ppgplot.pgtext(np.array([id.x0]), np.array([id.y0]),
                           " %05d" % id.norad)
            ppgplot.pgsch(1.0)
            ppgplot.pgsci(1)

            ppgplot.pgend()
Example #20
0
	
	images = []
	for f in filesToLoad:
		image = Image.open(f)
		print image.bits, image.size, image.format, image.mode
		exposureTime = getExifValue(image, 'ExposureTime')
		print "Exposure time:", exposureTime
		
		if useDark:
			image = PIL.ImageChops.difference(image, dark)
		
		images.append(image)
	
	(width, height) = images[0].size
	
	previewWindow = ppgplot.pgopen('/xs')	
	ppgplot.pgask(False)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgsci(1)
	ppgplot.pgenv(0, width-1, 0, height-1, 0, 0)
	
	outputWindow = ppgplot.pgopen('/xs')	
	ppgplot.pgask(False)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgsci(1)
	ppgplot.pgenv(0, width-1, 0, height-1, 0, 0)
	
	redReference = numpy.array(images[0].split()[0])
	redTotal = numpy.zeros(numpy.shape(redReference))
	greenTotal = numpy.zeros(numpy.shape(redReference))
	blueTotal = numpy.zeros(numpy.shape(redReference))
Example #21
0
rgx = num.asarray([rs[0], rs[np-1]])
rgy = num.asarray([zs[0], zs[np-1]])
freqcut = pffdot[np/2, :]
fdotcut = pffdot[:, np/2]

image='antirainbow'
device='ffdot_combined.eps/VCPS'
device='/XWIN'
labx='Fourier Frequency Offset (bins)'
laby='Fourier Frequency Derivative (bins)'
contours = num.asarray([0.1, 0.3, 0.5, 0.7, 0.9])

imfract = 0.65
margin = 0.08

ppgplot.pgopen(device)
ppgplot.pgpap(0.0, 1.0)
ppgplot.pgpage()

# Give z and w values and power change
ppgplot.pgsvp(margin+imfract, 1.0-margin/2, margin+imfract, 1.0-margin/2)
ppgplot.pgswin(0.0, 1.0, 0.0, 1.0)
ppgplot.pgtext(0.1, 0.8, "Frac Recovered" % frp)
ppgplot.pgtext(0.2, 0.65, "Power = %.3f" % frp)
ppgplot.pgtext(0.1, 0.4, "signal z = %.1f" % z)
ppgplot.pgtext(0.1, 0.25, "signal w = %.1f" % w)

# freq cut
ppgplot.pgsvp(margin, margin+imfract, margin+imfract, 1.0-margin/2)
ppgplot.pgswin(min(rs), max(rs), -0.1, 1.1)
ppgplot.pgbox("BCST", 0.0, 0, "BCNST", 0.0, 0)
	temperature = 20 	# Temperature in keV
	log_lambda = 1 		# Optical depth parameter
	geometry = 0		# Mysterious geometry parameter
	
	inclination =81    	# Inclination of orbit
	phi = 20				# Angle offset of magnetic axis to orbital axis (not used yet)
	
	phaseArray = []
	angleArray = []
	# Plot theta as a function of orbital phase for these parameters
	for phase in numpy.arange(0.5, 1.51, 0.01):
		theta = computeViewingAngle(phase, inclination, beta, phi)
		phaseArray.append(phase)
		angleArray.append(theta)
		
	mainPlotWindow = ppgplot.pgopen("/xs")	
	ppgplot.pgask(False)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgsci(1)
	ppgplot.pgenv(min(phaseArray), max(phaseArray), 0, 180, 0, 0)
	ppgplot.pgline(phaseArray, angleArray)
	ppgplot.pgsls(2)
	ppgplot.pgline([0.5, 1.5], [90, 90])
	ppgplot.pglab("orbital phase", "viewing angle", "Viewing angle \gh as a function of orbital phase.")
	ppgplot.pgtext(0.6, 150, "i:%2.0f \gb:%2.0f \gf:%2.0f"%(inclination, beta, phi))
		
	
	modelPlotWindow = ppgplot.pgopen("models_i_81_b_40.ps/ps")	
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	ppgplot.pgask(False)
	mainFluxMax = 0
Example #23
0
#! /usr/bin/env python
#
#  pgex1: freely taken after PGDEMO1.F
#
import ppgplot, numpy
import sys

# create an array
xs = numpy.array([1., 2., 3., 4., 5.])
ys = numpy.array([1., 4., 9., 16., 25.])

# creat another array
yr = 0.1 * numpy.array(range(0, 60))
xr = yr * yr

# pgplotting
if len(sys.argv) > 1:  # if we got an argument use the argument as devicename
    ppgplot.pgopen(sys.argv[1])
else:
    ppgplot.pgopen('/xwin')
ppgplot.pgenv(0., 10., 0., 20., 0, 1)
ppgplot.pglab('(x)', '(y)', 'PGPLOT Example 1:  y = x\u2')
ppgplot.pgpt(xs, ys, 9)
ppgplot.pgline(xr, yr)
ppgplot.pgclos()
Example #24
0
    temperature = 20  # Temperature in keV
    log_lambda = 1  # Optical depth parameter
    geometry = 0  # Mysterious geometry parameter

    inclination = 81  # Inclination of orbit
    phi = 20  # Angle offset of magnetic axis to orbital axis (not used yet)

    phaseArray = []
    angleArray = []
    # Plot theta as a function of orbital phase for these parameters
    for phase in numpy.arange(0.5, 1.51, 0.01):
        theta = computeViewingAngle(phase, inclination, beta, phi)
        phaseArray.append(phase)
        angleArray.append(theta)

    mainPlotWindow = ppgplot.pgopen("/xs")
    ppgplot.pgask(False)
    pgPlotTransform = [0, 1, 0, 0, 0, 1]
    ppgplot.pgsci(1)
    ppgplot.pgenv(min(phaseArray), max(phaseArray), 0, 180, 0, 0)
    ppgplot.pgline(phaseArray, angleArray)
    ppgplot.pgsls(2)
    ppgplot.pgline([0.5, 1.5], [90, 90])
    ppgplot.pglab("orbital phase", "viewing angle",
                  "Viewing angle \gh as a function of orbital phase.")
    ppgplot.pgtext(0.6, 150,
                   "i:%2.0f \gb:%2.0f \gf:%2.0f" % (inclination, beta, phi))

    modelPlotWindow = ppgplot.pgopen("models_i_81_b_40.ps/ps")
    pgPlotTransform = [0, 1, 0, 0, 0, 1]
    ppgplot.pgask(False)
Example #25
0
	step = period * 60. / numPoints
	times = []
	brightness = []
	for x in range(numPoints):
		times.append(seconds)
		brightness.append(sinecurve(seconds, period))
		seconds+= step
	
	lightCurve = lightCurve()
	lightCurve.initValues(times, brightness)
	lightCurve.period = period * 60.
	
	lightCurve.brightness[3] = 1.0
	
	lightCurvePlot = {}
	lightCurvePlot['pgplotHandle'] = ppgplot.pgopen('/xs')
	ppgplot.pgpap(8, 0.618)
	ppgplot.pgenv(0., lightCurve.period, 0.0, 1.0, 0, 0)
	ppgplot.pglab("seconds", "brightness", "Light curve")
	ppgplot.pgpt(lightCurve.time, lightCurve.brightness, 2)
	ppgplot.pgsci(2)
	ppgplot.pgline(lightCurve.time, lightCurve.brightness)
	ppgplot.pgask(False)
	
	connectedCount = 0
	connectedBulbs = []
	for b in bulbs:
		print b
		if b['connected'] == True:
			connectedCount+= 1
			connectedBulbs.append(b)
Example #26
0
rgx = num.asarray([rs[0], rs[np - 1]])
rgy = num.asarray([zs[0], zs[np - 1]])
freqcut = pffdot[np / 2, :]
fdotcut = pffdot[:, np / 2]

image = 'antirainbow'
device = 'ffdot_combined.eps/VCPS'
device = '/XWIN'
labx = 'Fourier Frequency Offset (bins)'
laby = 'Fourier Frequency Derivative (bins)'
contours = num.asarray([0.1, 0.3, 0.5, 0.7, 0.9])

imfract = 0.65
margin = 0.08

ppgplot.pgopen(device)
ppgplot.pgpap(0.0, 1.0)
ppgplot.pgpage()

# Give z and w values and power change
ppgplot.pgsvp(margin + imfract, 1.0 - margin / 2, margin + imfract,
              1.0 - margin / 2)
ppgplot.pgswin(0.0, 1.0, 0.0, 1.0)
ppgplot.pgtext(0.1, 0.8, "Frac Recovered" % frp)
ppgplot.pgtext(0.2, 0.65, "Power = %.3f" % frp)
ppgplot.pgtext(0.1, 0.4, "signal z = %.1f" % z)
ppgplot.pgtext(0.1, 0.25, "signal w = %.1f" % w)

# freq cut
ppgplot.pgsvp(margin, margin + imfract, margin + imfract, 1.0 - margin / 2)
ppgplot.pgswin(min(rs), max(rs), -0.1, 1.1)
Example #27
0
def main():
    parser = OptionParser(usage)
    parser.add_option(
        "-x",
        "--xwin",
        action="store_true",
        dest="xwin",
        default=False,
        help="Don't make a postscript plot, just use an X-window")
    parser.add_option("-p",
                      "--noplot",
                      action="store_false",
                      dest="makeplot",
                      default=True,
                      help="Look for pulses but do not generate a plot")
    parser.add_option(
        "-m",
        "--maxwidth",
        type="float",
        dest="maxwidth",
        default=0.0,
        help="Set the max downsampling in sec (see below for default)")
    parser.add_option("-t",
                      "--threshold",
                      type="float",
                      dest="threshold",
                      default=5.0,
                      help="Set a different threshold SNR (default=5.0)")
    parser.add_option("-s",
                      "--start",
                      type="float",
                      dest="T_start",
                      default=0.0,
                      help="Only plot events occuring after this time (s)")
    parser.add_option("-e",
                      "--end",
                      type="float",
                      dest="T_end",
                      default=1e9,
                      help="Only plot events occuring before this time (s)")
    parser.add_option("-g",
                      "--glob",
                      type="string",
                      dest="globexp",
                      default=None,
                      help="Process the files from this glob expression")
    parser.add_option("-f",
                      "--fast",
                      action="store_true",
                      dest="fast",
                      default=False,
                      help="Use a faster method of de-trending (2x speedup)")
    (opts, args) = parser.parse_args()
    if len(args) == 0:
        if opts.globexp == None:
            print full_usage
            sys.exit(0)
        else:
            args = []
            for globexp in opts.globexp.split():
                args += glob.glob(globexp)
    useffts = True
    dosearch = True
    if opts.xwin:
        pgplot_device = "/XWIN"
    else:
        pgplot_device = ""

    fftlen = 8192  # Should be a power-of-two for best speed
    chunklen = 8000  # Must be at least max_downfact less than fftlen
    detrendlen = 1000  # length of a linear piecewise chunk of data for detrending
    blocks_per_chunk = chunklen / detrendlen
    overlap = (fftlen - chunklen) / 2
    worklen = chunklen + 2 * overlap  # currently it is fftlen...

    max_downfact = 30
    default_downfacts = [2, 3, 4, 6, 9, 14, 20, 30, 45, 70, 100, 150]

    if args[0].endswith(".singlepulse"):
        filenmbase = args[0][:args[0].rfind(".singlepulse")]
        dosearch = False
    elif args[0].endswith(".dat"):
        filenmbase = args[0][:args[0].rfind(".dat")]
    else:
        filenmbase = args[0]

    # Don't do a search, just read results and plot
    if not dosearch:
        info, DMs, candlist, num_v_DMstr = \
              read_singlepulse_files(args, opts.threshold, opts.T_start, opts.T_end)
        orig_N, orig_dt = int(info.N), info.dt
        obstime = orig_N * orig_dt
    else:
        DMs = []
        candlist = []
        num_v_DMstr = {}

        # Loop over the input files
        for filenm in args:
            if filenm.endswith(".dat"):
                filenmbase = filenm[:filenm.rfind(".dat")]
            else:
                filenmbase = filenm
            info = infodata.infodata(filenmbase + ".inf")
            DMstr = "%.2f" % info.DM
            DMs.append(info.DM)
            N, dt = int(info.N), info.dt
            obstime = N * dt
            # Choose the maximum width to search based on time instead
            # of bins.  This helps prevent increased S/N when the downsampling
            # changes as the DM gets larger.
            if opts.maxwidth > 0.0:
                downfacts = [
                    x for x in default_downfacts if x * dt <= opts.maxwidth
                ]
            else:
                downfacts = [x for x in default_downfacts if x <= max_downfact]
            if len(downfacts) == 0:
                downfacts = [default_downfacts[0]]
            if (filenm == args[0]):
                orig_N = N
                orig_dt = dt
                if useffts:
                    fftd_kerns = make_fftd_kerns(downfacts, fftlen)
            if info.breaks:
                offregions = zip([x[1] for x in info.onoff[:-1]],
                                 [x[0] for x in info.onoff[1:]])
            outfile = open(filenmbase + '.singlepulse', mode='w')

            # Compute the file length in detrendlens
            roundN = N / detrendlen * detrendlen
            numchunks = roundN / chunklen
            # Read in the file
            print 'Reading "%s"...' % filenm
            timeseries = Num.fromfile(filenm, dtype=Num.float32, count=roundN)
            # Split the timeseries into chunks for detrending
            numblocks = roundN / detrendlen
            timeseries.shape = (numblocks, detrendlen)
            stds = Num.zeros(numblocks, dtype=Num.float64)
            # de-trend the data one chunk at a time
            print '  De-trending the data and computing statistics...'
            for ii, chunk in enumerate(timeseries):
                if opts.fast:  # use median removal instead of detrending (2x speedup)
                    tmpchunk = chunk.copy()
                    tmpchunk.sort()
                    med = tmpchunk[detrendlen / 2]
                    chunk -= med
                    tmpchunk -= med
                else:
                    # The detrend calls are the most expensive in the program
                    timeseries[ii] = scipy.signal.detrend(chunk, type='linear')
                    tmpchunk = timeseries[ii].copy()
                    tmpchunk.sort()
                # The following gets rid of (hopefully) most of the
                # outlying values (i.e. power dropouts and single pulses)
                # If you throw out 5% (2.5% at bottom and 2.5% at top)
                # of random gaussian deviates, the measured stdev is ~0.871
                # of the true stdev.  Thus the 1.0/0.871=1.148 correction below.
                # The following is roughly .std() since we already removed the median
                stds[ii] = Num.sqrt(
                    (tmpchunk[detrendlen / 40:-detrendlen / 40]**2.0).sum() /
                    (0.95 * detrendlen))
            stds *= 1.148
            # sort the standard deviations and separate those with
            # very low or very high values
            sort_stds = stds.copy()
            sort_stds.sort()
            # identify the differences with the larges values (this
            # will split off the chunks with very low and very high stds
            locut = (sort_stds[1:numblocks / 2 + 1] -
                     sort_stds[:numblocks / 2]).argmax() + 1
            hicut = (sort_stds[numblocks / 2 + 1:] -
                     sort_stds[numblocks / 2:-1]).argmax() + numblocks / 2 - 2
            std_stds = scipy.std(sort_stds[locut:hicut])
            median_stds = sort_stds[(locut + hicut) / 2]
            lo_std = median_stds - 4.0 * std_stds
            hi_std = median_stds + 4.0 * std_stds
            # Determine a list of "bad" chunks.  We will not search these.
            bad_blocks = Num.nonzero((stds < lo_std) | (stds > hi_std))[0]
            print "    pseudo-median block standard deviation = %.2f" % (
                median_stds)
            print "    identified %d bad blocks out of %d (i.e. %.2f%%)" % \
                  (len(bad_blocks), len(stds),
                   100.0*float(len(bad_blocks))/float(len(stds)))
            stds[bad_blocks] = median_stds
            print "  Now searching..."

            # Now normalize all of the data and reshape it to 1-D
            timeseries /= stds[:, Num.newaxis]
            timeseries.shape = (roundN, )
            # And set the data in the bad blocks to zeros
            # Even though we don't search these parts, it is important
            # because of the overlaps for the convolutions
            for bad_block in bad_blocks:
                loind, hiind = bad_block * detrendlen, (bad_block +
                                                        1) * detrendlen
                timeseries[loind:hiind] = 0.0
            # Convert to a set for faster lookups below
            bad_blocks = set(bad_blocks)

            # Step through the data
            dm_candlist = []
            for chunknum in range(numchunks):
                loind = chunknum * chunklen - overlap
                hiind = (chunknum + 1) * chunklen + overlap
                # Take care of beginning and end of file overlap issues
                if (chunknum == 0):  # Beginning of file
                    chunk = Num.zeros(worklen, dtype=Num.float32)
                    chunk[overlap:] = timeseries[loind + overlap:hiind]
                elif (chunknum == numchunks - 1):  # end of the timeseries
                    chunk = Num.zeros(worklen, dtype=Num.float32)
                    chunk[:-overlap] = timeseries[loind:hiind - overlap]
                else:
                    chunk = timeseries[loind:hiind]

                # Make a set with the current block numbers
                lowblock = blocks_per_chunk * chunknum
                currentblocks = set(Num.arange(blocks_per_chunk) + lowblock)
                localgoodblocks = Num.asarray(
                    list(currentblocks - bad_blocks)) - lowblock
                # Search this chunk if it is not all bad
                if len(localgoodblocks):
                    # This is the good part of the data (end effects removed)
                    goodchunk = chunk[overlap:-overlap]

                    # need to pass blocks/chunklen, localgoodblocks
                    # dm_candlist, dt, opts.threshold to cython routine

                    # Search non-downsampled data first
                    # NOTE:  these nonzero() calls are some of the most
                    #        expensive calls in the program.  Best bet would
                    #        probably be to simply iterate over the goodchunk
                    #        in C and append to the candlist there.
                    hibins = Num.flatnonzero(goodchunk > opts.threshold)
                    hivals = goodchunk[hibins]
                    hibins += chunknum * chunklen
                    hiblocks = hibins / detrendlen
                    # Add the candidates (which are sorted by bin)
                    for bin, val, block in zip(hibins, hivals, hiblocks):
                        if block not in bad_blocks:
                            time = bin * dt
                            dm_candlist.append(
                                candidate(info.DM, val, time, bin, 1))

                    # Prepare our data for the convolution
                    if useffts: fftd_chunk = rfft(chunk, -1)

                    # Now do the downsampling...
                    for ii, downfact in enumerate(downfacts):
                        if useffts:
                            # Note:  FFT convolution is faster for _all_ downfacts, even 2
                            goodchunk = fft_convolve(fftd_chunk,
                                                     fftd_kerns[ii], overlap,
                                                     -overlap)
                        else:
                            # The normalization of this kernel keeps the post-smoothing RMS = 1
                            kernel = Num.ones(downfact, dtype=Num.float32) / \
                                     Num.sqrt(downfact)
                            smoothed_chunk = scipy.signal.convolve(
                                chunk, kernel, 1)
                            goodchunk = smoothed_chunk[overlap:-overlap]
                        #hibins = Num.nonzero(goodchunk>opts.threshold)[0]
                        hibins = Num.flatnonzero(goodchunk > opts.threshold)
                        hivals = goodchunk[hibins]
                        hibins += chunknum * chunklen
                        hiblocks = hibins / detrendlen
                        hibins = hibins.tolist()
                        hivals = hivals.tolist()
                        # Now walk through the new candidates and remove those
                        # that are not the highest but are within downfact/2
                        # bins of a higher signal pulse
                        hibins, hivals = prune_related1(
                            hibins, hivals, downfact)
                        # Insert the new candidates into the candlist, but
                        # keep it sorted...
                        for bin, val, block in zip(hibins, hivals, hiblocks):
                            if block not in bad_blocks:
                                time = bin * dt
                                bisect.insort(
                                    dm_candlist,
                                    candidate(info.DM, val, time, bin,
                                              downfact))

            # Now walk through the dm_candlist and remove the ones that
            # are within the downsample proximity of a higher
            # signal-to-noise pulse
            dm_candlist = prune_related2(dm_candlist, downfacts)
            print "  Found %d pulse candidates" % len(dm_candlist)

            # Get rid of those near padding regions
            if info.breaks: prune_border_cases(dm_candlist, offregions)

            # Write the pulses to an ASCII output file
            if len(dm_candlist):
                #dm_candlist.sort(cmp_sigma)
                outfile.write(
                    "# DM      Sigma      Time (s)     Sample    Downfact\n")
                for cand in dm_candlist:
                    outfile.write(str(cand))
            outfile.close()

            # Add these candidates to the overall candidate list
            for cand in dm_candlist:
                candlist.append(cand)
            num_v_DMstr[DMstr] = len(dm_candlist)

    if (opts.makeplot):

        # Step through the candidates to make a SNR list
        DMs.sort()
        snrs = []
        for cand in candlist:
            snrs.append(cand.sigma)
        if snrs:
            maxsnr = max(int(max(snrs)), int(opts.threshold)) + 3
        else:
            maxsnr = int(opts.threshold) + 3

        # Generate the SNR histogram
        snrs = Num.asarray(snrs)
        (num_v_snr, lo_snr, d_snr, num_out_of_range) = \
                    scipy.stats.histogram(snrs,
                                          int(maxsnr-opts.threshold+1),
                                          [opts.threshold, maxsnr])
        snrs = Num.arange(maxsnr-opts.threshold+1, dtype=Num.float64) * d_snr \
               + lo_snr + 0.5*d_snr
        num_v_snr = num_v_snr.astype(Num.float32)
        num_v_snr[num_v_snr == 0.0] = 0.001

        # Generate the DM histogram
        num_v_DM = Num.zeros(len(DMs))
        for ii, DM in enumerate(DMs):
            num_v_DM[ii] = num_v_DMstr["%.2f" % DM]
        DMs = Num.asarray(DMs)

        # open the plot device
        short_filenmbase = filenmbase[:filenmbase.find("_DM")]
        if opts.T_end > obstime:
            opts.T_end = obstime
        if pgplot_device:
            ppgplot.pgopen(pgplot_device)
        else:
            if (opts.T_start > 0.0 or opts.T_end < obstime):
                ppgplot.pgopen(short_filenmbase +
                               '_%.0f-%.0fs_singlepulse.ps/VPS' %
                               (opts.T_start, opts.T_end))
            else:
                ppgplot.pgopen(short_filenmbase + '_singlepulse.ps/VPS')
        ppgplot.pgpap(7.5, 1.0)  # Width in inches, aspect

        # plot the SNR histogram
        ppgplot.pgsvp(0.06, 0.31, 0.6, 0.87)
        ppgplot.pgswin(opts.threshold, maxsnr, Num.log10(0.5),
                       Num.log10(2 * max(num_v_snr)))
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCLNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "Signal-to-Noise")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "Number of Pulses")
        ppgplot.pgsch(1.0)
        ppgplot.pgbin(snrs, Num.log10(num_v_snr), 1)

        # plot the DM histogram
        ppgplot.pgsvp(0.39, 0.64, 0.6, 0.87)
        # Add [1] to num_v_DM in YMAX below so that YMIN != YMAX when max(num_v_DM)==0
        ppgplot.pgswin(
            min(DMs) - 0.5,
            max(DMs) + 0.5, 0.0, 1.1 * max(num_v_DM + [1]))
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "DM (pc cm\u-3\d)")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "Number of Pulses")
        ppgplot.pgsch(1.0)
        ppgplot.pgbin(DMs, num_v_DM, 1)

        # plot the SNR vs DM plot
        ppgplot.pgsvp(0.72, 0.97, 0.6, 0.87)
        ppgplot.pgswin(min(DMs) - 0.5, max(DMs) + 0.5, opts.threshold, maxsnr)
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "DM (pc cm\u-3\d)")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "Signal-to-Noise")
        ppgplot.pgsch(1.0)
        cand_ts = Num.zeros(len(candlist), dtype=Num.float32)
        cand_SNRs = Num.zeros(len(candlist), dtype=Num.float32)
        cand_DMs = Num.zeros(len(candlist), dtype=Num.float32)
        for ii, cand in enumerate(candlist):
            cand_ts[ii], cand_SNRs[ii], cand_DMs[ii] = \
                         cand.time, cand.sigma, cand.DM
        ppgplot.pgpt(cand_DMs, cand_SNRs, 20)

        # plot the DM vs Time plot
        ppgplot.pgsvp(0.06, 0.97, 0.08, 0.52)
        ppgplot.pgswin(opts.T_start, opts.T_end,
                       min(DMs) - 0.5,
                       max(DMs) + 0.5)
        ppgplot.pgsch(0.8)
        ppgplot.pgbox("BCNST", 0, 0, "BCNST", 0, 0)
        ppgplot.pgmtxt('B', 2.5, 0.5, 0.5, "Time (s)")
        ppgplot.pgmtxt('L', 1.8, 0.5, 0.5, "DM (pc cm\u-3\d)")
        # Circles are symbols 20-26 in increasing order
        snr_range = 12.0
        cand_symbols = (cand_SNRs - opts.threshold) / snr_range * 6.0 + 20.5
        cand_symbols = cand_symbols.astype(Num.int32)
        cand_symbols[cand_symbols > 26] = 26
        for ii in [26, 25, 24, 23, 22, 21, 20]:
            inds = Num.nonzero(cand_symbols == ii)[0]
            ppgplot.pgpt(cand_ts[inds], cand_DMs[inds], ii)

        # Now fill the infomation area
        ppgplot.pgsvp(0.05, 0.95, 0.87, 0.97)
        ppgplot.pgsch(1.0)
        ppgplot.pgmtxt('T', 0.5, 0.0, 0.0,
                       "Single pulse results for '%s'" % short_filenmbase)
        ppgplot.pgsch(0.8)
        # first row
        ppgplot.pgmtxt('T', -1.1, 0.02, 0.0, 'Source: %s'%\
                       info.object)
        ppgplot.pgmtxt('T', -1.1, 0.33, 0.0, 'RA (J2000):')
        ppgplot.pgmtxt('T', -1.1, 0.5, 0.0, info.RA)
        ppgplot.pgmtxt('T', -1.1, 0.73, 0.0, 'N samples: %.0f' % orig_N)
        # second row
        ppgplot.pgmtxt('T', -2.4, 0.02, 0.0, 'Telescope: %s'%\
                       info.telescope)
        ppgplot.pgmtxt('T', -2.4, 0.33, 0.0, 'DEC (J2000):')
        ppgplot.pgmtxt('T', -2.4, 0.5, 0.0, info.DEC)
        ppgplot.pgmtxt('T', -2.4, 0.73, 0.0, 'Sampling time: %.2f \gms'%\
                       (orig_dt*1e6))
        # third row
        if info.instrument.find("pigot") >= 0:
            instrument = "Spigot"
        else:
            instrument = info.instrument
        ppgplot.pgmtxt('T', -3.7, 0.02, 0.0, 'Instrument: %s' % instrument)
        if (info.bary):
            ppgplot.pgmtxt('T', -3.7, 0.33, 0.0,
                           'MJD\dbary\u: %.12f' % info.epoch)
        else:
            ppgplot.pgmtxt('T', -3.7, 0.33, 0.0,
                           'MJD\dtopo\u: %.12f' % info.epoch)
        ppgplot.pgmtxt('T', -3.7, 0.73, 0.0, 'Freq\dctr\u: %.1f MHz'%\
                       ((info.numchan/2-0.5)*info.chan_width+info.lofreq))
        ppgplot.pgiden()
        ppgplot.pgend()
Example #28
0
#! /usr/bin/env python
#
#  pgex1: freely taken after PGDEMO1.F
#
import ppgplot, numpy
import sys

# create an array 
xs=numpy.array([1.,2.,3.,4.,5.])
ys=numpy.array([1.,4.,9.,16.,25.])

# creat another array
yr = 0.1*numpy.array(range(0,60))
xr = yr*yr


# pgplotting
if len(sys.argv) > 1: # if we got an argument use the argument as devicename
	ppgplot.pgopen(sys.argv[1])
else:
	ppgplot.pgopen('/xwin')
ppgplot.pgenv(0.,10.,0.,20.,0,1)
ppgplot.pglab('(x)', '(y)', 'PGPLOT Example 1:  y = x\u2')
ppgplot.pgpt(xs,ys,9)
ppgplot.pgline(xr,yr)
ppgplot.pgclos()
Example #29
0
def prepplot(rangex, rangey, title=None, labx=None, laby=None, \
             rangex2=None, rangey2=None, labx2=None, laby2=None, \
             logx=0, logy=0, logx2=0, logy2=0, font=ppgplot_font_, \
             fontsize=ppgplot_font_size_, id=0, aspect=1, ticks='in', \
             panels=[1,1], device=ppgplot_device_):
    """
    prepplot(rangex, rangey, ...)
        Open a PGPLOT device for plotting.
            'rangex' and 'rangey' are sequence objects giving min and
                max values for each axis.
        The optional entries are:
            title:    graph title                 (default = None)   
            labx:     label for the x-axis        (default = None)   
            laby:     label for the y-axis        (default = None)   
            rangex2:  ranges for 2nd x-axis       (default = None)   
            rangey2:  ranges for 2nd y-axis       (default = None)   
            labx2:    label for the 2nd x-axis    (default = None)   
            laby2:    label for the 2nd y-axis    (default = None)   
            logx:     make the 1st x-axis log     (default = 0 (no))
            logy:     make the 1st y-axis log     (default = 0 (no))
            logx2:    make the 2nd x-axis log     (default = 0 (no))
            logy2:    make the 2nd y-axis log     (default = 0 (no))
            font:     PGPLOT font to use          (default = 1 (normal))
            fontsize: PGPLOT font size to use     (default = 1.0 (normal))
            id:       Show ID line on plot        (default = 0 (no)) 
            aspect:   Aspect ratio                (default = 1 (square))
            ticks:    Ticks point in or out       (default = 'in')   
            panels:   Number of subpanels [r,c]   (default = [1,1])
            device:   PGPLOT device to use        (default = '/XWIN')
        Note:  Many default values are defined in global variables
            with names like ppgplot_font_ or ppgplot_device_.
    """
    global ppgplot_dev_open_, ppgplot_dev_prep_
    # Check if we will use second X or Y axes
    # Note:  if using a 2nd X axis, the range should correspond
    #   to the minimum and maximum values of the 1st X axis.  If
    #   using a 2nd Y axis, the range should correspond to the
    #   scalerange() values of the 1st Y axis.
    if rangex2 is None:
        rangex2 = rangex
        otherxaxis = 0
    else:
        otherxaxis = 1
    if rangey2 is None:
        rangey2 = rangey
        otheryaxis = 0
    else:
        otheryaxis = 1
    # Open the plot device
    if (not ppgplot_dev_open_):
        ppgplot.pgopen(device)
        # Let the routines know that we already have a device open
        ppgplot_dev_open_ = 1
        # Set the aspect ratio
        ppgplot.pgpap(0.0, aspect)
        if (panels != [1, 1]):
            # Set the number of panels
            ppgplot.pgsubp(panels[0], panels[1])
            ppgplot.pgpage()
    # Choose the font
    ppgplot.pgscf(font)
    # Choose the font size
    ppgplot.pgsch(fontsize)
    # Choose the font size
    ppgplot.pgslw(ppgplot_linewidth_)
    # Plot the 2nd axis if needed first
    if otherxaxis or otheryaxis:
        ppgplot.pgvstd()
        ppgplot.pgswin(rangex2[0], rangex2[1], rangey2[0], rangey2[1])
        # Decide how the axes will be drawn
        if ticks == 'in': env = "CMST"
        else: env = "CMSTI"
        if logx2: lxenv = 'L'
        else: lxenv = ''
        if logy2: lyenv = 'L'
        else: lyenv = ''
        if otherxaxis and otheryaxis:
            ppgplot.pgbox(env + lxenv, 0.0, 0, env + lyenv, 0.0, 0)
        elif otheryaxis:
            ppgplot.pgbox("", 0.0, 0, env + lyenv, 0.0, 0)
        else:
            ppgplot.pgbox(env + lxenv, 0.0, 0, "", 0.0, 0)
    # Now setup the primary axis
    ppgplot.pgvstd()
    ppgplot.pgswin(rangex[0], rangex[1], rangey[0], rangey[1])
    # Decide how the axes will be drawn
    if ticks == 'in': env = "ST"
    else: env = "STI"
    if logx: lxenv = 'L'
    else: lxenv = ''
    if logy: lyenv = 'L'
    else: lyenv = ''
    if otherxaxis and otheryaxis:
        ppgplot.pgbox("BN" + env + lxenv, 0.0, 0, "BN" + env + lyenv, 0.0, 0)
    elif otheryaxis:
        ppgplot.pgbox("BCN" + env + lxenv, 0.0, 0, "BN" + env + lyenv, 0.0, 0)
    elif otherxaxis:
        ppgplot.pgbox("BN" + env + lxenv, 0.0, 0, "BCN" + env + lyenv, 0.0, 0)
    else:
        ppgplot.pgbox("BCN" + env + lxenv, 0.0, 0, "BCN" + env + lyenv, 0.0, 0)
    # Add labels
    if not title is None: ppgplot.pgmtxt("T", 3.2, 0.5, 0.5, title)
    ppgplot.pgmtxt("B", 3.0, 0.5, 0.5, labx)
    ppgplot.pgmtxt("L", 2.6, 0.5, 0.5, laby)
    if otherxaxis: ppgplot.pgmtxt("T", 2.0, 0.5, 0.5, labx2)
    if otheryaxis: ppgplot.pgmtxt("R", 3.0, 0.5, 0.5, laby2)
    # Add ID line if required
    if (id == 1): ppgplot.pgiden()
    # Let the routines know that we have already prepped the device
    ppgplot_dev_prep_ = 1
Example #30
0
	
	filenames = []
	# Load the first set of spectra.
	filename = arg.files
	fileList = open(filename, 'r')
	for line in fileList:
		filenames.append(str(line.strip()))
	
	for fileIndex, f in enumerate(filenames):
		spectrum = spectrumClasses.spectrumObject()
		spectrum.loadFromJSON(f)
		print "Loaded %s, contains %s."%(f, spectrum.objectName)
		spectra.append(spectrum)
		
	
	mainPGPlotWindow = ppgplot.pgopen(device)	
	ppgplot.pgask(True)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	
		
	for spectrum in spectra:
		
		ppgplot.pgsci(1)
		lowerWavelength = min(spectrum.wavelengths)
		upperWavelength = max(spectrum.wavelengths)
		lowerFlux = min(spectrum.flux)
		upperFlux = max(spectrum.flux)
		ppgplot.pgenv(lowerWavelength, upperWavelength, lowerFlux, upperFlux, 0, 0)
		
		ppgplot.pgline(spectrum.wavelengths, spectrum.flux)
		
		if (arg.usefirstframe):
			window.setData(image)
			bkg_sigma = 1.48 * mad(image)
			sources = daofind(image, fwhm=4.0, threshold=3*bkg_sigma)   
			window.setSourcesAvoidBorders(sources)	
		else: 
			window.setBlankData(image)
		
		
		allWindows.append(window)
		
	(xmin, ymin, xmax, ymax) = determineFullFrameSize(allWindows)
	fullFramexsize = xmax - xmin
	fullFrameysize = ymax - ymin
	
	lightcurveView = ppgplot.pgopen('/xs')
	ppgplot.pgenv(startFrame, startFrame + frameRange, 0, 100, 0, 0)
	ppgplot.pgask(False)
	
	if (arg.preview):		
		bitmapView = ppgplot.pgopen('/xs')
		ppgplot.pgenv(0.,fullFramexsize,0.,fullFrameysize, 1, 0)
		pgPlotTransform = [0, 1, 0, 0, 0, 1]
		ppgplot.pgsfs(2)
	
					
	xValues = []
	yValues = []	
	yAxisMax= 100	
	referenceApertures = ultraspecClasses.referenceApertures()
	referenceApertures.initFromSourceList(sourceList)
Example #32
0
    def plot(self, vlo=2., vhi=98., nc=-1, method='p', mpl=False, cmap=CMDEF, \
                 close=True, x1=None, x2=None, y1=None, y2=None, sepmin=1.):
        """
        Plots an MCCD using pgplot or matplotlib if preferred.

        :Parameters:
         vlo : float
            number specifying the lowest level to plot (default as a percentile)
         vhi : float
            number specifying the lowest level to plot (default as a percentile)
         nc : int
            CCD number (starting from 0, -1 for all)
         method : string
            how vlo and vhi are to be interpreted. 'p' = percentile, 'a' = automatic (min to max,
            vlo and vhi are irrelevant), 'd' = direct, i.e. just take the values given.
         mpl : bool
            True to prefer matplotlib over pgplot (which may not even be an option)
         cmap : matplotlib.cm.binary
            colour map if using matplotlib
         close : bool
            close (pgplot) or 'show' (matplotlib) the plot at the end (or not, to allow 
            you to plot something else, use a cursor etc). In the case of pgplot, this also
            implies opening the plot at the start, i.e. a self-contained quick plot.
         x1 : float
            left-hand plot limit. Defaults to 0.5
         x2 : float
             right-hand plot limit. Defaults to nxmax+0.5
         y1 : float
            lower plot limit. Defaults to 0.5
         y2 : float
             upper plot limit. Defaults to nymax+0.5
         sepmin : float
             minimum separation between intensity limits (> 0 to stop PGPLOT complaining)

        :Returns:
         range(s) : tuple or list
            the plot range(s) used either as a single 2-element tuple, or
            a list of them, one per CCD plotted.
        """

        if nc == -1:
            nc1 = 0
            nc2 = len(self)
        else:
            nc1 = nc
            nc2 = nc+1
        
        if not mpl:
            if close: pg.pgopen('/xs')
            if nc2-nc1 > 1: pg.pgsubp(nc2-nc1,1)

        prange = []
        for nc, ccd in enumerate(self._data[nc1:nc2]):

            # Determine intensity range to display
            if method == 'p':
                vmin, vmax = ccd.centile((vlo,vhi))
            elif method == 'a':
                vmin, vmax = ccd.min(), ccd.max()
            elif method == 'd':
                vmin, vmax = vlo, vhi
            else:
                raise UltracamError('MCCD.plot: method must be one of p, a or d.')

            if vmin == vmax:
                vmin -= sepmin/2.
                vmax += sepmin/2.
            prange.append((vmin, vmax))

            # start
            nxmax, nymax = ccd.nxmax, ccd.nymax
            x1    = 0.5 if x1 is None else x1
            x2    = nxmax+0.5 if x2 is None else x2
            y1    = 0.5 if y1 is None else y1
            y2    = nymax+0.5 if y2 is None else y2

            if mpl:
                if nc2-nc1 > 1:
                    plt.subplot(1,nc2-nc1,nc+1)
                plt.axis('equal')
            else:
                if nc2-nc1 > 1: pg.pgpanl(nc-nc1+1,1)
                pg.pgwnad(x1,x2,y1,y2)

            # plot CCD
            ccd.plot(vmin,vmax,mpl,cmap)

            # per-frame finishing-off
            if mpl:
                plt.xlim(x1,x2)
                plt.ylim(y1,y2)
            else:
                pg.pgbox('bcnst',0,0,'bcnst',0,0)
                pg.pglab('X','Y','')

        if close:
            if mpl:
                plt.show()
            else:
                pg.pgclos()

        # return intensity range(s) used
        if len(prange) == 1:
            return prange[0]
        else:
            return tuple(prange)
Example #33
0
    imageData = hdulist[1].data
    savedImageData = numpy.copy(imageData)

    wcsSolution = WCS(hdulist[1].header)

    hdulist.close()

    (height, width) = numpy.shape(imageData)

    aspectRatio = float(height) / float(width)
    print (aspectRatio)

    """ Set up the PGPLOT windows """
    imagePlot = {}
    imagePlot["pgplotHandle"] = ppgplot.pgopen("/xs")
    ppgplot.pgpap(paperSize, aspectRatio)
    ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
    ppgplot.pgswin(0, width, 0, height)

    # ppgplot.pgenv(0., width,0., height, 1, -2)
    imagePlot["pgPlotTransform"] = [0, 1, 0, 0, 0, 1]

    boostedImage = generalUtils.percentiles(imageData, 20, 99)
    ppgplot.pggray(boostedImage, 0, width - 1, 0, height - 1, 0, 255, imagePlot["pgPlotTransform"])

    # Determine the RA, DEC of the centre of the image, using the WCS solution found in the FITS header
    imageCentre = [width / 2, height / 2]

    ra, dec = wcsSolution.all_pix2world([imageCentre], 1)[0]
Example #34
0
    else:
        print '# Warning: no sources found to match ', src
        os._exit(1)

    if _do_grace:
        #  -- switch lists to arrays (should have done that to begin with) for pgplot
        t = Numeric.array(date)  # time (in days)
        t = t - t0  # but relative to first date found
        f = Numeric.array(flux)  # flux
        e = 3 * Numeric.array(ferr)  # flux errors as 3 sigma
        g = Numeric.array(freq)  # freq

        p = gracePlot.gracePlot()
        p.plot(t, f, e, symbols=1)
        p.title('Fluxes for ' + src)
        p.xlabel('Days since ' + d0)
        p.ylabel('Flux (Jy)')
        for r in [[70, 100], [100, 120], [120, 250]]:
            n, x, y, dy = get_range(t, f, e, g, r[0], r[1], cut)
            if n: p.plot(x, y, dy, symbols=1)
            p.hold(1)
    elif _do_pgplot:
        t = Numeric.array(date)  # time (in days)
        t = t - t0  # but relative to first date found
        f = Numeric.array(flux)  # flux
        ppgplot.pgopen(pgp)
        ppgplot.pgenv(0, 1500, 0, 80, 0, 1)
        ppgplot.pglab('Days since %s' % d0, 'Flux(Jy)', 'Flux for %s' % src)
        ppgplot.pgpt(t, f, 9)
        ppgplot.pgline(t, f)
Example #35
0
	referenceSpectrum.objectName = "M-dwarf spectrum"
	tioSpectrum = copy.deepcopy(referenceSpectrum)
	tioSpectrum.trimWavelengthRange(7000, 7500)
	tioArea = tioSpectrum.integrate()
	print "tioArea", tioArea

	tio1Range = (7540, 7580)
	tio2Range = (7675, 7715)
	
	tio1reference = referenceSpectrum.integrate(wavelengthrange = tio1Range)
	tio2reference = referenceSpectrum.integrate(wavelengthrange = tio2Range)
	tioRatio = tio1reference / tio2reference
	tioDifference =  tio1reference - tio2reference
	print "tio1reference, tio2reference:", tio1reference, tio2reference, tioRatio, tioDifference
		
	mainPGPlotWindow = ppgplot.pgopen('/xs')	
	ppgplot.pgask(True)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	yUpper = 2.5
	yLower = -0.5
	
	newSpectra = []
	for spectrum in spectra:
		ppgplot.pgsci(1)
		lowerWavelength = min(spectrum.wavelengths)
		upperWavelength = max(spectrum.wavelengths)
		lowerFlux = min(spectrum.flux)
		upperFlux = max(spectrum.flux)
		ppgplot.pgenv(lowerWavelength, upperWavelength, yLower, yUpper, 0, 0)
		ppgplot.pgline(spectrum.wavelengths, spectrum.flux)
		if hasEphemeris:
Example #36
0
        l, b = w.wcs_pix2world(np.stack((x, y), axis=-1), 1).T
    else:
        l, b = w.wcs_pix2world([[x, y]], 1)[0]

    return l, b


if __name__ == "__main__":
    # Load stars
    s = Stars()

    # Load the master class
    m = Skymap()

    # Initialize plot
    ppgplot.pgopen("/xs")
    ppgplot.pgslw(2)
    ppgplot.pgpap(0.0, 0.75)

    # For ever loop
    redraw = True
    while True:
        # Redraw
        if redraw == True:
            # Update
            m.update()

            # Initialize window
            ppgplot.pgscr(0, 0., 0., 0.)
            ppgplot.pgeras()
            ppgplot.pgsvp(0.01, 0.99, 0.01, 0.99)
Example #37
0
def plot(command, data, group, cdata):
    """
    Plots dsets from a dictionary called data.

    Interactive usage:

    plot slots [device x1 x2 y1 y2 xoff ysep=0 pmask]

    Arguments:

    slots   -- range of slots as in '1-10', or just a single slot '9' to plot, or a group
               name such as 'ippeg'.
    device  -- plot device (e.g. '/xs', '3/xs', 'hardcopy.ps/cps')
    x1      -- left-hand plot limit
    x2      -- right-hand plot limit. Set = x1 for automatic determination
    y1      -- lower plot limit
    y2      -- upper plot limit.  Set = y1 for automatic determination
    xoff    -- offset to start X axis from, 0 for automatic determination.
    ysep    -- separation in y
    pmask   -- whether to plot masked data
    """

    # generate arguments
    inpt = inp.Input(DINT_ENV, DINT_DEF, inp.clist(command))

    # register parameters
    inpt.register('slots',  inp.Input.LOCAL, inp.Input.PROMPT)
    inpt.register('device', inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('x1',     inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('x2',     inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('y1',     inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('y2',     inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('xoff',   inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('ysep',   inp.Input.LOCAL, inp.Input.HIDE)
    inpt.register('pmask',  inp.Input.LOCAL, inp.Input.HIDE)

    # get inputs
    slots  = inpt.get_value('slots', 'slots to plot', '1')
    slist  = interp_slots(slots, True, data, group)

    device = inpt.get_value('device', 'plot device', '/xs')
    x1   = inpt.get_value('x1', 'left-hand plot limit', 0.0)
    x2   = inpt.get_value('x2', 'right-hand plot limit', 0.0)
    y1   = inpt.get_value('y1', 'lower plot limit', 0.0)
    y2   = inpt.get_value('y2', 'upper plot limit', 0.0)
    xoff = inpt.get_value('xoff', 'X offset', 0.0)
    inpt.set_default('ysep', 0.0)
    ysep = inpt.get_value('ysep', 'vertical separation between successive dsets', 0.0)
    pmask = inpt.get_value('pmask', 'do you want to plot the masked data too?', True)

    # Determine limits automatically if required
    if xoff !=0. or x1 == x2 or y1 == y2:
        xa1 = None
        xa2 = None
        ya1 = None
        ya2 = None
        yadd = 0.
        for i in slist:
            (xi1,xi2,yi1,yi2) = data[i].plimits()
            if xa1 is None:
                xa1 = xi1
            else:
                xa1 = min(xa1, xi1)

            if xa2 is None:
                xa2 = xi2
            else:
                xa2 = max(xa2, xi2)

            if ya1 is None and yi1 is not None:
                ya1 = yi1 + yadd
            elif yi1 is not None:
                ya1 = min(ya1, yi1 + yadd)

            if ya2 is None and yi2 is not None:
                ya2 = yi2 + yadd
            elif yi2 is not None:
                ya2 = max(ya2, yi2 + yadd)

            yadd += ysep

        if xa1 is None or xa2 is None or ya1 is None or ya2 is None:
            raise DintError('plot: no automatic limits could be evaluated; possibly no good data to plot?')

        if xoff == 0.0 and (xa2 - xa1) < (xa1+xa2)/2./100.:
            xoff = xa1
        xa1 -= xoff
        xa2 -= xoff

        if x1 == x2:
            x1 = xa1
            x2 = xa2

        if y1 == y2:
            y1 = ya1
            y2 = ya2

    try:

        pg.pgopen(device)
        pg.pgsci(4)
        pg.pgenv(x1, x2, y1, y2, 0, 0)
        pg.pgsci(2)
        first   = data[slist[0]]
        xlabel  = first.x.label if xoff == 0 else first.x.label + '-' + str(xoff)
        xlabel += ' (' + first.x.units + ')'
        ylabel  = first.y.label + ' (' + first.y.units + ')'
        pg.pglab(xlabel, ylabel, first.title)

        yadd = 0.
        for slot in slist:
            data[slot].plot(xoff,yoff=-yadd,masked=pmask)
            if not cdata.mute:
                print('Plotted slot ' + str(slot))
            yadd += ysep

        pg.pgclos()

    except pg.ioerror, err:
        raise DintError(str(err))
Example #38
0
		referenceSpectrum = spectra[0]
		normalConstant = referenceSpectrum.integrate((arg.nl, arg.nu))
		print "Normalisation constant:", normalConstant
	
		for index in range(1, len(spectra)):
			s = spectra[index]
			normalVal = s.integrate((arg.nl, arg.nu))
			print "Normalisation value:", normalVal, normalConstant
			spectra[index].divide(normalVal/normalConstant)
			normalVal = s.integrate((arg.nl, arg.nu))
			print "New Normalisation value:", normalVal, normalConstant
	
	
	
	if not arg.stacked:
		mainPGPlotWindow = ppgplot.pgopen(arg.device)	
		ppgplot.pgask(True)
		pgPlotTransform = [0, 1, 0, 0, 0, 1]
		yUpper = 2.5
		yLower = -0.5
		for spectrum in spectra:
			ppgplot.pgsci(1)
			lowerWavelength = min(spectrum.wavelengths)
			upperWavelength = max(spectrum.wavelengths)
			lowerFlux = min(spectrum.flux)
			upperFlux = max(spectrum.flux)
			ppgplot.pgenv(lowerWavelength, upperWavelength, lowerFlux, upperFlux, 0, 0)
			ppgplot.pgbin(spectrum.wavelengths, spectrum.flux)
			if hasEphemeris:
				ppgplot.pglab("wavelength [%s]"%spectrum.wavelengthUnits, "flux [%s]"%spectrum.fluxUnits, "%s [%f]"%(spectrum.objectName, spectrum.phase))
			else:
 def ok():
     pg.pgopen('/null')
     self.ccd.plot(5,95)
     pg.pgclos()
     return True
	numSources = len(allSources)
	maxSources = int(round((numSources)*0.4))
	debug.write("Number of sources: %d, number of top sources: %d"%(numSources, maxSources), 2)
	if maxSources<1:
		debug.write("WARNING: Not enough sources for shift calculation, proceeding in '--noshift' mode.", 1)
		applyShift = False
	else:
		topSources = allSources[0:maxSources]
		masterApertureList = [ (x, y) for (x, y, flux) in topSources]
		
	
	# Plot the preview frame
	if (arg.keyimages):
		#stackedFigure = matplotlib.pyplot.figure(figsize=(10, 10))
		#matplotlib.pyplot.title("Initial 10 frame stacked image")
		stackedPreview = ppgplot.pgopen('/xs')
		ppgplot.pgenv(0.,fullFramexsize,0.,fullFrameysize, 1, 0)
		pgPlotTransform = [0, 1, 0, 0, 0, 1]
		ppgplot.pglab("x", "y", "Initial 10 frame stacked image.")
	
		# Display the image on the user's screen
		image = matplotlib.pyplot.imshow(boostedFullFrame, cmap='gray_r')
		for s in allSources:
			x, y = s[0], s[1]
			matplotlib.pyplot.gca().add_artist(matplotlib.pyplot.Circle((x,y), 10, color='green', fill=False, linewidth=1.0))
		if applyShift:
			for s in topSources:
				x, y = s[0], s[1]
				matplotlib.pyplot.gca().add_artist(matplotlib.pyplot.Circle((x,y), 10, color='blue', fill=False, linewidth=1.0))
		
		rows, cols = numpy.shape(boostedFullFrame)
Example #41
0
    yield f[0, ...]


def sum_it_impl(ar, quant):
    # shape = (nheap, nspec, nchan)
    # we sum over nspec
    a2 = numpy.sum(quant(ar), axis=1)
    # now shape = (nheap, nchan)
    # we reorganize as:
    # (nheap, 1, nchan)
    a2.shape = ((a2.shape[0], 1, a2.shape[1]))
    print "a2's shape = ", a2.shape
    return a2


sum_it = lambda quant: (lambda ar: sum_it_impl(ar, quant))

#proc_file = lambda quant: lambda fn: map(draw_one, rdspec(fn, quant))
#proc_file = lambda quant: lambda fn: map(draw_one, rdbeamform(fn, quant))
#proc_file = lambda quant: lambda fn: map(draw_one, rdbeamform_nt(fn, quant))
proc_file = lambda quant: lambda fn: map(draw_one, rdbeamform_hv(fn, quant))
#proc_file = lambda quant: lambda fn: map(draw_one, rdbeamform_hv_avg(fn, quant))
#ppgplot.pgopen("42/xw")
#ppgplot.pgopen("/tmp/amplitude-1spectrum.ps/cps")
#ppgplot.pgopen("/tmp/amplitude-1spectrum.png/png")
ppgplot.pgopen("?")
ppgplot.pgask(False)
#map(proc_file(numpy.abs), sys.argv[1:])
map(proc_file(sum_it(numpy.abs)), sys.argv[1:])
#map(proc_file(lambda x: numpy.angle(x, True)), sys.argv[1:])
Example #42
0
def setmask(command, data, cdata):
    """
    Sets the mask on a dset and dumps a file containing the mask which can be applied
    to other dsets using 'appmask'. This is an interactive routine which will request
    input from the user and is better not used in batch processing. Repeated calls of
    this routine can be used to build complex masks. The masks are always applied in
    the original order so that you can mask then partially unmask for example. Note that
    whatever slot you choose to define the mask will always end up masked; if you don't
    want this you may want to make a copy.

    Interactive usage:

    setmask slot mfile append [device reset x1 x2 y1 y2] mask type

    Arguments:

    slot      -- an example slot to plot.
    mfile     -- mask file
    append    -- append to an old mask file if possible
    device    -- plot device, e.g. '/xs'
    reset     -- rest plot limits or not
    x1        -- left X plot limit
    x2        -- right X plot limit
    y1        -- bottom Y plot limit
    y2        -- top Y plot limit
    mask      -- mask 'M', or unmask 'U' or quit 'Q'.
    type      -- type of mask: 'X' masks using ranges in X

    Mask types:

    X  -- mask a range in X
    Y  -- mask a range in Y
    I  -- mask a range of pixel indices
    P  -- mask in 'phase', i.e. a range that repeats periodically.
    """

    import trm.dnl.mask as mask

    # generate arguments
    inpt = inp.Input(DINT_ENV, DINT_DEF, inp.clist(command))

    # register parameters
    inpt.register('slot',   inp.Input.LOCAL, inp.Input.PROMPT)
    inpt.register('mfile',  inp.Input.GLOBAL,  inp.Input.PROMPT)
    inpt.register('append', inp.Input.LOCAL,  inp.Input.PROMPT)
    inpt.register('device', inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('reset',  inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('x1',     inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('x2',     inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('y1',     inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('y2',     inp.Input.LOCAL,  inp.Input.HIDE)
    inpt.register('mask',   inp.Input.LOCAL,  inp.Input.PROMPT)
    inpt.register('type',   inp.Input.LOCAL,  inp.Input.PROMPT)

    # get inputs
    slots  = inpt.get_value('slot', 'slot to plot for mask definition', '1')
    slist  = interp_slots(slots, True, data, nfind=1)
    dset   = data[slist[0]]

    device = inpt.get_value('device', 'plot device', '/xs')

    # mask file
    mfile  = inpt.get_value('mfile',  'mask file to save results to', subs.Fname('mask','.msk', subs.Fname.NEW))
    append = inpt.get_value('append', 'add to an old mask file if possible', True)

    if append and mfile.exists():
        mptr  = open(mfile,'rb')
        gmask = pickle.load(mptr)
        gmask.app_mask(dset)
        mptr.close()
    else:
        gmask = mask.Gmask()

    # other parameters
    reset = inpt.get_value('reset',   'reset plot limits automatically?', True)

    # compute default limits
    (x1,x2,y1,y2) = dset.plimits()
    if (x2 - x1) < (x1+x2)/2./100.:
        xoff = x1
        x1   = 0.
        x2  -= xoff
    else:
        xoff = 0.
    yoff = 0.

    if reset:
        inpt.set_default('x1', x1)
        inpt.set_default('x2', x2)
        inpt.set_default('y1', y1)
        inpt.set_default('y2', y2)

    x1 = inpt.get_value('x1', 'left-hand limit of plot', x1)
    x2 = inpt.get_value('x2', 'right-hand limit of plot', x2)
    y1 = inpt.get_value('y1', 'bottom limit of plot', y1)
    y2 = inpt.get_value('y2', 'top limit of plot', y2)

    m_or_u    = inpt.get_value('mask', 'M(ask), U(nmask) or Q(uit)?', 'm', lvals=['m', 'M', 'u', 'U', 'q', 'Q'])
    if m_or_u.upper() == 'M':
        mtext = 'mask'
    else:
        mtext = 'unmask'

    mask_type = inpt.get_value('type', 'X, Y, P(hase), I(ndex) or Q(uit)?', 'x',
                               lvals=['x', 'X', 'y', 'Y', 'p', 'P', 'i', 'I', 'q', 'Q'])

    # initialise plot
    try:
        pg.pgopen(device)
        pg.pgsch(1.5)
        pg.pgscf(2)
        pg.pgslw(2)
        pg.pgsci(4)
        pg.pgenv(x1,x2,y1,y2,0,0)
        (xlabel,ylabel) = dset.plabel(xoff,yoff)
        pg.pgsci(2)
        pg.pglab(xlabel, ylabel, dset.title)

        # plot the dset
        dset.plot(xoff,yoff)

        x = (x1+x2)/2.
        y = (y1+y2)/2.

        # now define masks
        ch = 'X'
        while ch.upper() != 'Q':

            # go through mask options
            if mask_type.upper() == 'X':

                print('Set cursor at the one end of the X range, Q to quit')
                (xm1,y,ch) = pg.pgband(7,0,x,y)
                if ch.upper() != 'Q':
                    print('Set cursor at the other end of ' +
                          'the X range, Q to quit')
                    xm2,y,ch = pg.pgband(7,0,xm1,y)
                    if ch.upper() != 'Q':
                        if xm1 > xm2: xm1,xm2 = xm2,xm1
                        umask = mask.Xmask(xoff+xm1, xoff+xm2, m_or_u.upper() == 'M')

            elif mask_type.upper() == 'I':

                print('Place cursor near a point and click to ' +
                      mtext + ' it, Q to quit')
                x,y,ch = pg.pgband(7,0,x,y)
                if ch.upper() != 'Q':
                    xmm1,xmm2,ymm1,ymm2 = pg.pgqvp(2)
                    xscale  = (xmm2-xmm1)/(x2-x1)
                    yscale  = (ymm2-ymm1)/(y2-y1)

                    # only consider good data of opposite 'polarity' to the
                    # change we are making.
                    ok  = (dset.good == True) & \
                          (dset.mask == (m_or_u.upper() == 'M'))

                    if len(dset.x.dat[ok == True]):
                        # compute physical squared distance of cursor from
                        # points
                        sqdist  = npy.power(
                            xscale*(dset.x.dat[ok]-(xoff+x)),2) + \
                            npy.power(yscale*(dset.y.dat[ok]-(yoff+y)),2)

                        # select the index giving the minimum distance
                        indices = npy.arange(len(dset))[ok]
                        index   = indices[sqdist.min() == sqdist][0]
                        umask   = mask.Imask(index, m_or_u.upper() == 'M')
                    else:
                        print('There seem to be no data to ' + mtext +
                              '; data already ' + mtext + 'ed are ignored.')
                        umask = None

            if ch.upper() != 'Q' and umask is not None:
                gmask.append(umask)
                umask.app_mask(dset)

                print('overplotting data')
                # over-plot the dset
                dset.plot(xoff,yoff)

        pg.pgclos()
    except pg.ioerror, err:
        raise DintError(str(err))
Example #43
0
		print repr(card.header)
	
	imageData =  hdulist[0].data
	
	wcsSolution = WCS(hdulist[0].header)
	
	hdulist.close()
	
	(height, width) = numpy.shape(imageData)
	
	aspectRatio = float(height)/float(width)
	print aspectRatio
	
	""" Set up the PGPLOT windows """
	imagePlot = {}
	imagePlot['pgplotHandle'] = ppgplot.pgopen('/xs')
	ppgplot.pgpap(paperSize, aspectRatio)
	ppgplot.pgsvp(0.0, 1.0, 0.0, 1.0)
	ppgplot.pgswin(0, width, 0, height)
	
	# ppgplot.pgenv(0., width,0., height, 1, -2)
	imagePlot['pgPlotTransform'] = [0, 1, 0, 0, 0, 1]
	
	boostedImage = generalUtils.percentiles(imageData, 20, 99)
	ppgplot.pggray(boostedImage, 0, width-1, 0, height-1, 0, 255, imagePlot['pgPlotTransform'])
	
	# Determine the RA, DEC of the centre of the image, using the WCS solution found in the FITS header
	imageCentre = [ width/2, height/2]
	
	
	ra, dec = wcsSolution.all_pix2world([imageCentre], 1)[0]
Example #44
0
def prepplot(rangex, rangey, title=None, labx=None, laby=None, \
             rangex2=None, rangey2=None, labx2=None, laby2=None, \
             logx=0, logy=0, logx2=0, logy2=0, font=ppgplot_font_, \
             fontsize=ppgplot_font_size_, id=0, aspect=1, ticks='in', \
             panels=[1,1], device=ppgplot_device_):
    """
    prepplot(rangex, rangey, ...)
        Open a PGPLOT device for plotting.
            'rangex' and 'rangey' are sequence objects giving min and
                max values for each axis.
        The optional entries are:
            title:    graph title                 (default = None)   
            labx:     label for the x-axis        (default = None)   
            laby:     label for the y-axis        (default = None)   
            rangex2:  ranges for 2nd x-axis       (default = None)   
            rangey2:  ranges for 2nd y-axis       (default = None)   
            labx2:    label for the 2nd x-axis    (default = None)   
            laby2:    label for the 2nd y-axis    (default = None)   
            logx:     make the 1st x-axis log     (default = 0 (no))
            logy:     make the 1st y-axis log     (default = 0 (no))
            logx2:    make the 2nd x-axis log     (default = 0 (no))
            logy2:    make the 2nd y-axis log     (default = 0 (no))
            font:     PGPLOT font to use          (default = 1 (normal))
            fontsize: PGPLOT font size to use     (default = 1.0 (normal))
            id:       Show ID line on plot        (default = 0 (no)) 
            aspect:   Aspect ratio                (default = 1 (square))
            ticks:    Ticks point in or out       (default = 'in')   
            panels:   Number of subpanels [r,c]   (default = [1,1])
            device:   PGPLOT device to use        (default = '/XWIN')
        Note:  Many default values are defined in global variables
            with names like ppgplot_font_ or ppgplot_device_.
    """
    global ppgplot_dev_open_, ppgplot_dev_prep_
    # Check if we will use second X or Y axes
    # Note:  if using a 2nd X axis, the range should correspond
    #   to the minimum and maximum values of the 1st X axis.  If
    #   using a 2nd Y axis, the range should correspond to the
    #   scalerange() values of the 1st Y axis.
    if rangex2 is None:
        rangex2=rangex
        otherxaxis=0
    else: otherxaxis=1
    if rangey2 is None:
        rangey2=rangey
        otheryaxis=0
    else: otheryaxis=1
    # Open the plot device
    if (not ppgplot_dev_open_):
        ppgplot.pgopen(device)
	# My little add-on to switch the background to white
	if device == '/XWIN':
	    reset_colors()
	if device == '/AQT':
	    ppgplot.pgsci(0)
        # Let the routines know that we already have a device open
        ppgplot_dev_open_ = 1
        # Set the aspect ratio
        ppgplot.pgpap(0.0, aspect)
        if (panels != [1,1]):
            # Set the number of panels
            ppgplot.pgsubp(panels[0], panels[1])
            ppgplot.pgpage()
    # Choose the font  
    ppgplot.pgscf(font)
    # Choose the font size
    ppgplot.pgsch(fontsize)
    # Choose the font size
    ppgplot.pgslw(ppgplot_linewidth_)
    # Plot the 2nd axis if needed first
    if otherxaxis or otheryaxis:
        ppgplot.pgvstd()
        ppgplot.pgswin(rangex2[0], rangex2[1], rangey2[0], rangey2[1])
        # Decide how the axes will be drawn
        if ticks=='in': env = "CMST"
        else: env = "CMSTI"
        if logx2: lxenv='L'
        else: lxenv=''
        if logy2: lyenv='L'
        else: lyenv=''
        if otherxaxis and otheryaxis:
            ppgplot.pgbox(env+lxenv, 0.0, 0, env+lyenv, 0.0, 0)
        elif otheryaxis:
            ppgplot.pgbox("", 0.0, 0, env+lyenv, 0.0, 0)
        else:
            ppgplot.pgbox(env+lxenv, 0.0, 0, "", 0.0, 0)
    # Now setup the primary axis
    ppgplot.pgvstd()
    ppgplot.pgswin(rangex[0], rangex[1], rangey[0], rangey[1])
    # Decide how the axes will be drawn
    if ticks=='in': env = "ST"
    else: env = "STI"
    if logx: lxenv='L'
    else: lxenv=''
    if logy: lyenv='L'
    else: lyenv=''
    if otherxaxis and otheryaxis:
        ppgplot.pgbox("BN"+env+lxenv, 0.0, 0, "BN"+env+lyenv, 0.0, 0)
    elif otheryaxis:
        ppgplot.pgbox("BCN"+env+lxenv, 0.0, 0, "BN"+env+lyenv, 0.0, 0)
    elif otherxaxis:
        ppgplot.pgbox("BN"+env+lxenv, 0.0, 0, "BCN"+env+lyenv, 0.0, 0)
    else:
        ppgplot.pgbox("BCN"+env+lxenv, 0.0, 0, "BCN"+env+lyenv, 0.0, 0)
    # My little add-on to switch the background to white
    if device == '/AQT' or device == '/XWIN':
	reset_colors()
    # Add labels
    if not title is None: ppgplot.pgmtxt("T", 3.2, 0.5, 0.5, title)
    ppgplot.pgmtxt("B", 3.0, 0.5, 0.5, labx)
    ppgplot.pgmtxt("L", 2.6, 0.5, 0.5, laby)
    if otherxaxis: ppgplot.pgmtxt("T", 2.0, 0.5, 0.5, labx2)
    if otheryaxis: ppgplot.pgmtxt("R", 3.0, 0.5, 0.5, laby2)
    # Add ID line if required
    if (id==1): ppgplot.pgiden()
    # Let the routines know that we have already prepped the device
    ppgplot_dev_prep_ = 1
Example #45
0
#/usr/bin/env python
#
#  pgex1: freely taken after PGDEMO1.F
#
import ppgplot, numpy
import sys

# create an array 
xs=numpy.array([1.,2.,3.,4.,5.])
ys=numpy.array([1.,4.,9.,16.,25.])

# creat another array
yr = 0.1*numpy.array(range(0,60))
xr = yr*yr


# pgplotting
if len(sys.argv) > 1: # if we got an argument use the argument as devicename
	ppgplot.pgopen(sys.argv[1])
else:
	ppgplot.pgopen('?')
ppgplot.pgenv(0.,10.,0.,20.,0,1)
ppgplot.pglab('(x)', '(y)', 'PGPLOT Example 1:  y = x\u2')
ppgplot.pgpt(xs,ys,9)
ppgplot.pgline(xr,yr)
ppgplot.pgclos()
			sources = daofind(image, fwhm=4.0, threshold=3*bkg_sigma)   
			window.setSourcesAvoidBorders(sources)	
		else: 
			window.setBlankData(image)
		
		
		allWindows.append(window)
		
	(xmin, ymin, xmax, ymax) = determineFullFrameSize(allWindows)
	fullFramexsize = xmax - xmin
	fullFrameysize = ymax - ymin
	
	
	""" Set up the PGPLOT windows """
	xyPositionPlot = {}
	xyPositionPlot['pgplotHandle'] = ppgplot.pgopen('/xs')
	xyPositionPlot['yLimit'] = 1.0
	xyPositionPlot['numXYPanels'] = len(referenceApertures.sources)
	ppgplot.pgpap(6.18, 1.618)
	ppgplot.pgsubp(1, xyPositionPlot['numXYPanels'])
	ppgplot.pgsci(5)
	for panel in range(xyPositionPlot['numXYPanels']):
		currentSize = ppgplot.pgqch()
		ppgplot.pgsch(1)
		yLimit = xyPositionPlot['yLimit']
		ppgplot.pgenv(startFrame, startFrame + frameRange, -yLimit, yLimit, 0, -2)
		ppgplot.pgbox('A', 0.0, 0, 'BCG', 0.0, 0)
		ppgplot.pglab("", "%d"%panel, "")
		ppgplot.pgsch(currentSize)
	
	ppgplot.pgask(False)
Example #47
0
# /usr/bin/env python
#
#  pgex1: freely taken after PGDEMO1.F
#
import ppgplot, Numeric
import sys

# create an array
xs = Numeric.array([1.0, 2.0, 3.0, 4.0, 5.0])
ys = Numeric.array([1.0, 4.0, 9.0, 16.0, 25.0])

# creat another array
yr = 0.1 * Numeric.array(range(0, 60))
xr = yr * yr


# pgplotting
if len(sys.argv) > 1:  # if we got an argument use the argument as devicename
    ppgplot.pgopen(sys.argv[1])
else:
    ppgplot.pgopen("?")
ppgplot.pgenv(0.0, 10.0, 0.0, 20.0, 0, 1)
ppgplot.pglab("(x)", "(y)", "PGPLOT Example 1:  y = x\u2")
ppgplot.pgpt(xs, ys, 9)
ppgplot.pgline(xr, yr)
ppgplot.pgclos()