Example #1
0
def plotsigsff(sig, sf, file, nbin):

    psplot = file + ".ps"
    psplotinit(psplot)
    tot = N.ones(len(sf), 'f')
    (sigbin, sfbin) = my.binitsumequal(sig, sf, nbin)
    (sigbin, totbin) = my.binitsumequal(sig, tot, nbin)
    print sfbin
    print totbin
    (sff, sfferr) = my.ratioerror(sfbin, totbin)
    ppgplot.pgbox("", 0.0, 0, "L", 0.0, 0)
    ymin = -.05
    ymax = 1.05
    xmin = min(sig) - 10.
    #xmax=max(sig)-200.
    xmax = 350.
    ppgplot.pgenv(xmin, xmax, ymin, ymax, 0)
    ppgplot.pglab("\gS\d5\u (gal/Mpc\u2\d)", "Fraction EW([OII])>4 \(2078)",
                  "")
    ppgplot.pgsls(1)  #dotted
    ppgplot.pgslw(4)  #line width
    sig = N.array(sig, 'f')
    sff = N.array(sff, 'f')
    ppgplot.pgsci(2)
    ppgplot.pgline(sigbin, sff)
    ppgplot.pgsci(1)

    ppgplot.pgpt(sigbin, sff, 17)
    my.errory(sigbin, sff, sfferr)
    ppgplot.pgend()
Example #2
0
def plotCircles(objectTable, margins):
    margins = checkMargins(margins)
    ppgplot.pgsci(3)
    ppgplot.pgsfs(2)
    index = 0
    print ("Margins:", margins)
    for obj in objectTable:
        ra = obj["ra"]
        dec = obj["dec"]
        c = obj["class"]
        if ra > margins[1][0] and ra < margins[0][0] and dec < margins[0][1] and dec > margins[1][1]:
            # print index, ra, dec, x, y, c
            index += 1
            colour = 1
            if c == -9:
                colour = 2  # Red  = Saturated
            if c == 1:
                colour = 4  # Blue   = Galaxy
            if c == -3:
                colour = 5  # Cyan   = Probable Galaxy
            if c == -1:
                colour = 3  # Green = Star
            if c == -2:
                colour = 8  # Orange = Probable Star
            if c == 0:
                colour = 2  # Red    = Noise
            ppgplot.pgsci(colour)
            ppgplot.pgcirc(obj["x"], obj["y"], 5 + (5 * obj["pStar"]))
    return index + 1
def getChiSqByParameters(params, *args):
	global iteration, mainPlotWindow, currentPlotWindow, colour, inclination, phase
	print "Params:", params
	beta = params[0]
	log_lambda = params[1]
	scale_factor = params[2]
	linear_offset = params[3]
	print "Args:", args
	temperature = args[0]
	field = args[1]
	
	# cos(theta) = cos(i)cos(beta) - sin(i)sin(beta)cos(phi + pi/2)
	cosTheta = math.cos(radians(inclination)) * math.cos(radians(beta)) - math.sin(radians(inclination)) * math.sin(radians(beta))*math.cos(phase + math.pi/2.)
	angle = math.acos(cosTheta) / math.pi * 180
	print "Angle: %f [deg], Field: %f [MG], Temperature:%f [keV], log_lambda: %f, scale: %f, offset: %f"%(angle, field, temperature, log_lambda, scale_factor, linear_offset)
	model = getSampledModel(observedSpectrum.wavelengths, angle, field, temperature, log_lambda)
	model = [m * scale_factor + linear_offset for m in model]
	chi = computeChiSq(observedSpectrum, model)
	allChiSqs.append(chi)
	print "Chi-squared:", chi
	startWavelength = min(observedSpectrum.wavelengths)
	endWavelength = max(observedSpectrum.wavelengths)
	
	# Draw the most recent iteration
	ppgplot.pgslct(currentPlotWindow)
	ppgplot.pgsci(1)
	ppgplot.pgenv(startWavelength, endWavelength, lowerFlux, upperFlux, 0, 0)
	ppgplot.pgline(observedSpectrum.wavelengths, observedSpectrum.flux)
	ppgplot.pgsci(4)
	ppgplot.pgline(observedSpectrum.wavelengths, model)
	ppgplot.pgsci(1)
	ppgplot.pglab("wavelength", "flux", "Current fit: %d"%iteration)
	
	# Overplot the iteration on the original diagram
	print "overplotting"
	ppgplot.pgslct(mainPlotWindow)
	ppgplot.pgsci(colour)
	ppgplot.pgline(observedSpectrum.wavelengths, model)
	colour += 1
	if colour>15: colour = 1
	ppgplot.pgsci(1)
	
	# Re-generate the Chi-Squared plot
	ppgplot.pgslct(chiSqPlotWindow)
	
	if iteration > 9:
		ppgplot.pgenv(0, iteration+1, 0, max(allChiSqs), 0, 0)
	else:
		ppgplot.pgenv(0, 10, 0, max(allChiSqs), 0, 0)
	iterations = range(iteration+1)
	ppgplot.pgpt(iterations, allChiSqs, 2)
	minCh = min(allChiSqs)
	medCh = numpy.median(allChiSqs)
	maxCh = max(allChiSqs)
	ppgplot.pglab("Iteration [n]", "Chi-squared", "Chi-squared values [%.2f, %.2f, %.2f]"%(minCh, medCh, maxCh))
	
	
	iteration += 1
	return chi
Example #4
0
    def undoSetColour(self):
        try:
            ci = self.previousColours.pop()
        except IndexError:
            ci = None

        if not ci is None:
            pgplot.pgsci(ci)
Example #5
0
    def setColour(self, colour):
        if colour in self.colours.keys():
            ci = self.colours[colour]['ci']
            pgplot.pgsci(ci)
        else:
            try:
                ci = colour
                pgplot.pgsci(ci)
            except:
                raise ex.UnrecognizedChoiceObject(colour)

        self.previousColours.append(ci)
Example #6
0
def resetdefaults():
    """
    resetdefaults():
        Reset global plotting variables to default values.
    """
    global ppgplot_font_, ppgplot_linestyle_, ppgplot_linewidth_, \
           ppgplot_color_, ppgplot_font_size_
    ppgplot.pgscf(ppgplot_font_)
    ppgplot.pgsls(ppgplot_linestyle_)
    ppgplot.pgslw(ppgplot_linewidth_)
    ppgplot.pgsci(ppgplot_colors_[ppgplot_color_])
    ppgplot.pgsch(ppgplot_font_size_)
Example #7
0
def resetdefaults():
    """
    resetdefaults():
        Reset global plotting variables to default values.
    """
    global ppgplot_font_, ppgplot_linestyle_, ppgplot_linewidth_, \
           ppgplot_color_, ppgplot_font_size_
    ppgplot.pgscf(ppgplot_font_)
    ppgplot.pgsls(ppgplot_linestyle_)
    ppgplot.pgslw(ppgplot_linewidth_)
    ppgplot.pgsci(ppgplot_colors_[ppgplot_color_])
    ppgplot.pgsch(ppgplot_font_size_)
Example #8
0
    def terminatePlot(self):
        if not self.plotDeviceIsOpened:
            raise ValueError("You have not yet opened a PGPLOT device.")

        if self._drawBox:
            pgplot.pgsci(1)
            pgplot.pgbox(self._xAxisOptions, 0.0, 0, self._yAxisOptions, 0.0,
                         0)
            pgplot.pglab(self.xLabel, self.yLabel, self.title)

        pgplot.pgend()

        self.plotDeviceIsOpened = False
Example #9
0
def resetdefaults():
    """
    resetdefaults():
        Reset global plotting variables to default values.
    """
    global ppgplot_font_, ppgplot_linestyle_, ppgplot_linewidth_, \
           ppgplot_color_, ppgplot_font_size_
    ppgplot.pgscf(ppgplot_font_)
    ppgplot.pgsls(ppgplot_linestyle_)
    ppgplot.pgslw(ppgplot_linewidth_)
    ppgplot.pgsci(ppgplot_colors_[ppgplot_color_])
    # My little add-on to switch the background to white
    reset_colors()
    ppgplot.pgsch(ppgplot_font_size_)
Example #10
0
def redraw():
    ppgplot.pgslct(imagePlot['pgplotHandle'])
    ppgplot.pgslw(3)
    ppgplot.pggray(boostedImage, xlimits[0], xlimits[1] - 1, ylimits[0],
                   ylimits[1] - 1, imageMinMax[0], imageMinMax[1],
                   imagePlot['pgPlotTransform'])
    if plotSources: plotCircles(dr2Objects, margins)
    if plotHa:
        reduceddr2cat = []
        for selected in extendedHaSources:
            reduceddr2cat.append(dr2Objects[selected])
        plotCircles(reduceddr2cat, margins)
    if plotGrid:
        print("Plotting grid")
        ppgplot.pgsci(6)
        xVals = [p[0] for p in pixelGrid]
        yVals = [p[1] for p in pixelGrid]
        ppgplot.pgpt(xVals, yVals, 2)
    if plotPointings:

        ppgplot.pgsfs(2)
        ppgplot.pgslw(10)
        for p in pointings:
            if p['type'] == "Maximum": ppgplot.pgsci(2)
            if p['type'] == "Minimum": ppgplot.pgsci(4)
            ppgplot.pgcirc(p['x'], p['y'], 30)
        ppgplot.pgslw(1)
    if plotBrightStars:
        ppgplot.pgsci(3)
        ppgplot.pgsfs(2)
        ppgplot.pgslw(10)
        for b in brightStars:
            ppgplot.pgcirc(b['x'], b['y'], 40)
Example #11
0
def plot_selection(id, x0, y0, dt=2.0, w=10.0):
    dx, dy = id.x1 - id.x0, id.y1 - id.y0
    ang = np.arctan2(dy, dx)
    r = np.sqrt(dx**2 + dy**2)
    drdt = r / (id.t1 - id.t0)
    sa, ca = np.sin(ang), np.cos(ang)

    dx = np.array([-dt, -dt, dt, dt, -dt]) * drdt
    dy = np.array([w, -w, -w, w, w])
    x = ca * dx - sa * dy + x0
    y = sa * dx + ca * dy + y0

    ppg.pgsci(7)
    ppg.pgline(x, y)

    return
Example #12
0
def makeplot():
    psplotinit("noise.ps")

    DATAMIN = 0.
    DATAMAX = 15.

    ppgplot.pgbox("", 0.0, 0, "L", 0.0, 0)
    #print "making graph, ncl = ",ncl
    path = os.getcwd()
    f = path.split('/')
    #print path
    #print f
    prefix = f[4]
    title = prefix
    ymin = -.05
    ymax = max(aveaperr) + .1
    #ymax=10.
    ppgplot.pgenv(DATAMIN, DATAMAX, ymin, ymax, 0)
    ppgplot.pglab("linear size N of aperture (pixel)", "rms in Sky (ADU/s)",
                  title)
    ppgplot.pgsci(2)  #red
    ppgplot.pgslw(4)  #line width
    x = N.sqrt(avearea)
    y = aveaperr
    ppgplot.pgpt(x, y, 7)
    #errory(x,y,erry)
    ppgplot.pgsci(1)  #black
    #ppgplot.pgpt(isoarea,fluxerriso,3)
    #x1=N.sqrt(contsubisoarea)
    #y1=contsuberr

    #x1=N.sqrt(isoarea)
    #y1=fluxerriso
    #y=n*y1

    #ppgplot.pgpt(x1,y1,1)
    #ppgplot.pgsci(4)#blue
    #ppgplot.pgpt(x1,y,1)
    #ppgplot.pgsci(1)#black
    x = N.arange(0, 50, 1)
    y = x * (a + b * a * x)
    #y=N.sqrt(x)*.02
    ppgplot.pgline(x, y)
    #errory(x,y,erry)

    ppgplot.pgend()
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 #14
0
    def plot_horizontal_grid(self):
        sch, sls, sci = ppgplot.pgqch(), ppgplot.pgqls(), ppgplot.pgqci()

        ppgplot.pgsci(15)
        ppgplot.pgsls(2)

        # Altitudes
        for alt in np.arange(0.0, 90.0, 20.0):
            az = np.arange(0.0, 360.0)
            rx, ry = forward(self.az, self.alt, az, alt * np.ones_like(az))
            for i in range(len(rx)):
                if i == 0:
                    ppgplot.pgmove(rx[i], ry[i])
                if (np.abs(rx[i]) <= 1.5 * self.w) & (np.abs(ry[i]) <= self.w):
                    ppgplot.pgdraw(rx[i], ry[i])
                else:
                    ppgplot.pgmove(rx[i], ry[i])

        # Azimuths
        for az in np.arange(0.0, 360.0, 30.0):
            alt = np.arange(0.0, 80.0)
            rx, ry = forward(self.az, self.alt, az * np.ones_like(alt), alt)
            for i in range(len(rx)):
                if i == 0:
                    ppgplot.pgmove(rx[i], ry[i])
                if (np.abs(rx[i]) <= 1.5 * self.w) & (np.abs(ry[i]) <= self.w):
                    ppgplot.pgdraw(rx[i], ry[i])
                else:
                    ppgplot.pgmove(rx[i], ry[i])
        ppgplot.pgsci(1)
        ppgplot.pgsls(1)

        # Horizon
        az = np.arange(0.0, 360.0)
        rx, ry = forward(self.az, self.alt, az, np.zeros_like(az))
        for i in range(len(rx)):
            if i == 0:
                ppgplot.pgmove(rx[i], ry[i])
            if (np.abs(rx[i]) <= 1.5 * self.w) & (np.abs(ry[i]) <= self.w):
                ppgplot.pgdraw(rx[i], ry[i])
            else:
                ppgplot.pgmove(rx[i], ry[i])
Example #15
0
def compdiff(x, y, xlabel, ylabel):
    xmax = max(x)
    xmin = min(x)
    ymax = max(y)
    ymin = min(y)
    ave = N.average(N.compress((x < 21) & (im1.sn > 3), y))
    std = scipy.stats.std(N.compress((x < 21) & (im1.sn > 3), y))
    ppgplot.pgbox("", 0.0, 0, "", 0.0, 0)
    ppgplot.pgenv(xmin, xmax, -.8, .8, 0)
    ppgplot.pglab(xlabel, ylabel, "")
    ppgplot.pgpt(x, y, 3)
    x = N.arange((int(xmin) - 1), (int(xmax) + 2), 1)
    y = ave * x / x
    ppgplot.pgsci(2)
    ppgplot.pgline(x, y)
    ppgplot.pgsci(1)
    y1 = y - std
    ppgplot.pgline(x, y1)
    y1 = y + std
    ppgplot.pgline(x, y1)
Example #16
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 #17
0
def plotsigo2(sig, o2, file, nbin):

    psplot = file + ".ps"
    psplotinit(psplot)
    (sigbin, o2bin) = my.binit(sig, o2, nbin)
    ppgplot.pgbox("", 0.0, 0, "L", 0.0, 0)
    ymin = -10.
    ymax = 2.
    xmin = min(sig) - 10.
    #xmax=max(sig)-200.
    xmax = 350.
    ppgplot.pgenv(xmin, xmax, ymin, ymax, 0)
    ppgplot.pglab("\gS\d5\u (gal/Mpc\u2\d)", "EW([OII]) (\(2078))", "")
    ppgplot.pgsls(1)  #dotted
    ppgplot.pgslw(4)  #line width
    sig = N.array(sig, 'f')
    o2 = N.array(o2, 'f')
    ppgplot.pgpt(sig, o2, 1)
    ppgplot.pgsci(2)
    ppgplot.pgline(sigbin, o2bin)
    ppgplot.pgsci(1)
    ppgplot.pgend()
Example #18
0
 def drawLegend(self,
                listOfStyles,
                listOfColours,
                listOfTexts,
                fracHeight=0.25,
                isLeft=True,
                isUp=True):
     # if style is None just draw a line segment.
     numTexts = len(listOfTexts)
     x0 = self.xFracToWorld(0.02)
     x1 = self.xFracToWorld(0.025)
     x2 = self.xFracToWorld(0.03)
     for i in range(numTexts):
         yFrac = 1.0 - fracHeight * ((numTexts - i - 0.5) / float(numTexts))
         y = self.yFracToWorld(yFrac)
         self.setColour(listOfColours[i])
         if listOfStyles[i] is None:
             self.drawLine(x0, y, x1, y)
         else:
             self.drawPoint(0.5 * (x0 + x1), y, listOfStyles[i])
         pgplot.pgsci(1)
         pgplot.pgptxt(x2, y, 0.0, 0.0, listOfTexts[i])
Example #19
0
def plotCircles(objectTable, margins):
    margins = checkMargins(margins)
    ppgplot.pgsci(3)
    ppgplot.pgsfs(2)
    index = 0
    print("Margins:", margins)
    for obj in objectTable:
        ra = obj['ra']
        dec = obj['dec']
        c = obj['class']
        if ra > margins[1][0] and ra < margins[0][0] and dec < margins[0][
                1] and dec > margins[1][1]:
            # print index, ra, dec, x, y, c
            index += 1
            colour = 1
            if c == -9: colour = 2  # Red  = Saturated
            if c == 1: colour = 4  # Blue   = Galaxy
            if c == -3: colour = 5  # Cyan   = Probable Galaxy
            if c == -1: colour = 3  # Green = Star
            if c == -2: colour = 8  # Orange = Probable Star
            if c == 0: colour = 2  # Red    = Noise
            ppgplot.pgsci(colour)
            ppgplot.pgcirc(obj['x'], obj['y'], 5 + (5 * obj['pStar']))
    return (index + 1)
Example #20
0
def plotsig10sffall(sigspec, sigphot, sf, file, nbin):

    psplot = file + ".ps"
    psplotinit(psplot)
    ppgplot.pgbox("", 0.0, 0, "L", 0.0, 0)
    ymin = -.01
    ymax = 1.01
    #xmin=min(sigspec)-10.
    #xmax=max(sig)-200.
    #xmax=400.
    xmin = -1.
    xmax = 2.7
    ppgplot.pgenv(xmin, xmax, ymin, ymax, 0, 10)
    ppgplot.pglab("\gS\d10\u (gal/Mpc\u2\d)", "Fraction EW([OII])>4 \(2078)",
                  "")
    ppgplot.pgsls(1)  #dotted
    ppgplot.pgslw(4)  #line width
    tot = N.ones(len(sf), 'f')
    (sigbin, sfbin) = my.binitsumequal(sigspec, sf, nbin)
    (sigbin, totbin) = my.binitsumequal(sigspec, tot, nbin)
    (sff, sfferr) = my.ratioerror(sfbin, totbin)
    #sig=N.array(sig,'f')
    #sff=N.array(sff,'f')
    ppgplot.pgsci(2)
    sigbin = N.log10(sigbin)
    ppgplot.pgline(sigbin, sff)
    ppgplot.pgsci(1)

    ppgplot.pgpt(sigbin, sff, 17)
    my.errory(sigbin, sff, sfferr)

    (sigbin, sfbin) = my.binitsumequal(sigphot, sf, nbin)
    (sigbin, totbin) = my.binitsumequal(sigphot, tot, nbin)
    (sff, sfferr) = my.ratioerror(sfbin, totbin)
    #sig=N.array(sig,'f')
    #sff=N.array(sff,'f')
    ppgplot.pgslw(4)  #line width
    ppgplot.pgsci(4)
    sigbin = N.log10(sigbin)
    ppgplot.pgline(sigbin, sff)
    ppgplot.pgsci(1)

    ppgplot.pgpt(sigbin, sff, 21)
    #my.errory(sigbin,sff,sfferr)
    ppgplot.pgend()
Example #21
0
def plotsighaall(sig, psig, o2b, file, nbin):
    o2b = N.array(o2b, 'f')
    sig = N.array(sig, 'f')
    psig = N.array(psig, 'f')
    #o2b=o2b+4.
    o2 = N.compress(o2b > -500., o2b)
    sig = N.compress(o2b > -500., sig)
    psig = N.compress(o2b > -500., psig)

    psplot = file + ".ps"
    psplotinit(psplot)
    #ppgplot.pgsch(0.7)
    ppgplot.pgslw(7)
    (sigbin, o2bin) = my.binit(sig, o2, nbin)
    #print 'dude', sigbin, o2bin
    sigbin = N.log10(sigbin)
    ppgplot.pgswin(-2., 2., -5., 20.)
    ppgplot.pgbox('blcnst', 0.0, 0.0, 'bcvnst', 0.0,
                  0.0)  #tickmarks and labeling
    ppgplot.pgsch(1.0)
    ppgplot.pgmtxt('b', 2.5, 0.5, 0.5, "\gS\d10\u (gal/Mpc\u2\d)")  #xlabel
    ppgplot.pgsch(1.2)
    ppgplot.pgmtxt('l', 2.6, 0.5, 0.5, 'EW(H\ga) (\(2078))')

    ppgplot.pgsls(1)  #dotted
    ppgplot.pgslw(4)  #line width

    ppgplot.pgpt(sigbin, o2bin, 17)
    ppgplot.pgpt(N.log10(sig), o2, 1)
    #my.errory(sigbin,o2bin,yerr)
    #print 'dude2', sigbin, o2bin
    ppgplot.pgsci(2)
    ppgplot.pgline(sigbin, o2bin)
    (sigbin, o2bin) = my.binit(psig, o2, nbin)

    #print 'dude', sigbin, o2bin
    sigbin = N.log10(sigbin)
    ppgplot.pgsci(1)
    ppgplot.pgpt(sigbin, o2bin, 21)
    #my.errory(sigbin,o2bin,yerr)
    ppgplot.pgsci(4)
    ppgplot.pgline(sigbin, o2bin)
    ppgplot.pgsci(1)
    ppgplot.pgend()
Example #22
0
def redraw():
    ppgplot.pgslct(imagePlot["pgplotHandle"])
    ppgplot.pgslw(3)
    ppgplot.pggray(
        boostedImage,
        xlimits[0],
        xlimits[1] - 1,
        ylimits[0],
        ylimits[1] - 1,
        imageMinMax[0],
        imageMinMax[1],
        imagePlot["pgPlotTransform"],
    )
    if plotSources:
        plotCircles(dr2Objects, margins)
    if plotHa:
        reduceddr2cat = []
        for selected in extendedHaSources:
            reduceddr2cat.append(dr2Objects[selected])
        plotCircles(reduceddr2cat, margins)
    if plotGrid:
        print ("Plotting grid")
        ppgplot.pgsci(6)
        xVals = [p[0] for p in pixelGrid]
        yVals = [p[1] for p in pixelGrid]
        ppgplot.pgpt(xVals, yVals, 2)
    if plotPointings:

        ppgplot.pgsfs(2)
        ppgplot.pgslw(10)
        for p in pointings:
            if p["type"] == "Maximum":
                ppgplot.pgsci(2)
            if p["type"] == "Minimum":
                ppgplot.pgsci(4)
            ppgplot.pgcirc(p["x"], p["y"], 30)
        ppgplot.pgslw(1)
    if plotBrightStars:
        ppgplot.pgsci(3)
        ppgplot.pgsfs(2)
        ppgplot.pgslw(10)
        for b in brightStars:
            ppgplot.pgcirc(b["x"], b["y"], 40)
Example #23
0
def plotsigo2all(sig, psig, o2b, file, nbin):
    #o2=N.zeros(len(o2b),'f')
    #for i in range(len(o2b)):
    #print i, sig[i], psig[i], o2b[i]
    #    if o2b[i] < 0:

    #        o2[i]=-1*o2b[i]
    #print "hey", o2[i]
    o2 = o2b
    psplot = file + ".ps"
    psplotinit(psplot)
    ppgplot.pgsch(0.7)
    (sigbin, o2bin) = my.binit(sig, o2, nbin)
    #print 'dude', sigbin, o2bin
    sigbin = N.log10(sigbin)
    ppgplot.pgswin(-1., 3., -.5, 10.)
    ppgplot.pgbox('bcnst', 0.0, 0.0, 'bcvnst', 0.0,
                  0.0)  #tickmarks and labeling
    ppgplot.pgsch(1.0)
    ppgplot.pgmtxt('b', 2.5, 0.5, 0.5, "\gS\d10\u (gal/Mpc\u2\d)")  #xlabel
    ppgplot.pgsch(1.2)
    ppgplot.pgmtxt('l', 2.6, 0.5, 0.5, 'EW([OII]) (\(2078))')

    ppgplot.pgsls(1)  #dotted
    ppgplot.pgslw(4)  #line width
    ppgplot.pgsci(2)
    ppgplot.pgpt(sigbin, o2bin, 17)
    #print 'dude2', sigbin, o2bin
    ppgplot.pgline(sigbin, o2bin)
    (sigbin, o2bin) = my.binit(psig, o2, nbin)
    #print 'dude', sigbin, o2bin
    sigbin = N.log10(sigbin)
    ppgplot.pgsci(4)
    ppgplot.pgpt(sigbin, o2bin, 21)
    ppgplot.pgline(sigbin, o2bin)
    ppgplot.pgsci(1)
    ppgplot.pgend()
Example #24
0
def main(options):

    global keepPlotting
    keepPlotting = True
    debug = options.debug
    inputMS = options.inms
    if inputMS == "":
        print "Error: You must specify a MS name."
        print '       Use "uvplot.py -h" to get help.'
        return

    if inputMS.endswith("/"):
        inputMS = inputMS[:-1]
    inputMSbasename = inputMS.split("/")[-1]
    if inputMSbasename == "":
        # The user has not specified the full path of the MS
        inputMSbasename = inputMS

    device = options.device
    if device == "?":
        ppgplot.pgldev()
        return
    xaxis = options.xaxis
    yaxis = options.yaxis
    column = options.column
    nx, ny = options.nxy.split(",")
    axlimits = options.axlimits.split(",")
    if len(axlimits) == 4:
        xmin, xmax, ymin, ymax = axlimits
    else:
        print "Error: You must specify four axis limits"
        return
    showFlags = options.flag
    flagCol = options.colflag
    showAutocorr = options.autocorr
    showStats = options.statistics
    timeslots = options.timeslots.split(",")
    if len(timeslots) != 2:
        print "Error: Timeslots format is start,end"
        return
    for i in range(len(timeslots)):
        timeslots[i] = int(timeslots[i])
    antToPlotSpl = options.antennas.split(",")
    antToPlot = []
    for i in range(len(antToPlotSpl)):
        tmpspl = antToPlotSpl[i].split("..")
        if len(tmpspl) == 1:
            antToPlot.append(int(antToPlotSpl[i]))
        elif len(tmpspl) == 2:
            for j in range(int(tmpspl[0]), int(tmpspl[1]) + 1):
                antToPlot.append(j)
        else:
            print "Error: Could not understand antenna list."
            return
    polarizations = options.polar.split(",")
    for i in range(len(polarizations)):
        polarizations[i] = int(polarizations[i])

    convertStokes = options.stokes

    operation = options.operation
    if operation != "":
        operation = int(operation)
        if convertStokes:
            print "Error: Stokes conversion is not compatible with special operations"
            return

    channels = options.channels.split(",")
    if len(channels) != 2:
        print "Error: Channels format is start,end"
        return
    for i in range(len(channels)):
        channels[i] = int(channels[i])
    if channels[1] == -1:
        channels[1] = None  # last element even if there is only one
    else:
        channels[1] += 1
    queryMode = options.query
    doUnwrap = options.wrap

    if not queryMode:
        # open the graphics device, use the right number of panels
        ppgplot.pgbeg(device, int(nx), int(ny))
        # set the font size
        ppgplot.pgsch(1.5)
        ppgplot.pgvstd()

    # open the main table and print some info about the MS
    t = pt.table(inputMS, readonly=True, ack=False)
    firstTime = t.getcell("TIME", 0)
    lastTime = t.getcell("TIME", t.nrows() - 1)
    intTime = t.getcell("INTERVAL", 0)
    print "Integration time:\t%f sec" % (intTime)
    nTimeslots = (lastTime - firstTime) / intTime
    if timeslots[1] == -1:
        timeslots[1] = nTimeslots
    else:
        timeslots[1] += 1
    print "Number of timeslots:\t%d" % (nTimeslots)
    # open the antenna and spectral window subtables
    tant = pt.table(t.getkeyword("ANTENNA"), readonly=True, ack=False)
    tsp = pt.table(t.getkeyword("SPECTRAL_WINDOW"), readonly=True, ack=False)
    numChannels = len(tsp.getcell("CHAN_FREQ", 0))
    print "Number of channels:\t%d" % (numChannels)
    print "Reference frequency:\t%5.2f MHz" % (tsp.getcell("REF_FREQUENCY", 0) / 1.0e6)

    # Station names
    antList = tant.getcol("NAME")
    if len(antToPlot) == 1 and antToPlot[0] == -1:
        antToPlot = range(len(antList))
    print "Station list (only starred stations will be plotted):"
    for i in range(len(antList)):
        star = " "
        if i in antToPlot:
            star = "*"
        print "%s %2d\t%s" % (star, i, antList[i])

    # Bail if we're in query mode
    if queryMode:
        return

    # select by time from the beginning, and only use specified antennas
    tsel = t.query(
        "TIME >= %f AND TIME <= %f AND ANTENNA1 IN %s AND ANTENNA2 IN %s"
        % (firstTime + timeslots[0] * intTime, firstTime + timeslots[1] * intTime, str(antToPlot), str(antToPlot))
    )

    # values to use for each polarization
    plotColors = [1, 2, 3, 4]
    labXPositions = [0.35, 0.45, 0.55, 0.65]
    labYPositions = [1.0, 1.0, 1.0, 1.0]
    if convertStokes:
        polLabels = ["I", "Q", "U", "V"]
    else:
        polLabels = ["XX", "XY", "YX", "YY"]

    # define nicely written axis labels
    axisLabels = {
        "time": "Time",
        "chan": "Channel",
        "freq": "Frequency [MHz]",
        "amp": "Visibility amplitude",
        "real": "Real part of visibility",
        "imag": "Imaginary part of visibility",
        "phase": "Visibility phase [radians]",
    }

    # Now we loop through the baselines
    ppgplot.pgpage()
    for tpart in tsel.iter(["ANTENNA1", "ANTENNA2"]):
        if not keepPlotting:
            return
        ant1 = tpart.getcell("ANTENNA1", 0)
        ant2 = tpart.getcell("ANTENNA2", 0)
        if ant1 not in antToPlot or ant2 not in antToPlot:
            continue
        if ant1 == ant2:
            if not showAutocorr:
                continue
        # Get the values to plot, strategy depends on axis type
        if xaxis == "time":
            xaxisvals = getXAxisVals(tpart, xaxis, channels)
            yaxisvals = getYAxisVals(
                tpart, yaxis, column, operation, showFlags, flagCol, channels, doUnwrap, convertStokes
            )
        else:
            xaxisvals = getXAxisVals(tsp, xaxis, channels)
            yaxisvals = getYAxisVals(
                tpart, yaxis, column, operation, showFlags, flagCol, channels, doUnwrap, convertStokes, xaxistype=1
            )
        if xaxisvals == None:  # This baseline must be empty, go to next one
            print "No good data on baseline %s - %s" % (antList[ant1], antList[ant2])
            continue

        if debug:
            print xaxisvals.shape
            print yaxisvals.shape
            for r in range(len(xaxisvals)):
                print "%s" % yaxisvals[r]
        if len(xaxisvals) != len(yaxisvals):  # something is wrong
            print "Error: X and Y axis types incompatible"
            return

        # Plot the data, each polarization in a different color
        ppgplot.pgsci(1)
        if xmin == "":
            minx = xaxisvals.min()
        else:
            minx = float(xmin)
        if xmax == "":
            maxx = xaxisvals.max()
        else:
            maxx = float(xmax)
        if ymin == "":
            miny = yaxisvals.min()
            if numpy.ma.getmaskarray(yaxisvals.min()):
                print "All data flagged on baseline %s - %s" % (antList[ant1], antList[ant2])
                continue
        else:
            miny = float(ymin)
        if ymax == "":
            maxy = yaxisvals.max()
        else:
            maxy = float(ymax)
        if minx == maxx:
            minx -= 1.0
            maxx += 1.0
        else:
            diffx = maxx - minx
            minx -= 0.02 * diffx
            maxx += 0.02 * diffx
        if miny == maxy:
            miny -= 1.0
            maxy += 1.0
        else:
            diffy = maxy - miny
            miny -= 0.02 * diffy
            maxy += 0.02 * diffy
        # ppgplot.pgpage()
        ppgplot.pgswin(minx, maxx, miny, maxy)
        if xaxis == "time":
            ppgplot.pgtbox("ZHOBCNST", 0.0, 0, "BCNST", 0.0, 0)
        else:
            ppgplot.pgbox("BCNST", 0.0, 0, "BCNST", 0.0, 0)

        # ppgplot.pglab(axisLabels[xaxis], axisLabels[yaxis], '%s - %s'%(antList[ant1],antList[ant2]))
        # ppgplot.pgmtxt('T', 3.0, 0.5, 0.5, inputMSbasename)

        ppgplot.pglab(
            axisLabels[xaxis],
            axisLabels[yaxis],
            inputMSbasename + "(" + getDataDescription(column) + "): %s - %s" % (antList[ant1], antList[ant2]),
        )

        if operation != 0:
            # some operations is defined
            if operation == 1:
                label = "XX-YY"
            elif operation == 2:
                label = "XY.YX*"
            else:
                print "Special operation not defined"
                return

            ppgplot.pgsci(plotColors[0])
            tmpvals = yaxisvals
            print "Baseline", antList[ant1], "-", antList[ant2], ": Plotting", len(
                tmpvals[~tmpvals.mask]
            ), "points of " + label
            ppgplot.pgpt(xaxisvals[~tmpvals.mask], tmpvals[~tmpvals.mask], 1)

            addInfo(showStats, tmpvals[~tmpvals.mask], label, labXPositions[1], labYPositions[1])
        else:
            for j in polarizations:
                ppgplot.pgsci(plotColors[j])
                tmpvals = yaxisvals[:, j]
                if j == polarizations[0]:
                    print "Baseline", antList[ant1], "-", antList[ant2], ": Plotting", len(
                        tmpvals[~tmpvals.mask]
                    ), "points per polarization"
                ppgplot.pgpt(xaxisvals[~tmpvals.mask], tmpvals[~tmpvals.mask], 1)

                addInfo(showStats, tmpvals[~tmpvals.mask], polLabels[j], labXPositions[j], labYPositions[j])
        ppgplot.pgpage()

    # Close the PGPLOT device
    ppgplot.pgclos()
Example #25
0
	positionString = generalUtils.toSexagesimal((ra, dec))
	print "RA, DEC of image centre is: ", positionString, ra, dec
	margins = wcsSolution.all_pix2world([[0, 0], [width, height]], 1)
	margins = checkMargins(margins)
	print "ra, dec limits:", margins
	
	xlimits = (0, width)
	ylimits = (0, height)
		
		
	# try: 
	x=width/2
	y=height/2
	newWidth = width
	newHeight = height
	ppgplot.pgsci(3)
	keyPressed = None
	while keyPressed != 'q':
		ch = ppgplot.pgcurs(x, y)
		x=ch[0]
		y=ch[1]
		keyPressed = ch[2]
		# print "Key pressed:", ch[2]
			
		if keyPressed== 'w':
			imageMinMax = (imageMinMax[1], imageMinMax[0])
			if invertedColours: invertedColours= False
			else: invertedColours=True
			redraw()
			
		if keyPressed=='i':
Example #26
0
def plotxy(y, x=None, title=None, rangex=None, rangey=None, \
           labx='', laby='', rangex2=None, rangey2=None, \
           labx2='', laby2='', symbol=ppgplot_symbol_, \
           line=ppgplot_linestyle_, width=ppgplot_linewidth_, \
           color=ppgplot_color_, font=ppgplot_font_, logx=0, logy=0, \
           logx2=0, logy2=0, errx=None, erry=None, id=0, noscale=0, \
           aspect=0.7727, fontsize=ppgplot_font_size_, ticks='in', \
           panels=[1,1], device=ppgplot_device_, setup=1):
    """
    plotxy(y, ...)
        An interface to make various XY style plots using PGPLOT.
            'y' is the 1D sequence object to plot.
        The optional entries are:
            x:        x values                  (default = 0, 1, ...)
            title:    graph title               (default = None)   
            rangex:   ranges for the x-axis     (default = automatic)
            rangey:   ranges for the y-axis     (default = automatic)
            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))
            errx:     symmetric x errors        (default = None)   
            erry:     symmetric y errors        (default = None)   
            symbol:   symbol for points         (default = None)   
            line:     line style                (default = 1 (solid))
            width:    line width                (default = 1 (thin))
            color:    line and/or symbol color  (default = 'white')
            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)) 
            noscale:  turn off auto scaling     (default = 0 (no)) 
            aspect:   aspect ratio              (default = 0.7727 (rect))
            ticks:    Ticks point in or out     (default = 'in')   
            panels:   Number of subpanels [r,c] (default = [1,1])
            device:   PGPLOT device to use      (default = '/XWIN')
            setup:    Auto-setup the plot       (default = 1)
        Note:  Many default values are defined in global variables
            with names like ppgplot_font_ or ppgplot_device_.
    """
    # Make sure the input data is an array
    y = Num.asarray(y);
    # Announce the global variables we will be using
    global ppgplot_dev_open_, ppgplot_dev_prep_, ppgplot_colors_
    # Define the X axis limits if needed
    if x is None: x=Num.arange(len(y), dtype='f')
    else: x = Num.asarray(x)
    # Determine the scaling to use for the first axis
    if rangex is None: rangex=[x.min(), x.max()]
    if rangey is None:
        if noscale: rangey=[y.min(), y.max()]
        else: rangey=scalerange(y)
    # Prep the plotting device...
    if (not ppgplot_dev_prep_ and setup):
	prepplot(rangex, rangey, title, labx, laby, \
                 rangex2, rangey2, labx2, laby2, \
                 logx, logy, logx2, logy2, font, fontsize, \
                 id, aspect, ticks, panels, device=device)
    # Choose the line color
    if type(color) == types.StringType:
        ppgplot.pgsci(ppgplot_colors_[color])
    else:
        ppgplot.pgsci(color)
    # Plot symbols (and errors) if requested
    if not symbol is None:
        ppgplot.pgpt(x, y, symbol)
    # Error bars
    if errx is not None:
        if not logx:
            errx = Num.asarray(errx)
	    if errx.size == 1:
		errx = errx.repeat(x.size)
	    #ppgplot.pgerrx(x+errx, x-errx, y, 1.0)
	    ppgplot.pgerrb(5, x, y, errx, 1.0)
        else:
            errx = 10.0**Num.asarray(errx)
	    if errx.size == 1:
		errx = errx.repeat(x.size)
	    #ppgplot.pgerrx(Num.log10(10.0**x + errx),
            #               Num.log10(10.0**x - errx), y, 1.0)
	    ppgplot.pgerrb(5, x, y, Num.log10(errx), 1.0)
    if erry is not None:
        if not logy:
            erry = Num.asarray(erry)
	    if erry.size == 1:
		erry = erry.repeat(y.size)
	    #ppgplot.pgerry(x, y+erry, y-erry, 1.0)
	    ppgplot.pgerrb(6, x, y, erry, 1.0)
        else:
            erry = 10.0**Num.asarray(erry)
	    if erry.size == 1:
		erry = erry.repeat(y.size)
	    #ppgplot.pgerry(x, Num.log10(10.0**y + erry),
            #               Num.log10(10.0**y - erry), 1.0)
	    ppgplot.pgerrb(6, x, y, Num.log10(erry), 1.0)
    # Plot connecting lines if requested
    if not line is None:
        # Choose the line style
        ppgplot.pgsls(line)
        # Choose the line width
        ppgplot.pgslw(width)
        ppgplot.pgline(x, y)
					boostedImage = ultracamutils.percentiles(w.data, 20, 99)
				xll = w.xll/w.xbin - xmin
				xsize = w.nx
				yll = w.yll/w.ybin - ymin
				ysize = w.ny
				fullFrame[yll:yll+ysize, xll:xll+xsize] = fullFrame[yll:yll+ysize, xll:xll+xsize] + boostedImage		
			
			dimensions = numpy.shape(fullFrame)
			rows = dimensions[0]
			cols = dimensions[1]

			# Draw the grayscale bitmap
			ppgplot.pggray(fullFrame, 0, cols-1 , 0, rows-1 , 0, 255, pgPlotTransform)
	
			# Draw the full reference aperture list
			ppgplot.pgsci(3)
			for s in sourceList.getSources():
				(x, y) = s.abs_position
				ppgplot.pgcirc(x, y, 10)
		
		margins = 10
		
		if arg.preview: 
			ppgplot.pgslct(bitmapView)
			ppgplot.pgsci(2)
			
		plotColour = [1, 2, 3, 4, 5, 6]
		for index, s in enumerate(referenceApertures.getSources()):
			window = allWindows[s.windowIndex]
			center = s.latestPosition
			xcenterInt = int(center[0])
Example #28
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 #29
0
ppgplot.pgtext(7.2,0.88,"twib_hour")
ppgplot.pgtext(7.55,0.88,"twib_min")


t_lmstmidn = hour + min/60 + sec/3600
twie_dn = twie_hour - 24 + twie_min/60 
twib_dn = twib_hour + twib_min/60 

ss_dn = ss_hour - 24 + ss_min/60 
sr_dn = sr_hour + sr_min/60 

# SHADE Twilight zone
#####################################################################
ppgplot.pgsfs(1)

ppgplot.pgsci(6) 
ppgplot.pgrect(t_min, twie_dn, a_min, a_max) 
ppgplot.pgrect(twib_dn, t_max,  a_min, a_max) 

ppgplot.pgsci(12)
ppgplot.pgrect(t_min, ss_dn, a_min, a_max) 
ppgplot.pgrect(sr_dn, t_max,  a_min, a_max) 

ppgplot.pgsci(1)

# Read (RA,DEC) FROM OBJECT LIST
############################################################
open(FILE, "filename") || die ("cannot open filename")
n=0

while(line=<FILE>) {
Example #30
0
def plot2d(z, x=None, y=None, title=None, rangex=None, rangey=None, \
           rangez=None, labx='', laby='', rangex2=None, rangey2=None, \
           labx2='', laby2='', image=ppgplot_palette_, contours=None, \
           logx=0, logy=0, logx2=0, logy2=0, \
           line=ppgplot_linestyle_, width=ppgplot_linewidth_, \
           color=ppgplot_color_, labels=ppgplot_labels_, \
           labelint=ppgplot_labelint_, labelmin=ppgplot_labelmin_, \
           font=ppgplot_font_, id=0, noscale=0, aspect=1, \
           fontsize=ppgplot_font_size_, ticks='out', panels=[1,1], \
           device=ppgplot_device_):
    """
    plot2d(z, ...)
        An interface to make various 2D plots using PGPLOT.
            'z' is the 2D Numpy array to be plotted.
        The optional entries are:
            x:         x values                    (default = 0, 1, ...) 
            y:         y values                    (default = 0, 1, ...) 
            title:     graph title                 (default = None)      
            rangex:    range for the x-axis        (default = automatic) 
            rangey:    range for the y-axis        (default = automatic) 
            rangez:    range for the z-axis        (default = automatic) 
            labx:      label for the x-axis        (default = None)      
            laby:      label for the y-axis        (default = None)      
            rangex2:   range for 2nd x-axis        (default = None)      
            rangey2:   range 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))
            image:     color palette for image     (default = 'rainbow') 
            contours:  list of contour values      (default = None)      
            line:      contour line style          (default = 1 (solid)) 
            width:     contour line width          (default = 1 (thin))  
            color:     contour line color          (default = 'white')   
            labels:    color of contour labels     (default = None)      
            labelint:  contour label spacing       (default = 20)        
            labelmin:  min contour label spacing   (default = 20)        
            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))    
            noscale:   turn off auto scaling       (default = 0 (no))    
            aspect:    Aspect ratio                (default = 1 (square))
            ticks:     Ticks point in or out       (default = 'out')   
            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_.
    """
    # Make sure the input data is a 2D array
    z = Num.asarray(z)
    if not len(z.shape) == 2:
        print 'Input data array must be 2 dimensional.'
        return
    # Announce the global variables we will be using
    global ppgplot_dev_open_, ppgplot_dev_prep_, pgpalette
    # Define the X and Y axis limits if needed
    if x is None: x = Num.arange(z.shape[1], dtype='f')
    else: x = Num.asarray(x)
    if y is None: y = Num.arange(z.shape[0], dtype='f')
    else: y = Num.asarray(y)
    # Determine the scaling to use for the axes
    if rangex is None:
        dx = x[-1] - x[-2]
        rangex = [x[0], x[-1] + dx]
    if rangey is None:
        dy = y[-1] - y[-2]
        rangey = [y[0], y[-1] + dy]
    if rangez is None:        rangez=[Num.minimum.reduce(Num.ravel(z)), \
              Num.maximum.reduce(Num.ravel(z))]
    # Prep the plotting device...
    if (not ppgplot_dev_prep_):
        prepplot(rangex, rangey, title, labx, laby, \
                 rangex2, rangey2, labx2, laby2, logx, logy, \
                 logx2, logy2, font, fontsize, id, aspect, \
                 ticks, panels, device=device)
    if image is not None:
        # Set the color indices and the color table
        lo_col_ind, hi_col_ind = ppgplot.pgqcol()
        lo_col_ind = lo_col_ind + 2
        ppgplot.pgscir(lo_col_ind, hi_col_ind)
        pgpalette.setpalette(image)
        ppgplot.pgctab(pgpalette.l, pgpalette.r, pgpalette.g, pgpalette.b)
        # Construct the image
        ppgplot.pgimag_s(z, 0.0, 0.0, rangex[0], rangey[0], \
                         rangex[1], rangey[1])
        reset_colors()
    if contours is not None:
        contours = Num.asarray(contours)
        # Choose the line style
        ppgplot.pgsls(line)
        # Choose the line width
        ppgplot.pgslw(width)
        # Choose the line color for the contourlines
        if type(color) == types.StringType:
            ppgplot.pgsci(ppgplot_colors_[color])
        else:
            ppgplot.pgsci(color)
        # Construct the contours
        ppgplot.pgcont_s(z, len(contours), contours, rangex[0], \
                         rangey[0], rangex[1], rangey[1])
        # Label the contours if requested
        if labels is not None:
            # Choose the line color for the contourlines
            if type(labels) == types.StringType:
                ppgplot.pgsci(ppgplot_colors_[labels])
            else:
                ppgplot.pgsci(labels)
            for i in range(len(contours)):
                ppgplot.pgconl_s(z, contours[i], str(contours[i]), labelint,
                                 labelmin)
Example #31
0
 helpItem = {'key': "i/o", 'text': "Zoom in/out."}
 help.append(helpItem)
 helpItem = {'key': "q", 'text': "Quit."}
 help.append(helpItem)
 helpItem = {'key': "f", 'text': "Find local Ha maxima."}
 help.append(helpItem)
 helpItem = {'key': "l", 'text': "Show location of cursor."}
 help.append(helpItem)
 # try:
 x = width / 2
 y = height / 2
 newWidth = width
 newHeight = height
 # pixelGrid = makeGrid(width, height, 100)
 originalImageData = numpy.copy(imageData)
 ppgplot.pgsci(3)
 keyPressed = None
 while keyPressed != 'q':
     ch = ppgplot.pgcurs(x, y)
     x = ch[0]
     y = ch[1]
     keyPressed = ch[2]
     # print "Key pressed:", ch[2]
     if keyPressed == '?':
         print("Help:")
         for helpItem in help:
             print("\t" + helpItem['key'] + " : " + helpItem['text'])
         print("")
     if keyPressed == 'p':
         if plotSources == True:
             plotSources = False
Example #32
0
def plotold():
    xmin=2.2
    xmax=3.2
    ymin=-2.5
    ymax=-.5
    psplotinit('fSsigma3Gyr.ps')
    ppgplot.pgbox("",0.0,0,"",0.0,0)
    ppgplot.pgenv(xmin,xmax,ymin,ymax,0,30)
    ppgplot.pglab("\gs (km/s)",'fS(10\u11\d:10\u13\d)',"")
    ppgplot.pgsci(1)
    ppgplot.pgline(sigma,frac)
    ppgplot.pgsls(2)
    ppgplot.pgsci(2)
    ppgplot.pgline(sigma08,frac08)
    ppgplot.pgsls(1)
    ppgplot.pgsci(1)
    
    ppgplot.pgend()


    xmin=2.2
    xmax=3.2
    ymin=11.
    ymax=14.2
    psplotinit('maccretsigma3Gyr.ps')
    ppgplot.pgbox("",0.0,0,"",0.0,0)
    ppgplot.pgenv(xmin,xmax,ymin,ymax,0,30)
    ppgplot.pglab("\gs (km/s)",'M\dacc\u (M\d\(2281)\u)',"")
    ppgplot.pgsci(1)
    ppgplot.pgline(sigma,maccret)
    ppgplot.pgsls(2)
    ppgplot.pgsci(2)
    ppgplot.pgline(sigma08,maccret08)
    ppgplot.pgsls(1)
    ppgplot.pgsci(1)
    
    mylines=N.arange(-20.,20.,.4)
    mylineswidth=3
    ppgplot.pgsls(4)
    ppgplot.pgslw(mylineswidth)
    x=N.arange(0.,5.,1.)
    lines=mylines
    for y0 in lines:  
	y=3*x +y0 
	ppgplot.pgline(x,y)
	
	ppgplot.pgsls(1)
	ppgplot.pgend()
    os.system('cp maccretsigma.ps /Users/rfinn/SDSS/paper/.')
    os.system('cp fSsigma.ps /Users/rfinn/SDSS/paper/.')
		
		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)
	ppgplot.pgsci(1)
	
	
	if (arg.preview):		
		bitmapView = {}
Example #34
0
def mratiopg():
    ppgplot.pgbeg("maccratio.ps/vcps",1,1)  #color port.
    ppgplot.pgpap(8.,1.)
    ppgplot.pgpage
    ppgplot.pgsch(1.3) #font size
    ppgplot.pgslw(7)   #line width

    # 1st panel with symbols w/ stddev errorbars
    #ylabel="SFR (M\d\(2281) \u yr\u-1\d)"
    ylabel="L(H\ga) (10\u41\d  erg s\u-1\d)"
    xlabel="M\dr\u "
    x1=.15
    x2=.5
    x3=.5
    x4=.85
    y1=x1
    y2=x2
    y3=x3
    y4=x4
    emarker=18
    smarker=23
    xmin=N.log10(1.e14)
    xmax=N.log10(2.5e15)
    #ymin=-1.
    #ymax=3.
    ymin=0.
    ymax=25.
    ppgplot.pgsvp(x1,x4,y1,y4)  #sets viewport
    ppgplot.pgswin(xmin,xmax,ymin,ymax) #axes limits
    ppgplot.pgbox('blncst',1.,2,'bcvnst',2.,2)  #tickmarks and labeling


    for i in range(len(lz1lm.mass)):
	m=lz1lm.mass[i]
	l=lz1lm.maccret[i]
	h=hz1lm.maccret[i]
	r=h/l
	print i,m,l,h,r
    #print lz1lm.maccret
    #print hz1lm.maccret
    #print hz3lm.maccret
    r3lm=(hz3lm.maccret)/(lz3lm.maccret)
    r3hm=(hz3hm.maccret)/(lz3hm.maccret)
    #for i in range(len(r3)):
#	print i,lz3.sigma[i],hz3.sigma[i],lz3.mass[i],hz3.mass[i]
#	print i,lz01.sigma[i],hz01.sigma[i],lz01.mass[i],hz01.mass[i]
    r1lm=hz1lm.maccret/lz1lm.maccret
    r1hm=hz1hm.maccret/lz1hm.maccret
    #ra=N.array(hz01.maccret,'d')
    #rb=N.array(lz01.maccret,'d')
    #r01=ra/rb
    #for i in range(len(r01)):
	#print "ratio ",hz01.maccret[i],lz01.maccret[i],ra[i],rb[i],r01[i]
    ppgplot.pgsci(14)
    ppgplot.pgsls(1)
    ppgplot.pgline(N.log10(lz3lm.mass),r3lm)
    ppgplot.pgsls(2)
    ppgplot.pgline(N.log10(lz3hm.mass),r3hm)

    ppgplot.pgsci(1)
    ppgplot.pgsls(1)
    ppgplot.pgline(N.log10(lz1lm.mass),r1lm)
    ppgplot.pgsls(2)
    ppgplot.pgline(N.log10(lz1hm.mass),r1hm)

    xlabel='M\dcl\u (M\d\(2281)\u)'
    ylabel='M\dacc\u(z=0.75) / M\dacc\u(z=0.07)'

    ppgplot.pgsch(1.8)
    ppgplot.pgslw(7)
    ppgplot.pgmtxt('b',2.2,0.5,0.5,ylabel)    #xlabel
    ppgplot.pgmtxt('l',2.5,0.5,0.5,xlabel)

    ppgplot.pgend()
Example #35
0
def main(options):

    debug = options.debug
    MSlist = []
    device = options.device
    if device == '?':
        ppgplot.pgldev()
        return
    for inmspart in options.inms.split(','):
        for msname in glob.iglob(inmspart):
            MSlist.append(msname)
    if len(MSlist) == 0:
        print('Error: You must specify at least one MS name.')
        print('       Use "uvplot.py -h" to get help.')
        return
    if len(MSlist) > 1:
        print('WARNING: Antenna selection (other than all) may not work well')
        print('         when plotting more than one MS. Carefully inspect the')
        print('         listings of antenna numbers/names!')
    if options.title == '':
        plottitle = options.inms
    else:
        plottitle = options.title
    axlimits = options.axlimits.split(',')
    if len(axlimits) == 4:
        xmin, xmax, ymin, ymax = axlimits
    else:
        print('Error: You must specify four axis limits')
        return
    timeslots = options.timeslots.split(',')
    if len(timeslots) != 3:
        print('Error: Timeslots format is start,skip,end')
        return
    for i in range(len(timeslots)):
        timeslots[i] = int(timeslots[i])
        if timeslots[i] < 0:
            print('Error: timeslots values must not be negative')
            return
    doPlotColors = options.colors
    antToPlotSpl = options.antennas.split(',')
    antToPlot = []
    for i in range(len(antToPlotSpl)):
        tmpspl = antToPlotSpl[i].split('..')
        if len(tmpspl) == 1:
            antToPlot.append(int(antToPlotSpl[i]))
        elif len(tmpspl) == 2:
            for j in range(int(tmpspl[0]), int(tmpspl[1]) + 1):
                antToPlot.append(j)
        else:
            print('Error: Could not understand antenna list.')
            return
    queryMode = options.query
    plotLambda = options.kilolambda

    badval = 0.0
    xaxisvals0 = numpy.array([])
    yaxisvals0 = numpy.array([])
    xaxisvals1 = numpy.array([])
    yaxisvals1 = numpy.array([])
    xaxisvals2 = numpy.array([])
    yaxisvals2 = numpy.array([])
    xaxisvals3 = numpy.array([])
    yaxisvals3 = numpy.array([])
    xaxisvals4 = numpy.array([])
    yaxisvals4 = numpy.array([])
    xaxisvals5 = numpy.array([])
    yaxisvals5 = numpy.array([])
    savex0 = numpy.array([])
    savey0 = numpy.array([])
    savex1 = numpy.array([])
    savey1 = numpy.array([])
    savex2 = numpy.array([])
    savey2 = numpy.array([])
    savex3 = numpy.array([])
    savey3 = numpy.array([])
    savex4 = numpy.array([])
    savey4 = numpy.array([])
    savex5 = numpy.array([])
    savey5 = numpy.array([])
    numPlotted = 0
    ptcolor = 0
    for inputMS in MSlist:
        # open the main table and print some info about the MS
        print('Getting info for', inputMS)
        t = pt.table(inputMS, readonly=True, ack=False)
        tfreq = pt.table(t.getkeyword('SPECTRAL_WINDOW'),
                         readonly=True,
                         ack=False)
        ref_freq = tfreq.getcol('REF_FREQUENCY', nrow=1)[0]
        ch_freq = tfreq.getcol('CHAN_FREQ', nrow=1)[0]
        print('Reference frequency:\t%f MHz' % (ref_freq / 1.e6))
        if options.wideband:
            ref_wavelength = 2.99792458e8 / ch_freq
        else:
            ref_wavelength = [2.99792458e8 / ref_freq]
        print('Reference wavelength:\t%f m' % (ref_wavelength[0]))
        if options.sameuv and numPlotted > 0:
            print('Assuming same uvw as first MS!')
            if plotLambda:
                for w in ref_wavelength:
                    xaxisvals0 = numpy.append(
                        xaxisvals0, [savex0 / w / 1000., -savex0 / w / 1000.])
                    yaxisvals0 = numpy.append(
                        yaxisvals0, [savey0 / w / 1000., -savey0 / w / 1000.])
                    xaxisvals1 = numpy.append(
                        xaxisvals1, [savex1 / w / 1000., -savex1 / w / 1000.])
                    yaxisvals1 = numpy.append(
                        yaxisvals1, [savey1 / w / 1000., -savey1 / w / 1000.])
                    xaxisvals2 = numpy.append(
                        xaxisvals2, [savex2 / w / 1000., -savex2 / w / 1000.])
                    yaxisvals2 = numpy.append(
                        yaxisvals2, [savey2 / w / 1000., -savey2 / w / 1000.])
                    xaxisvals3 = numpy.append(
                        xaxisvals3, [savex3 / w / 1000., -savex3 / w / 1000.])
                    yaxisvals3 = numpy.append(
                        yaxisvals3, [savey3 / w / 1000., -savey3 / w / 1000.])
                    xaxisvals4 = numpy.append(
                        xaxisvals4, [savex4 / w / 1000., -savex4 / w / 1000.])
                    yaxisvals4 = numpy.append(
                        yaxisvals4, [savey4 / w / 1000., -savey4 / w / 1000.])
                    xaxisvals5 = numpy.append(
                        xaxisvals5, [savex5 / w / 1000., -savex5 / w / 1000.])
                    yaxisvals5 = numpy.append(
                        yaxisvals5, [savey5 / w / 1000., -savey5 / w / 1000.])
            else:
                print(
                    'Plotting more than one MS with same uv, all in meters... do you want -k?'
                )
                xaxisvals0 = numpy.append(xaxisvals0, [savex0, -savex0])
                yaxisvals0 = numpy.append(yaxisvals0, [savey0, -savey0])
                xaxisvals1 = numpy.append(xaxisvals1, [savex1, -savex1])
                yaxisvals1 = numpy.append(yaxisvals1, [savey1, -savey1])
                xaxisvals2 = numpy.append(xaxisvals2, [savex2, -savex2])
                yaxisvals2 = numpy.append(yaxisvals2, [savey2, -savey2])
                xaxisvals3 = numpy.append(xaxisvals3, [savex3, -savex3])
                yaxisvals3 = numpy.append(yaxisvals3, [savey3, -savey3])
                xaxisvals4 = numpy.append(xaxisvals4, [savex4, -savex4])
                yaxisvals4 = numpy.append(yaxisvals4, [savey4, -savey4])
                xaxisvals5 = numpy.append(xaxisvals5, [savex5, -savex5])
                yaxisvals5 = numpy.append(yaxisvals5, [savey5, -savey5])
            continue

        firstTime = t.getcell("TIME", 0)
        lastTime = t.getcell("TIME", t.nrows() - 1)
        intTime = t.getcell("INTERVAL", 0)
        print('Integration time:\t%f sec' % (intTime))
        nTimeslots = (lastTime - firstTime) / intTime
        print('Number of timeslots:\t%d' % (nTimeslots))
        if timeslots[1] == 0:
            if nTimeslots >= 100:
                timeskip = int(nTimeslots / 100)
            else:
                timeskip = 1
        else:
            timeskip = int(timeslots[1])
        print('For each baseline, plotting one point every %d samples' %
              (timeskip))
        if timeslots[2] == 0:
            timeslots[2] = nTimeslots
# open the antenna subtable
        tant = pt.table(t.getkeyword('ANTENNA'), readonly=True, ack=False)

        # Station names
        antList = tant.getcol('NAME')
        if len(antToPlot) == 1 and antToPlot[0] == -1:
            antToPlot = list(range(len(antList)))
        print('Station list (only starred stations will be plotted):')
        for i in range(len(antList)):
            star = ' '
            if i in antToPlot: star = '*'
            print('%s %2d\t%s' % (star, i, antList[i]))

# Bail if we're in query mode
        if queryMode:
            return

# select by time from the beginning, and only use specified antennas
        tsel = t.query(
            'TIME >= %f AND TIME <= %f AND ANTENNA1 IN %s AND ANTENNA2 IN %s' %
            (firstTime + timeslots[0] * intTime, firstTime +
             timeslots[2] * intTime, str(antToPlot), str(antToPlot)),
            columns='ANTENNA1,ANTENNA2,UVW')

        # Now we loop through the baselines
        i = 0
        nb = (len(antToPlot) * (len(antToPlot) - 1)) / 2
        sys.stdout.write('Reading uvw for %d baselines: %04d/%04d' %
                         (nb, i, nb))
        sys.stdout.flush()
        for tpart in tsel.iter(["ANTENNA1", "ANTENNA2"]):
            ant1 = tpart.getcell("ANTENNA1", 0)
            ant2 = tpart.getcell("ANTENNA2", 0)
            if ant1 not in antToPlot or ant2 not in antToPlot: continue
            if ant1 == ant2: continue
            i += 1
            sys.stdout.write('\b\b\b\b\b\b\b\b\b%04d/%04d' % (i, nb))
            sys.stdout.flush()
            if doPlotColors:
                stNameStr = antList[ant1][0] + antList[ant2][0]
                if stNameStr == 'CC': ptcolor = 0
                elif stNameStr == 'RR': ptcolor = 1
                elif 'C' in stNameStr and 'R' in stNameStr: ptcolor = 2
                elif 'C' in stNameStr: ptcolor = 3
                elif 'R' in stNameStr: ptcolor = 4
                else: ptcolor = 5
            # Get the values to plot
            uvw = tpart.getcol('UVW', rowincr=timeskip)
            if numPlotted == 0:
                savex0 = numpy.append(savex0, [uvw[:, 0], -uvw[:, 0]])
                savey0 = numpy.append(savey0, [uvw[:, 1], -uvw[:, 1]])
                savex1 = numpy.append(savex1, [uvw[:, 0], -uvw[:, 0]])
                savey1 = numpy.append(savey1, [uvw[:, 1], -uvw[:, 1]])
                savex2 = numpy.append(savex2, [uvw[:, 0], -uvw[:, 0]])
                savey2 = numpy.append(savey2, [uvw[:, 1], -uvw[:, 1]])
                savex3 = numpy.append(savex3, [uvw[:, 0], -uvw[:, 0]])
                savey3 = numpy.append(savey3, [uvw[:, 1], -uvw[:, 1]])
                savex4 = numpy.append(savex4, [uvw[:, 0], -uvw[:, 0]])
                savey4 = numpy.append(savey4, [uvw[:, 1], -uvw[:, 1]])
                savex5 = numpy.append(savex5, [uvw[:, 0], -uvw[:, 0]])
                savey5 = numpy.append(savey5, [uvw[:, 1], -uvw[:, 1]])
            if plotLambda:
                for w in ref_wavelength:
                    if ptcolor == 0:
                        xaxisvals0 = numpy.append(
                            xaxisvals0,
                            [uvw[:, 0] / w / 1000., -uvw[:, 0] / w / 1000.])
                        yaxisvals0 = numpy.append(
                            yaxisvals0,
                            [uvw[:, 1] / w / 1000., -uvw[:, 1] / w / 1000.])
                    elif ptcolor == 1:
                        xaxisvals1 = numpy.append(
                            xaxisvals1,
                            [uvw[:, 0] / w / 1000., -uvw[:, 0] / w / 1000.])
                        yaxisvals1 = numpy.append(
                            yaxisvals1,
                            [uvw[:, 1] / w / 1000., -uvw[:, 1] / w / 1000.])
                    elif ptcolor == 2:
                        xaxisvals2 = numpy.append(
                            xaxisvals2,
                            [uvw[:, 0] / w / 1000., -uvw[:, 0] / w / 1000.])
                        yaxisvals2 = numpy.append(
                            yaxisvals2,
                            [uvw[:, 1] / w / 1000., -uvw[:, 1] / w / 1000.])
                    elif ptcolor == 3:
                        xaxisvals3 = numpy.append(
                            xaxisvals3,
                            [uvw[:, 0] / w / 1000., -uvw[:, 0] / w / 1000.])
                        yaxisvals3 = numpy.append(
                            yaxisvals3,
                            [uvw[:, 1] / w / 1000., -uvw[:, 1] / w / 1000.])
                    elif ptcolor == 4:
                        xaxisvals4 = numpy.append(
                            xaxisvals4,
                            [uvw[:, 0] / w / 1000., -uvw[:, 0] / w / 1000.])
                        yaxisvals4 = numpy.append(
                            yaxisvals4,
                            [uvw[:, 1] / w / 1000., -uvw[:, 1] / w / 1000.])
                    elif ptcolor == 5:
                        xaxisvals5 = numpy.append(
                            xaxisvals5,
                            [uvw[:, 0] / w / 1000., -uvw[:, 0] / w / 1000.])
                        yaxisvals5 = numpy.append(
                            yaxisvals5,
                            [uvw[:, 1] / w / 1000., -uvw[:, 1] / w / 1000.])
            else:
                if ptcolor == 0:
                    xaxisvals0 = numpy.append(xaxisvals0,
                                              [uvw[:, 0], -uvw[:, 0]])
                    yaxisvals0 = numpy.append(yaxisvals0,
                                              [uvw[:, 1], -uvw[:, 1]])
                elif ptcolor == 1:
                    xaxisvals1 = numpy.append(xaxisvals1,
                                              [uvw[:, 0], -uvw[:, 0]])
                    yaxisvals1 = numpy.append(yaxisvals1,
                                              [uvw[:, 1], -uvw[:, 1]])
                elif ptcolor == 2:
                    xaxisvals2 = numpy.append(xaxisvals2,
                                              [uvw[:, 0], -uvw[:, 0]])
                    yaxisvals2 = numpy.append(yaxisvals2,
                                              [uvw[:, 1], -uvw[:, 1]])
                elif ptcolor == 3:
                    xaxisvals3 = numpy.append(xaxisvals3,
                                              [uvw[:, 0], -uvw[:, 0]])
                    yaxisvals3 = numpy.append(yaxisvals3,
                                              [uvw[:, 1], -uvw[:, 1]])
                elif ptcolor == 4:
                    xaxisvals4 = numpy.append(xaxisvals4,
                                              [uvw[:, 0], -uvw[:, 0]])
                    yaxisvals4 = numpy.append(yaxisvals4,
                                              [uvw[:, 1], -uvw[:, 1]])
                elif ptcolor == 5:
                    xaxisvals5 = numpy.append(xaxisvals5,
                                              [uvw[:, 0], -uvw[:, 0]])
                    yaxisvals5 = numpy.append(yaxisvals5,
                                              [uvw[:, 1], -uvw[:, 1]])
            #if debug:
            #        print uvw.shape
            #	print xaxisvals.shape
            #	print yaxisvals.shape
            #else:
            #        sys.stdout.write('.')
            #        sys.stdout.flush()
        sys.stdout.write(' Done!\n')
        numPlotted += 1

    print('Plotting uv points ...')
    # open the graphics device, using only one panel
    ppgplot.pgbeg(device, 1, 1)
    # set the font size
    ppgplot.pgsch(1)
    ppgplot.pgvstd()

    xaxisvals = numpy.append(
        xaxisvals0,
        numpy.append(
            xaxisvals1,
            numpy.append(
                xaxisvals2,
                numpy.append(xaxisvals3, numpy.append(xaxisvals4,
                                                      xaxisvals5)))))
    yaxisvals = numpy.append(
        yaxisvals0,
        numpy.append(
            yaxisvals1,
            numpy.append(
                yaxisvals2,
                numpy.append(yaxisvals3, numpy.append(yaxisvals4,
                                                      yaxisvals5)))))
    tmpvals0 = numpy.sqrt(xaxisvals0**2 + yaxisvals0**2)
    tmpvals1 = numpy.sqrt(xaxisvals1**2 + yaxisvals1**2)
    tmpvals2 = numpy.sqrt(xaxisvals2**2 + yaxisvals2**2)
    tmpvals3 = numpy.sqrt(xaxisvals3**2 + yaxisvals3**2)
    tmpvals4 = numpy.sqrt(xaxisvals4**2 + yaxisvals4**2)
    tmpvals5 = numpy.sqrt(xaxisvals5**2 + yaxisvals5**2)
    # Plot the data
    if debug:
        print(xaxisvals0[tmpvals0 != badval])
        print(yaxisvals0[tmpvals0 != badval])
    ppgplot.pgsci(1)
    uvmax = max(xaxisvals.max(), yaxisvals.max())
    uvmin = min(xaxisvals.min(), yaxisvals.min())
    uvuplim = 0.02 * (uvmax - uvmin) + uvmax
    uvlolim = uvmin - 0.02 * (uvmax - uvmin)
    if xmin == '':
        minx = uvlolim
    else:
        minx = float(xmin)
    if xmax == '':
        maxx = uvuplim
    else:
        maxx = float(xmax)
    if ymin == '':
        miny = uvlolim
    else:
        miny = float(ymin)
    if ymax == '':
        maxy = uvuplim
    else:
        maxy = float(ymax)
    if minx == maxx:
        minx = -1.0
        maxx = 1.0
    if miny == maxy:
        miny = -1.0
        maxy = 1.0
    ppgplot.pgpage()
    ppgplot.pgswin(minx, maxx, miny, maxy)
    ppgplot.pgbox('BCNST', 0.0, 0, 'BCNST', 0.0, 0)
    if plotLambda:
        ppgplot.pglab('u [k\gl]', 'v [k\gl]', '%s' % (plottitle))
    else:
        ppgplot.pglab('u [m]', 'v [m]', '%s' % (plottitle))
    ppgplot.pgpt(xaxisvals0[tmpvals0 != badval],
                 yaxisvals0[tmpvals0 != badval], 1)
    #if doPlotColors: ppgplot.pgmtxt('T', 1, 0.35, 0.5, 'C-C')
    ppgplot.pgsci(2)
    ppgplot.pgpt(xaxisvals1[tmpvals1 != badval],
                 yaxisvals1[tmpvals1 != badval], 1)
    #if doPlotColors: ppgplot.pgmtxt('T', 1, 0.50, 0.5, 'R-R')
    ppgplot.pgsci(4)
    ppgplot.pgpt(xaxisvals2[tmpvals2 != badval],
                 yaxisvals2[tmpvals2 != badval], 1)
    #if doPlotColors: ppgplot.pgmtxt('T', 1, 0.65, 0.5, 'C-R')
    ppgplot.pgsci(3)
    ppgplot.pgpt(xaxisvals3[tmpvals3 != badval],
                 yaxisvals3[tmpvals3 != badval], 1)
    #if doPlotColors: ppgplot.pgmtxt('T', 1, 0.55, 0.5, 'C-I')
    ppgplot.pgsci(5)
    ppgplot.pgpt(xaxisvals4[tmpvals4 != badval],
                 yaxisvals4[tmpvals4 != badval], 1)
    #if doPlotColors: ppgplot.pgmtxt('T', 1, 0.65, 0.5, 'R-I')
    ppgplot.pgsci(6)
    ppgplot.pgpt(xaxisvals5[tmpvals5 != badval],
                 yaxisvals5[tmpvals5 != badval], 1)
    #if doPlotColors: ppgplot.pgmtxt('T', 1, 0.75, 0.5, 'I-I')

    # Close the PGPLOT device
    ppgplot.pgclos()
Example #36
0
			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:
				ppgplot.pglab("wavelength [%s]"%spectrum.wavelengthUnits, "flux [%s]"%spectrum.fluxUnits, "%s [%s]"%(spectrum.objectName, spectrum.loadedFromFilename))
		
		
	
	if arg.stacked:
		mainPGPlotWindow = ppgplot.pgopen(arg.device)	
Example #37
0
def plotxy(y, x=None, title=None, rangex=None, rangey=None, \
           labx='', laby='', rangex2=None, rangey2=None, \
           labx2='', laby2='', symbol=ppgplot_symbol_, \
           line=ppgplot_linestyle_, width=ppgplot_linewidth_, \
           color=ppgplot_color_, font=ppgplot_font_, logx=0, logy=0, \
           logx2=0, logy2=0, errx=None, erry=None, id=0, noscale=0, \
           aspect=0.7727, fontsize=ppgplot_font_size_, ticks='in', \
           panels=[1,1], device=ppgplot_device_, setup=1):
    """
    plotxy(y, ...)
        An interface to make various XY style plots using PGPLOT.
            'y' is the 1D sequence object to plot.
        The optional entries are:
            x:        x values                  (default = 0, 1, ...)
            title:    graph title               (default = None)   
            rangex:   ranges for the x-axis     (default = automatic)
            rangey:   ranges for the y-axis     (default = automatic)
            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))
            errx:     symmetric x errors        (default = None)   
            erry:     symmetric y errors        (default = None)   
            symbol:   symbol for points         (default = None)   
            line:     line style                (default = 1 (solid))
            width:    line width                (default = 1 (thin))
            color:    line and/or symbol color  (default = 'white')
            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)) 
            noscale:  turn off auto scaling     (default = 0 (no)) 
            aspect:   aspect ratio              (default = 0.7727 (rect))
            ticks:    Ticks point in or out     (default = 'in')   
            panels:   Number of subpanels [r,c] (default = [1,1])
            device:   PGPLOT device to use      (default = '/XWIN')
            setup:    Auto-setup the plot       (default = 1)
        Note:  Many default values are defined in global variables
            with names like ppgplot_font_ or ppgplot_device_.
    """
    # Make sure the input data is an array
    y = Num.asarray(y)
    # Announce the global variables we will be using
    global ppgplot_dev_open_, ppgplot_dev_prep_, ppgplot_colors_
    # Define the X axis limits if needed
    if x is None: x = Num.arange(len(y), dtype='f')
    else: x = Num.asarray(x)
    # Determine the scaling to use for the first axis
    if rangex is None: rangex = [x.min(), x.max()]
    if rangey is None:
        if noscale: rangey = [y.min(), y.max()]
        else: rangey = scalerange(y)
    # Prep the plotting device...
    if (not ppgplot_dev_prep_ and setup):
        prepplot(rangex, rangey, title, labx, laby, \
                 rangex2, rangey2, labx2, laby2, \
                 logx, logy, logx2, logy2, font, fontsize, \
                 id, aspect, ticks, panels, device=device)
    # Choose the line color
    if type(color) == types.StringType:
        ppgplot.pgsci(ppgplot_colors_[color])
    else:
        ppgplot.pgsci(color)
    # Plot symbols (and errors) if requested
    if not symbol is None:
        ppgplot.pgpt(x, y, symbol)
    # Error bars
    if errx is not None:
        if not logx:
            errx = Num.asarray(errx)
            ppgplot.pgerrx(x + errx, x - errx, y, 1.0)
        else:
            errx = 10.0**Num.asarray(errx)
            ppgplot.pgerrx(Num.log10(10.0**x + errx),
                           Num.log10(10.0**x - errx), y, 1.0)
    if erry is not None:
        if not logy:
            erry = Num.asarray(erry)
            ppgplot.pgerry(x, y + erry, y - erry, 1.0)
        else:
            erry = 10.0**Num.asarray(erry)
            ppgplot.pgerry(x, Num.log10(10.0**y + erry),
                           Num.log10(10.0**y - erry), 1.0)
    # Plot connecting lines if requested
    if not line is None:
        # Choose the line style
        ppgplot.pgsls(line)
        # Choose the line width
        ppgplot.pgslw(width)
        ppgplot.pgline(x, y)
Example #38
0
		
	mainPGPlotWindow = ppgplot.pgopen(device)	
	ppgplot.pgask(True)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	
	if numSpectra1 != numSpectra2:
		print "We need an equal number of spectra in each list."
		print numSpectra1, numSpectra2
		sys.exit()
		
	for s1, s2 in zip(spectra1, spectra2):
		combinedSpectrum = copy.deepcopy(s1)
		combinedSpectrum.appendNewData(s2)
	
		ppgplot.pgsci(1)
		lowerWavelength = min(combinedSpectrum.wavelengths)
		upperWavelength = max(combinedSpectrum.wavelengths)
		lowerFlux = min(combinedSpectrum.flux)
		upperFlux = max(combinedSpectrum.flux)
		lowerFlux = 0
		upperFlux = 2.5
		ppgplot.pgenv(lowerWavelength, upperWavelength, lowerFlux, upperFlux, 0, 0)
		
		ppgplot.pgsci(2)
		ppgplot.pgline(s1.wavelengths, s1.flux)
		ppgplot.pgsci(3)
		ppgplot.pgline(s2.wavelengths, s2.flux)
		
		
		ppgplot.pgsci(1)
Example #39
0
 helpItem = {"key": "i/o", "text": "Zoom in/out."}
 help.append(helpItem)
 helpItem = {"key": "q", "text": "Quit."}
 help.append(helpItem)
 helpItem = {"key": "f", "text": "Find local Ha maxima."}
 help.append(helpItem)
 helpItem = {"key": "l", "text": "Show location of cursor."}
 help.append(helpItem)
 # try:
 x = width / 2
 y = height / 2
 newWidth = width
 newHeight = height
 # pixelGrid = makeGrid(width, height, 100)
 originalImageData = numpy.copy(imageData)
 ppgplot.pgsci(3)
 keyPressed = None
 while keyPressed != "q":
     ch = ppgplot.pgcurs(x, y)
     x = ch[0]
     y = ch[1]
     keyPressed = ch[2]
     # print "Key pressed:", ch[2]
     if keyPressed == "?":
         print ("Help:")
         for helpItem in help:
             print ("\t" + helpItem["key"] + " : " + helpItem["text"])
         print ("")
     if keyPressed == "p":
         if plotSources == True:
             plotSources = False
Example #40
0
    positionString = generalUtils.toSexagesimal((ra, dec))
    print "RA, DEC of image centre is: ", positionString, ra, dec
    margins = wcsSolution.all_pix2world([[0, 0], [width, height]], 1)
    margins = checkMargins(margins)
    print "ra, dec limits:", margins

    xlimits = (0, width)
    ylimits = (0, height)

    # try:
    x = width / 2
    y = height / 2
    newWidth = width
    newHeight = height
    ppgplot.pgsci(3)
    keyPressed = None
    while keyPressed != 'q':
        ch = ppgplot.pgcurs(x, y)
        x = ch[0]
        y = ch[1]
        keyPressed = ch[2]
        # print "Key pressed:", ch[2]

        if keyPressed == 'w':
            imageMinMax = (imageMinMax[1], imageMinMax[0])
            if invertedColours: invertedColours = False
            else: invertedColours = True
            redraw()

        if keyPressed == 'i':
Example #41
0
def extract_tracks(fname, trkrmin, drdtmin, trksig, ntrkmin, path,
                   results_path):
    # 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()

    tr = np.array([-0.5, 1.0, 0.0, -0.5, 0.0, 1.0])

    # Parse identifications
    idents = [satid(line) for line in lines]

    # Identify unknowns
    for ident0 in idents:
        if ident0.catalog == "unidentified":
            for ident1 in idents:
                if ident1.catalog == "unidentified":
                    continue

                # Find matches
                p1 = inside_selection(ident1, ident0.t0, ident0.x0, ident0.y0)
                p2 = inside_selection(ident1, ident0.t1, ident0.x1, ident0.y1)

                # Match found
                if p1 and p2:
                    # Copy info
                    ident0.norad = ident1.norad
                    ident0.catalog = ident1.catalog
                    ident0.state = ident1.state
                    ident1.state = "remove"
                    break

    # Loop over identifications
    for ident in idents:
        # Skip superseded unknowns
        if ident.state == "remove":
            continue

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

        # Extract significant pixels along a track
        x, y, t, sig = ff.significant_pixels_along_track(
            trksig, ident.x0, ident.y0, ident.dxdt, ident.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(ident.norad, ff.nfd)
            obs = observation(ff, mjd, x0, y0)
            iod_line = "%s" % format_iod_line(ident.norad, cospar, ff.site_id,
                                              obs.nfd, obs.ra, obs.de)

            # Create diagnostic plot
            plot_header(fname.replace(".fits", "_%05d.png/png" % ident.norad),
                        ff, iod_line)

            ppg.pgimag(ff.zmax, ff.nx, ff.ny, 0, ff.nx - 1, 0, ff.ny - 1,
                       ff.zmaxmax, ff.zmaxmin, tr)
            ppg.pgbox("BCTSNI", 0., 0, "BCTSNI", 0., 0)
            ppg.pgstbg(1)

            ppg.pgsci(0)
            if ident.catalog.find("classfd.tle") > 0:
                ppg.pgsci(4)
            elif ident.catalog.find("inttles.tle") > 0:
                ppg.pgsci(3)

            ppg.pgpt(np.array([x0]), np.array([y0]), 4)
            ppg.pgmove(xmin, ymin)
            ppg.pgdraw(xmax, ymax)
            ppg.pgsch(0.65)
            ppg.pgtext(np.array([x0]), np.array([y0]), " %05d" % ident.norad)
            ppg.pgsch(1.0)
            ppg.pgsci(1)

            ppg.pgend()

            # Store results
            store_results(ident, fname, results_path, iod_line)

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

            # Skip if no points selected
            if np.sum(c) == 0:
                store_not_seen(ident, fname, results_path)
                continue

            # Compute track
            tmid = np.mean(t[c])
            mjd = ff.mjd + tmid / 86400.0
            xmid = ident.x0 + ident.dxdt * tmid
            ymid = ident.y0 + ident.dydt * tmid
            ztrk = ndimage.gaussian_filter(
                ff.track(ident.dxdt, ident.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:
                store_not_seen(ident, fname, results_path)
                continue

            # Skip if point is outside selection area
            if inside_selection(ident, tmid, x0, y0) is False:
                store_not_seen(ident, fname, results_path)
                continue

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

            # Create diagnostic plot
            pngfile = fname.replace(".fits", "_%05d.png" % ident.norad)
            plot_header(pngfile + "/png", ff, iod_line)

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

            plot_selection(ident, xmid, ymid)

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

            ppg.pgend()

            # Store results
            store_results(ident, fname, results_path, iod_line)
Example #42
0
            ppgplot.pgeras()
            ppgplot.pgsvp(0.01, 0.99, 0.01, 0.99)
            ppgplot.pgwnad(-1.5 * m.w, 1.5 * m.w, -m.w, m.w)

            # Set background depending on solar altitude
            if m.sunalt > 0.0:
                ppgplot.pgscr(0, 0.0, 0.0, 0.4)
            elif m.sunalt > -6.0:
                ppgplot.pgscr(0, 0.0, 0.0, 0.3)
            elif m.sunalt > -12.0:
                ppgplot.pgscr(0, 0.0, 0.0, 0.2)
            elif m.sunalt > -18.0:
                ppgplot.pgscr(0, 0.0, 0.0, 0.1)
            else:
                ppgplot.pgscr(0, 0.0, 0.0, 0.0)
            ppgplot.pgsci(0)

            # Plot box
            ppgplot.pgrect(-1.5 * m.w, 1.5 * m.w, -m.w, m.w)
            ppgplot.pgsci(1)
            ppgplot.pgsch(1.0)
            ppgplot.pgbox("BC", 0., 0, "BC", 0., 0)
            ppgplot.pgpt1(0., 0., 2)

            # Plot field-of-view
            ppgplot.pgsfs(2)
            ppgplot.pgrect(-m.fw, m.fw, -m.fh, m.fh)
            ppgplot.pgsfs(1)

            # Top left string
            ppgplot.pgsch(0.8)
Example #43
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 #44
0
def plot_rating_sheet(rating):
    """
    Plot a fact sheet on the ratings in the database corresponding to 'rating'.
    'rating' is a dictionary of information from the MySQL database (as returned
    by 'get_all_rating_types()'.
    """
    plot_utils.beginplot("rating_report%s.ps" % currdatetime.strftime('%y%m%d'), vertical=True)
    ch0 = ppgplot.pgqch()
    ppgplot.pgsch(0.5)
    ch = ppgplot.pgqch()
    ppgplot.pgsch(0.75)
    ppgplot.pgtext(0,1,"Rating Report for %s (%s) - page 1 of 2" % (rating["name"], currdatetime.strftime('%c')))
    ppgplot.pgsch(ch)
    
    # Plot Histograms
    
    all_ratings = get_ratings(rating["rating_id"]) 
    range = xmin,xmax = np.min(all_ratings), np.max(all_ratings)
    ppgplot.pgsci(1)
    ppgplot.pgslw(1)
    
    #===== Total/Classified/Unclassified
    # Get data
    ppgplot.pgsvp(0.1, 0.9, 0.75, 0.9)
    (tot_counts, tot_left_edges)=np.histogram(all_ratings, bins=NUMBINS, range=range)
    ppgplot.pgswin(xmin,xmax,0,np.max(tot_counts)*1.1)
    ppgplot.pgsch(0.5)
    ppgplot.pgbox("BCTS",0,5,"BCNTS",0,5)
    ppgplot.pgbin(tot_left_edges, tot_counts)
    (clsfd_counts, clsfd_left_edges)=np.histogram(get_ratings(rating["rating_id"], human_classification=(1,2,3,4,5,6,7)), bins=NUMBINS, range=range)
    ppgplot.pgsci(3) # plot classified in green
    ppgplot.pgbin(tot_left_edges, clsfd_counts)
    unclsfd_counts = tot_counts-clsfd_counts
    ppgplot.pgsci(2) # plot unclassified in red
    ppgplot.pgbin(tot_left_edges, unclsfd_counts)
    ppgplot.pgsci(1) # reset colour to black
    ppgplot.pgsch(0.75)
    ppgplot.pglab("","Counts","")

    #===== Class 1/2/3
    ppgplot.pgsvp(0.1, 0.9, 0.6, 0.75)
    (counts, left_edges)=np.histogram(get_ratings(rating["rating_id"], human_classification=(1,2,3)), bins=NUMBINS, range=range)
    ppgplot.pgswin(xmin,xmax,0,np.max(counts)*1.1)
    ppgplot.pgsch(0.5)
    ppgplot.pgbox("BCTS",0,5,"BCNTS",0,5)
    ppgplot.pgsci(1) # plot in black
    ppgplot.pgbin(tot_left_edges, counts)
    ppgplot.pgsci(1) # reset colour to black
    ppgplot.pgsch(0.75)
    ppgplot.pglab("","Class 1/2/3","")

    #===== RFI
    ppgplot.pgsvp(0.1, 0.9, 0.45, 0.6)
    rfi_ratings = get_ratings(rating["rating_id"], human_classification=(4,))
    (counts, left_edges)=np.histogram(rfi_ratings, bins=NUMBINS, range=range)
    ppgplot.pgswin(xmin,xmax,0,np.max(counts)*1.1)
    ppgplot.pgsch(0.5)
    ppgplot.pgbox("BCTS",0,5,"BCNTS",0,5)
    ppgplot.pgsci(1) # plot in black
    ppgplot.pgbin(tot_left_edges, counts)
    ppgplot.pgsci(1) # reset colour to black
    ppgplot.pgsch(0.75)
    ppgplot.pglab("","RFI","")

    #===== Noise
    ppgplot.pgsvp(0.1, 0.9, 0.3, 0.45)
    noise_ratings = get_ratings(rating["rating_id"], human_classification=(5,))
    (counts, left_edges)=np.histogram(noise_ratings, bins=NUMBINS, range=range)
    ppgplot.pgswin(xmin,xmax,0,np.max(counts)*1.1)
    ppgplot.pgsch(0.5)
    ppgplot.pgbox("BCTS",0,5,"BCNTS",0,5)
    ppgplot.pgsci(1) # plot in black
    ppgplot.pgbin(tot_left_edges, counts)
    ppgplot.pgsci(1) # reset colour to black
    ppgplot.pgsch(0.75)
    ppgplot.pglab("","Noise","")

    #===== Known/Harmonic
    ppgplot.pgsvp(0.1, 0.9, 0.15, 0.3)
    known_ratings = get_ratings(rating["rating_id"], human_classification=(6,7))
    (counts, left_edges)=np.histogram(known_ratings, bins=NUMBINS, range=range)
    ppgplot.pgswin(xmin,xmax,0,np.max(counts)*1.1)
    ppgplot.pgsch(0.5)
    ppgplot.pgbox("BCNTS",0,5,"BCNTS",0,5)
    ppgplot.pgsci(1) # plot in black
    ppgplot.pgbin(tot_left_edges, counts)
    ppgplot.pgsci(1) # reset colour to black
    ppgplot.pgsch(0.75)
    ppgplot.pglab(rating["name"],"Known/Harmonic","")

    #===== Second page for differential histograms
    plot_utils.nextpage(vertical=True)
    ppgplot.pgsch(0.75)
    ppgplot.pgtext(0,1,"Rating Report for %s (%s) - page 2 of 2" % (rating["name"], currdatetime.strftime('%c')))
    
    #===== RFI - Known
    ppgplot.pgsvp(0.1, 0.9, 0.75, 0.9)
    if rfi_ratings.size==0 or known_ratings.size==0:
        ppgplot.pgswin(0,1,0,1)
        ppgplot.pgbox("BC",0,0,"BC",0,0)
	ppgplot.pgsch(0.75)
        ppgplot.pglab("","RFI - Known","")
	ppgplot.pgsch(1.0)
	ppgplot.pgptxt(0.5, 0.5, 0.0, 0.5, "Not enough data")
    else:
        (known_counts, known_left_edges)=np.histogram(known_ratings, bins=NUMBINS, range=range, normed=True)
        (rfi_counts, rfi_left_edges)=np.histogram(rfi_ratings, bins=NUMBINS, range=range, normed=True)
        diff_counts = rfi_counts - known_counts
        ppgplot.pgswin(xmin,xmax,np.min(diff_counts)*1.1,np.max(diff_counts)*1.1)
	ppgplot.pgsch(0.5)
        ppgplot.pgbox("BCTS",0,5,"BCNTS",0,5)
        ppgplot.pgbin(tot_left_edges, diff_counts)
        ppgplot.pgsci(2) # set colour to red
        ppgplot.pgline(tot_left_edges, np.zeros_like(tot_left_edges))
        ppgplot.pgsci(1) # reset colour to black
	ppgplot.pgsch(0.75)
        ppgplot.pglab("","RFI - Known","")

    #===== RFI - Noise
    ppgplot.pgsvp(0.1, 0.9, 0.6, 0.75)
    if noise_ratings.size==0 or rfi_ratings.size==0:
        ppgplot.pgswin(0,1,0,1)
        ppgplot.pgbox("BC",0,0,"BC",0,0)
	ppgplot.pgsch(0.75)
        ppgplot.pglab("","RFI - Noise","")
	ppgplot.pgsch(1.0)
	ppgplot.pgptxt(0.5, 0.5, 0.0, 0.5, "Not enough data")
    else:
        (noise_counts, noise_left_edges)=np.histogram(noise_ratings, bins=NUMBINS, range=range, normed=True)
        (rfi_counts, rfi_left_edges)=np.histogram(rfi_ratings, bins=NUMBINS, range=range, normed=True)
        diff_counts = rfi_counts - noise_counts
        ppgplot.pgswin(xmin,xmax,np.min(diff_counts)*1.1,np.max(diff_counts)*1.1)
	ppgplot.pgsch(0.5)
        ppgplot.pgbox("BCTS",0,5,"BCNTS",0,5)
        ppgplot.pgbin(tot_left_edges, diff_counts)
        ppgplot.pgsci(2) # set colour to red
        ppgplot.pgline(tot_left_edges, np.zeros_like(tot_left_edges))
        ppgplot.pgsci(1) # reset colour to black
	ppgplot.pgsch(0.75)
        ppgplot.pglab("","RFI - Noise","")

    #===== Known - Noise
    ppgplot.pgsvp(0.1, 0.9, 0.45, 0.6)
    if noise_ratings.size==0 or known_ratings.size==0:
        ppgplot.pgswin(0,1,0,1)
        ppgplot.pgbox("BC",0,0,"BC",0,0)
	# Y-axis label is taken care of outside of if/else (below)
	ppgplot.pgsch(1.0)
	ppgplot.pgptxt(0.5, 0.5, 0.0, 0.5, "Not enough data")
    else:
        (noise_counts, noise_left_edges)=np.histogram(noise_ratings, bins=NUMBINS, range=range, normed=True)
        (known_counts, known_left_edges)=np.histogram(known_ratings, bins=NUMBINS, range=range, normed=True)
        diff_counts = known_counts - noise_counts
        ppgplot.pgswin(xmin,xmax,np.min(diff_counts)*1.1,np.max(diff_counts)*1.1)
	ppgplot.pgsch(0.5)
        ppgplot.pgbox("BCNTS",0,5,"BCNTS",0,5)
        ppgplot.pgbin(tot_left_edges, diff_counts)
        ppgplot.pgsci(2) # set colour to red
        ppgplot.pgline(tot_left_edges, np.zeros_like(tot_left_edges))
        ppgplot.pgsci(1) # reset colour to black
    ppgplot.pgswin(xmin,xmax,0,1)
    ppgplot.pgsch(0.5)
    ppgplot.pgbox("NTS",0,5,"",0,0)
    ppgplot.pgsch(0.75)
    ppgplot.pglab(rating["name"],"Known - Noise","")
    
    ppgplot.pgsch(ch0) # reset character height
Example #45
0
def main(options):

        global keepPlotting
        keepPlotting = True
        debug = options.debug
        inputMS = glob.glob(options.inms)
        if inputMS == '':
                print 'Error: You must specify a MS name.'
                print '       Use "uvplot.py -h" to get help.'
                return
        if options.inms.endswith('/'):
            options.inms = options.inms[:-1]
        inputMSbasename = options.inms.split('/')[-1]
        if inputMSbasename == '':
            # The user has not specified the full path of the MS
            inputMSbasename = options.inms
        
        device = options.device
        if device=='?':
                ppgplot.pgldev()
                return
        xaxis = options.xaxis
        if xaxis == 'ha':
            print 'Adding derived columns to allow plotting hour angle...'
            try:
                pt.addDerivedMSCal(inputMS)
            except:
                print 'Failed, trying to remove and add columns...'
                try:
                    pt.removeDerivedMSCal(inputMS)
                    pt.addDerivedMSCal(inputMS)
                except:
                    print 'That failed too... plotting HA seems to not be possible.'
                    return
        yaxis = options.yaxis
        column = options.column
        nx, ny = options.nxy.split(',')
        axlimits = options.axlimits.split(',')
        if len(axlimits) == 4:
                xmin,xmax,ymin,ymax = axlimits
        else:
                print 'Error: You must specify four axis limits'
                return
        showFlags = options.flag
        flagCol = options.colflag
        showAutocorr = options.autocorr
        showStats = options.statistics
        timeslots = options.timeslots.split(',')
        if len(timeslots) != 2:
                print 'Error: Timeslots format is start,end'
                return
        for i in range(len(timeslots)): timeslots[i] = int(timeslots[i])
        antToPlotSpl = options.antennas.split(',')
        antToPlot = []
        for i in range(len(antToPlotSpl)):
                tmpspl = antToPlotSpl[i].split('..')
                if len(tmpspl) == 1:
                        antToPlot.append(int(antToPlotSpl[i]))
                elif len(tmpspl) == 2:
                        for j in range(int(tmpspl[0]),int(tmpspl[1])+1):
                                antToPlot.append(j)
                else:
                        print 'Error: Could not understand antenna list.'
                        return
        polarizations = options.polar.split(',')
        for i in range(len(polarizations)):
                polarizations[i] = int(polarizations[i])
        
        convertStokes = options.stokes        
        
        operation = options.operation
        if operation != '':
            operation = int(operation)
            if convertStokes:
                print 'Error: Stokes conversion is not compatible with special operations'
                return
        
        channels = options.channels.split(',')
        if len(channels) != 2:
                print 'Error: Channels format is start,end'
                return
        for i in range(len(channels)): channels[i] = int(channels[i])
        if channels[1] == -1:
                channels[1] = None # last element even if there is only one
        else:
                channels[1] += 1
        queryMode = options.query
        doUnwrap = options.wrap


        if not queryMode:
                # open the graphics device, use the right number of panels
                ppgplot.pgbeg(device, int(nx), int(ny))
                # set the font size
                ppgplot.pgsch(1.5)
                ppgplot.pgvstd()

        # open the main table and print some info about the MS
        t = pt.table(inputMS, readonly=True, ack=False)
        firstTime = t.query(sortlist='TIME',columns='TIME',limit=1).getcell("TIME", 0)
        lastTime = t.query(sortlist='TIME',columns='TIME',offset=t.nrows()-1).getcell("TIME", 0)
        intTime = t.getcell("INTERVAL", 0)
        print 'Integration time:\t%f sec' % (intTime)
        nTimeslots = (lastTime - firstTime) / intTime
        if timeslots[1] == -1:
                timeslots[1] = nTimeslots
        else:
                timeslots[1] += 1
        print 'Number of timeslots:\t%d' % (nTimeslots)
        # open the antenna and spectral window subtables
        tant = pt.table(t.getkeyword('ANTENNA'), readonly=True, ack=False)
        tsp = pt.table(t.getkeyword('SPECTRAL_WINDOW'), readonly=True, ack=False)
        numChannels = len(tsp.getcell('CHAN_FREQ',0))
        print 'Number of channels:\t%d' % (numChannels)
        print 'Reference frequency:\t%5.2f MHz' % (tsp.getcell('REF_FREQUENCY',0)/1.e6)

        # Station names
        antList = tant.getcol('NAME')
        if len(antToPlot)==1 and antToPlot[0]==-1:
                antToPlot = range(len(antList))
        print 'Station list (only starred stations will be plotted):'
        for i in range(len(antList)):
                star = ' '
                if i in antToPlot: star = '*'
                print '%s %2d\t%s' % (star, i, antList[i])

        # Bail if we're in query mode
        if queryMode:
                return

        # select by time from the beginning, and only use specified antennas
        tsel = t.query('TIME >= %f AND TIME <= %f AND ANTENNA1 IN %s AND ANTENNA2 IN %s' % (firstTime+timeslots[0]*intTime,firstTime+timeslots[1]*intTime,str(antToPlot),str(antToPlot)))

        # values to use for each polarization
        plotColors = [1,2,3,4]
        labXPositions = [0.35,0.45,0.55,0.65]
        labYPositions = [1.0,1.0,1.0,1.0]
        if convertStokes:
                polLabels = ['I','Q','U','V']
        else:
                polLabels = ['XX','XY','YX','YY']

        # define nicely written axis labels
        axisLabels = {'time': 'Time',
                      'ha': 'Hour angle',
                      'chan': 'Channel',
                      'freq': 'Frequency [MHz]',
                      'amp': 'Visibility amplitude',
                      'real': 'Real part of visibility',
                      'imag': 'Imaginary part of visibility',
                      'phase': 'Visibility phase [radians]'}

        # Now we loop through the baselines
        ppgplot.pgpage()
        for tpart in tsel.iter(["ANTENNA1","ANTENNA2"]):
                if not keepPlotting: return
                ant1 = tpart.getcell("ANTENNA1", 0)
                ant2 = tpart.getcell("ANTENNA2", 0)
                if ant1 not in antToPlot or ant2 not in antToPlot: continue
                if ant1 == ant2:
                        if not showAutocorr:
                                continue
                # Get the values to plot, strategy depends on axis type
                if xaxis == 'time' or xaxis == 'ha':
                        xaxisvals = getXAxisVals(tpart, xaxis, channels)
                        yaxisvals = getYAxisVals(tpart, yaxis, column, operation, showFlags, flagCol, channels, doUnwrap, convertStokes)
                else:
                        xaxisvals = getXAxisVals(tsp, xaxis, channels)
                        yaxisvals = getYAxisVals(tpart, yaxis, column, operation, showFlags, flagCol, channels, doUnwrap, convertStokes, xaxistype=1)
                if xaxisvals == None: # This baseline must be empty, go to next one
                        print 'No good data on baseline %s - %s' % (antList[ant1],antList[ant2])
                        continue
                    
                if debug:
                        print xaxisvals.shape
                        print yaxisvals.shape
                        for r in range(len(xaxisvals)):
                                print '%s'%yaxisvals[r]
                if len(xaxisvals) != len(yaxisvals): # something is wrong
                        print 'Error: X and Y axis types incompatible'
                        return

                # Plot the data, each polarization in a different color
                ppgplot.pgsci(1)
                if xmin == '':
                        minx = xaxisvals.min()
                else:
                        minx = float(xmin)
                if xmax == '':
                        maxx = xaxisvals.max()
                else:
                        maxx = float(xmax)
                if ymin == '':
                        miny = yaxisvals.min()
                        if numpy.ma.getmaskarray(yaxisvals.min()):
                                print 'All data flagged on baseline %s - %s' % (antList[ant1],antList[ant2])
                                continue
                else:
                        miny = float(ymin)
                if ymax == '':
                        maxy = yaxisvals.max()
                else:
                        maxy = float(ymax)
                if minx == maxx:
                        minx -= 1.0
                        maxx += 1.0
                else:
                        diffx = maxx - minx
                        minx -= 0.02*diffx
                        maxx += 0.02*diffx
                if miny == maxy:
                        miny -= 1.0
                        maxy += 1.0
                else:
                        diffy = maxy - miny
                        miny -= 0.02*diffy
                        maxy += 0.02*diffy
                #ppgplot.pgpage()
                ppgplot.pgswin(minx,maxx,miny,maxy)
                if xaxis == 'time' or xaxis == 'ha':
                        ppgplot.pgtbox('ZHOBCNST',0.0,0,'BCNST',0.0,0)
                else:
                        ppgplot.pgbox('BCNST',0.0,0,'BCNST',0.0,0)
                
                #ppgplot.pglab(axisLabels[xaxis], axisLabels[yaxis], '%s - %s'%(antList[ant1],antList[ant2]))
                #ppgplot.pgmtxt('T', 3.0, 0.5, 0.5, inputMSbasename)
                
                ppgplot.pglab(axisLabels[xaxis], axisLabels[yaxis], inputMSbasename + '(' + getDataDescription(column) + '): %s - %s'%(antList[ant1],antList[ant2]))
               
               
                if operation != 0:
                    # some operations is defined
                    if operation == 1:
                        label = 'XX-YY'
                    elif operation == 2:
                        label = 'XY.YX*'
                    else:
                        print 'Special operation not defined'
                        return
            
                    ppgplot.pgsci(plotColors[0])
                    tmpvals = yaxisvals
                    print 'Baseline',antList[ant1],'-',antList[ant2],': Plotting',len(tmpvals[~tmpvals.mask]),'points of ' + label
                    ppgplot.pgpt(xaxisvals[~tmpvals.mask], tmpvals[~tmpvals.mask], 1)
                            
                    addInfo(showStats, tmpvals[~tmpvals.mask], label, labXPositions[1], labYPositions[1])
                else:
                    for j in polarizations:
                        ppgplot.pgsci(plotColors[j])
                        tmpvals = yaxisvals[:,j]
                        if j == polarizations[0]:
                                print 'Baseline',antList[ant1],'-',antList[ant2],': Plotting',len(tmpvals[~tmpvals.mask]),'points per polarization'
                        ppgplot.pgpt(xaxisvals[~tmpvals.mask], tmpvals[~tmpvals.mask], 1)
                        
                        addInfo(showStats, tmpvals[~tmpvals.mask], polLabels[j], labXPositions[j], labYPositions[j])
                ppgplot.pgpage()

        # Close the PGPLOT device
        ppgplot.pgclos()

        if xaxis=='ha':
            print 'Removing derived columns...'
            pt.removeDerivedMSCal(inputMS)
Example #46
0
	recordedData.sortByHJD()
	# print recordedData
	"""
	mainPGPlotWindow = ppgplot.pgopen(arg.device)	
	ppgplot.pgask(False)
	pgPlotTransform = [0, 1, 0, 0, 0, 1]
	yUpper = 2.5
	yLower = -0.5
	
	fitPGPlotWindow = ppgplot.pgopen(arg.device)	
	ppgplot.pgask(False)
	
	for spectrum in spectra:
		ppgplot.pgslct(mainPGPlotWindow)
		
		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)
		ppgplot.pglab("wavelength [%s]"%spectrum.wavelengthUnits, "flux [%s]"%spectrum.fluxUnits, "%s [%s]"%(spectrum.objectName, spectrum.loadedFromFilename))
		
		# Grab the continuum from either side of the spectrum
		
		lowerCut = 6540
		upperCut = 6585
		continuumSpectrum = copy.deepcopy(spectrum)
		continuumSpectrum.snipWavelengthRange(lowerCut, upperCut)
		ppgplot.pgsci(2)
Example #47
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 #48
0
def joy_division_plot(pulses, timeseries, downfactor=1, hgt_mult=1):
    """Plot each pulse profile on the same plot separated
        slightly on the vertical axis.
        'timeseries' is the Datfile object dissected.
        Downsample profiles by factor 'downfactor' before plotting.
        hgt_mult is a factor to stretch the height of the paper.
    """
    first = True
    ppgplot.pgbeg("%s.joydiv.ps/CPS" % \
                    os.path.split(timeseries.basefn)[1], 1, 1)
    ppgplot.pgpap(10.25, hgt_mult*8.5/11.0) # Letter landscape
    # ppgplot.pgpap(7.5, 11.7/8.3) # A4 portrait, doesn't print properly
    ppgplot.pgiden()
    ppgplot.pgsci(1)
    
    # Set up main plot
    ppgplot.pgsvp(0.1, 0.9, 0.1, 0.8)
    ppgplot.pglab("Profile bin", "Single pulse profiles", "")
    to_plot = []
    xmin = 0
    xmax = None
    ymin = None
    ymax = None
    for pulse in pulses:
        vertical_offset = (pulse.number-1)*JOYDIV_SEP
        copy_of_pulse = pulse.make_copy()
        if downfactor > 1:
            # Interpolate before downsampling
            interp = ((copy_of_pulse.N/downfactor)+1)*downfactor
            copy_of_pulse.interpolate(interp)
            copy_of_pulse.downsample(downfactor)
            # copy_of_pulse.scale()
        if first:
            summed_prof = copy_of_pulse.profile.copy()
            first = False
        else:
            summed_prof += copy_of_pulse.profile
        prof = copy_of_pulse.profile + vertical_offset
        min = prof.min()
        if ymin is None or min < ymin:
            ymin = min
        max = prof.max()
        if ymax is None or max > ymax:
            ymax = max
        max = prof.size-1
        if xmax is None or max > xmax:
            xmax = max
        to_plot.append(prof)
    yspace = 0.1*ymax
    ppgplot.pgswin(0, xmax, ymin-yspace, ymax+yspace)
    for prof in to_plot:
        ppgplot.pgline(np.arange(0,prof.size), prof)
    ppgplot.pgbox("BNTS", 0, 0, "BC", 0, 0)

    # Set up summed profile plot
    ppgplot.pgsvp(0.1, 0.9, 0.8, 0.9)
    ppgplot.pglab("", "Summed profile", "Pulses from %s" % timeseries.datfn)
    summed_prof = summed_prof - summed_prof.mean()
    ppgplot.pgswin(0, xmax, summed_prof.min(), summed_prof.max())
    ppgplot.pgline(np.arange(0, summed_prof.size), summed_prof)
    ppgplot.pgbox("C", 0, 0, "BC", 0, 0)
    ppgplot.pgclos()
Example #49
0
def plot2d(z, x=None, y=None, title=None, rangex=None, rangey=None, \
           rangez=None, labx='', laby='', rangex2=None, rangey2=None, \
           labx2='', laby2='', image=ppgplot_palette_, contours=None, \
           logx=0, logy=0, logx2=0, logy2=0, \
           line=ppgplot_linestyle_, width=ppgplot_linewidth_, \
           color=ppgplot_color_, labels=ppgplot_labels_, \
           labelint=ppgplot_labelint_, labelmin=ppgplot_labelmin_, \
           font=ppgplot_font_, id=0, noscale=0, aspect=1, \
           fontsize=ppgplot_font_size_, ticks='out', panels=[1,1], \
           device=ppgplot_device_):
    """
    plot2d(z, ...)
        An interface to make various 2D plots using PGPLOT.
            'z' is the 2D Numpy array to be plotted.
        The optional entries are:
            x:         x values                    (default = 0, 1, ...) 
            y:         y values                    (default = 0, 1, ...) 
            title:     graph title                 (default = None)      
            rangex:    range for the x-axis        (default = automatic) 
            rangey:    range for the y-axis        (default = automatic) 
            rangez:    range for the z-axis        (default = automatic) 
            labx:      label for the x-axis        (default = None)      
            laby:      label for the y-axis        (default = None)      
            rangex2:   range for 2nd x-axis        (default = None)      
            rangey2:   range 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))
            image:     color palette for image     (default = 'rainbow') 
            contours:  list of contour values      (default = None)      
            line:      contour line style          (default = 1 (solid)) 
            width:     contour line width          (default = 1 (thin))  
            color:     contour line color          (default = 'white')   
            labels:    color of contour labels     (default = None)      
            labelint:  contour label spacing       (default = 20)        
            labelmin:  min contour label spacing   (default = 20)        
            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))    
            noscale:   turn off auto scaling       (default = 0 (no))    
            aspect:    Aspect ratio                (default = 1 (square))
            ticks:     Ticks point in or out       (default = 'out')   
            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_.
    """
    # Make sure the input data is a 2D array
    z = Num.asarray(z);
    if not len(z.shape)==2:
        print 'Input data array must be 2 dimensional.'
        return
    # Announce the global variables we will be using
    global ppgplot_dev_open_, ppgplot_dev_prep_, pgpalette
    # Define the X and Y axis limits if needed
    if x is None: x=Num.arange(z.shape[1], dtype='f')
    else: x = Num.asarray(x)
    if y is None: y=Num.arange(z.shape[0], dtype='f')
    else: y = Num.asarray(y)
    # Determine the scaling to use for the axes
    if rangex is None: rangex=[Num.minimum.reduce(x), \
                             Num.maximum.reduce(x)]
    if rangey is None: rangey=[Num.minimum.reduce(y), \
                             Num.maximum.reduce(y)]
    if rangez is None: rangez=[Num.minimum.reduce(Num.ravel(z)), \
                             Num.maximum.reduce(Num.ravel(z))]
    # Prep the plotting device...
    if (not ppgplot_dev_prep_):
        prepplot(rangex, rangey, title, labx, laby, \
                 rangex2, rangey2, labx2, laby2, logx, logy, \
                 logx2, logy2, font, fontsize, id, aspect, \
                 ticks, panels, device=device)
    if image is not None:
        # Set the color indices and the color table
        lo_col_ind, hi_col_ind = ppgplot.pgqcol()
        lo_col_ind = lo_col_ind + 2
        ppgplot.pgscir(lo_col_ind, hi_col_ind)
        pgpalette.setpalette(image)
        ppgplot.pgctab(pgpalette.l,pgpalette.r,pgpalette.g,pgpalette.b)
        # Construct the image
        ppgplot.pgimag_s(z, 0.0, 0.0, rangex[0], rangey[0], \
                         rangex[1], rangey[1])  
        reset_colors()
    if contours is not None:
        contours = Num.asarray(contours)
        # Choose the line style
        ppgplot.pgsls(line)
        # Choose the line width
        ppgplot.pgslw(width)
        # Choose the line color for the contourlines
        if type(color) == types.StringType:
            ppgplot.pgsci(ppgplot_colors_[color])
        else:
            ppgplot.pgsci(color)
        # Construct the contours
        ppgplot.pgcont_s(z, len(contours), contours, rangex[0], \
                         rangey[0], rangex[1], rangey[1])  
        # Label the contours if requested
        if labels is not None:
            # Choose the line color for the contourlines
            if type(labels) == types.StringType:
                ppgplot.pgsci(ppgplot_colors_[labels])
            else:
                ppgplot.pgsci(labels)
            for i in range(len(contours)):
                ppgplot.pgconl_s(z, contours[i], str(contours[i]),
                                 labelint, labelmin)
		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)
		ppgplot.pggray(boostedFullFrame, 0, cols-1, 0, rows-1, 0, 255, pgPlotTransform)
		ppgplot.pgsfs(2)   # Set fill style to 'outline'
		ppgplot.pgsci(3)   # Set the colour to 'green'
		for s in allSources:
			x, y = s[0], s[1]
			ppgplot.pgcirc(x,y, 10)
		
		
	""" End of the prework """

	rdat.set(1)		# Reset back to the first frame
	
	frameRange = maximumFrames - startFrame + 1
	
	if arg.numframes!=None:
		requestedNumFrames = arg.numframes
		if requestedNumFrames<(frameRange):
			frameRange = requestedNumFrames
Example #51
0
def main(options):

	debug = options.debug
        MSlist = []
        for inmspart in options.inms.split(','):
                for msname in glob.iglob(inmspart):
	                MSlist.append(msname)
	if len(MSlist) == 0:
		print 'Error: You must specify at least one MS name.'
		print '       Use "uvplot.py -h" to get help.'
		return
        if len(MSlist) > 1:
                print 'WARNING: Antenna selection (other than all) may not work well'
                print '         when plotting more than one MS. Carefully inspect the'
                print '         listings of antenna numbers/names!'
	device = options.device
	if device=='?':
		ppgplot.pgldev()
		return
        if options.title == '':
                plottitle = options.inms
        else:
                plottitle = options.title
	axlimits = options.axlimits.split(',')
	if len(axlimits) == 4:
		xmin,xmax,ymin,ymax = axlimits
	else:
		print 'Error: You must specify four axis limits'
		return
	timeslots = options.timeslots.split(',')
	if len(timeslots) != 3:
		print 'Error: Timeslots format is start,skip,end'
		return
	for i in range(len(timeslots)):
		timeslots[i] = int(timeslots[i])
		if timeslots[i] < 0:
			print 'Error: timeslots values must not be negative'
			return
        antToPlotSpl = options.antennas.split(',')
        antToPlot = []
        for i in range(len(antToPlotSpl)):
                tmpspl = antToPlotSpl[i].split('..')
                if len(tmpspl) == 1:
                        antToPlot.append(int(antToPlotSpl[i]))
                elif len(tmpspl) == 2:
                        for j in range(int(tmpspl[0]),int(tmpspl[1])+1):
                                antToPlot.append(j)
                else:
                        print 'Error: Could not understand antenna list.'
                        return
	queryMode = options.query
        plotLambda = options.kilolambda

        badval = 0.0
        xaxisvals = numpy.array([])
        yaxisvals = numpy.array([])
        savex = numpy.array([])
        savey = numpy.array([])
        numPlotted = 0
        for inputMS in MSlist:
	        # open the main table and print some info about the MS
                print 'Getting info for', inputMS
	        t = pt.table(inputMS, readonly=True, ack=False)
                tfreq = pt.table(t.getkeyword('SPECTRAL_WINDOW'),readonly=True,ack=False)
                ref_freq = tfreq.getcol('REF_FREQUENCY',nrow=1)[0]
                ch_freq = tfreq.getcol('CHAN_FREQ',nrow=1)[0]
                print 'Reference frequency:\t%f MHz' % (ref_freq/1.e6)
                if options.wideband:
                        ref_wavelength = 2.99792458e8/ch_freq
                else:
                        ref_wavelength = [2.99792458e8/ref_freq]
                print 'Reference wavelength:\t%f m' % (ref_wavelength[0])
                if options.sameuv and numPlotted > 0:
                        print 'Assuming same uvw as first MS!'
                        if plotLambda:
                                for w in ref_wavelength:
                                        xaxisvals = numpy.append(xaxisvals,[savex/w/1000.,-savex/w/1000.])
                                        yaxisvals = numpy.append(yaxisvals,[savey/w/1000.,-savey/w/1000.])
                        else:
                                print 'Plotting more than one MS with same uv, all in meters... do you want -k?'
                                xaxisvals = numpy.append(xaxisvals,[savex,-savex])
                                yaxisvals = numpy.append(yaxisvals,[savey,-savey])
                        continue
                        
	        firstTime = t.getcell("TIME", 0)
	        lastTime = t.getcell("TIME", t.nrows()-1)
	        intTime = t.getcell("INTERVAL", 0)
	        print 'Integration time:\t%f sec' % (intTime)
	        nTimeslots = (lastTime - firstTime) / intTime
	        print 'Number of timeslots:\t%d' % (nTimeslots)
                if timeslots[1] == 0:
                        if nTimeslots >= 100:
                                timeskip = int(nTimeslots/100)
                        else:
                                timeskip = 1
                else:
                        timeskip = int(timeslots[1])
                print 'For each baseline, plotting one point every %d samples' % (timeskip)
       	        if timeslots[2] == 0:
        		timeslots[2] = nTimeslots
        	# open the antenna subtable
        	tant = pt.table(t.getkeyword('ANTENNA'), readonly=True, ack=False)
        
        	# Station names
        	antList = tant.getcol('NAME')
                if len(antToPlot)==1 and antToPlot[0]==-1:
                        antToPlot = range(len(antList))
        	print 'Station list (only starred stations will be plotted):'
        	for i in range(len(antList)):
                        star = ' '
                        if i in antToPlot: star = '*'
        		print '%s %2d\t%s' % (star, i, antList[i])
        
        	# Bail if we're in query mode
        	if queryMode:
        		return
        
        	# select by time from the beginning, and only use specified antennas
        	tsel = t.query('TIME >= %f AND TIME <= %f AND ANTENNA1 IN %s AND ANTENNA2 IN %s' % (firstTime+timeslots[0]*intTime,firstTime+timeslots[2]*intTime,str(antToPlot),str(antToPlot)), columns='ANTENNA1,ANTENNA2,UVW')

        	# Now we loop through the baselines
                i = 0
                nb = (len(antToPlot)*(len(antToPlot)-1))/2
                sys.stdout.write('Reading uvw for %d baselines: %04d/%04d'%(nb,i,nb))
                sys.stdout.flush()
	        for tpart in tsel.iter(["ANTENNA1","ANTENNA2"]):
        		ant1 = tpart.getcell("ANTENNA1", 0)
        		ant2 = tpart.getcell("ANTENNA2", 0)
                        if ant1 not in antToPlot or ant2 not in antToPlot: continue
        		if ant1 == ant2: continue
                        i += 1
                        sys.stdout.write('\b\b\b\b\b\b\b\b\b%04d/%04d'%(i,nb))
                        sys.stdout.flush()
        		# Get the values to plot
                        uvw = tpart.getcol('UVW', rowincr=timeskip)
                        if numPlotted == 0:
                                savex = numpy.append(savex,[uvw[:,0],-uvw[:,0]])
                                savey = numpy.append(savey,[uvw[:,1],-uvw[:,1]])
                        if plotLambda:
                                for w in ref_wavelength:
                                        xaxisvals = numpy.append(xaxisvals,[uvw[:,0]/w/1000.,-uvw[:,0]/w/1000.])
                                        yaxisvals = numpy.append(yaxisvals,[uvw[:,1]/w/1000.,-uvw[:,1]/w/1000.])
                        else:
                                xaxisvals = numpy.append(xaxisvals,[uvw[:,0],-uvw[:,0]])
                                yaxisvals = numpy.append(yaxisvals,[uvw[:,1],-uvw[:,1]])
        		#if debug:
                        #        print uvw.shape
        		#	print xaxisvals.shape
        		#	print yaxisvals.shape
                        #else:
                        #        sys.stdout.write('.')
                        #        sys.stdout.flush()
                sys.stdout.write(' Done!\n')
                numPlotted += 1

        print 'Plotting uv points ...'
	# open the graphics device, using only one panel
	ppgplot.pgbeg(device, 1, 1)
	# set the font size
	ppgplot.pgsch(1)
	ppgplot.pgvstd()

	# Plot the data
        if debug:
                print xaxisvals
        xaxisvals = numpy.array(xaxisvals)
        yaxisvals = numpy.array(yaxisvals)
        tmpvals = numpy.sqrt(xaxisvals**2+yaxisvals**2)
	ppgplot.pgsci(1)
        uvmax = max(xaxisvals.max(),yaxisvals.max())
        uvmin = min(xaxisvals.min(),yaxisvals.min())
        uvuplim = 0.02*(uvmax-uvmin)+uvmax
        uvlolim = uvmin-0.02*(uvmax-uvmin)
	if xmin == '':
		minx = uvlolim
	else:
		minx = float(xmin)
	if xmax == '':
		maxx = uvuplim
	else:
		maxx = float(xmax)
	if ymin == '':
		miny = uvlolim
	else:
		miny = float(ymin)
	if ymax == '':
		maxy = uvuplim
	else:
		maxy = float(ymax)
	if minx == maxx:
		minx = -1.0
		maxx = 1.0
	if miny == maxy:
		miny = -1.0
		maxy = 1.0
        ppgplot.pgpage()
	ppgplot.pgswin(minx,maxx,miny,maxy)
        ppgplot.pgbox('BCNST',0.0,0,'BCNST',0.0,0)
        if plotLambda:
	        ppgplot.pglab('u [k\gl]', 'v [k\gl]', '%s'%(plottitle))
        else:
	        ppgplot.pglab('u [m]', 'v [m]', '%s'%(plottitle))
	ppgplot.pgpt(xaxisvals[tmpvals!=badval], yaxisvals[tmpvals!=badval], 1)

	# Close the PGPLOT device
	ppgplot.pgclos()
		lowerFlambda = min(modelSpectrum.flux)
		upperFlambda = max(modelSpectrum.flux)
		lowerFlambda = 0
		
		lowerFlux = 0
		upperFlux = 0
		
		for s in modelSpectra:
			fmax = max(s.flux)
			if fmax>upperFlux:
				upperFlux = fmax
		
		ppgplot.pgenv(lowerWavelength, upperWavelength, lowerFlux, upperFlux, 0, 0)
		colour = 1
		for s in modelSpectra:
			ppgplot.pgsci(colour)
			ppgplot.pgline(s.wavelengths, s.flux)
			plotx = 8500
			ploty = s.getNearestFlux(plotx)
			ppgplot.pgptxt(plotx, ploty, 0, 0, "%2.0f'"%(s.angle)) 
			colour+= 1
			if colour>15: colour = 1
			
		ppgplot.pgsci(1)	
		label = "B=%.0f MG, T=%.1f keV"%(field, temperature)
		ppgplot.pglab("wavelength", "i_0", label)
		
	ppgplot.pgclos()

	if arg.device!=None:
		# Write to an additional output devide