Beispiel #1
0
    def plot(self):
        """
            Metodo che effettua il plot della curva, mostrando le condizioni di controllo
            (derivata prima e seconda) come frecce
        """

        positionPoints = self.cntrl[::self.rpp]
        firstDerivatives = self.cntrl[1::self.rpp]
        secondDerivatives = self.cntrl[2::self.rpp]

        xmin = positionPoints[:, 0].min()
        xmax = positionPoints[:, 0].max()
        ymin = positionPoints[:, 1].min()
        ymax = positionPoints[:, 1].max()

        offset = max(abs(np.append(firstDerivatives, secondDerivatives)))

        pl.plot(self.points[:, 0], self.points[:, 1])

        ax = pl.gca()

        for pt, d1, d2 in zip(positionPoints, firstDerivatives,
                              secondDerivatives):
            ax.add_patch(
                pl.Arrow(pt[0],
                         pt[1],
                         d1[0],
                         d1[1],
                         label='d1',
                         color='r',
                         width=0.2,
                         alpha=0.3))
            ax.add_patch(
                pl.Arrow(pt[0],
                         pt[1],
                         d2[0],
                         d2[1],
                         label='d2',
                         color='g',
                         width=0.2,
                         alpha=0.3))

        axis_limits = [
            xmin - offset, xmax + offset, ymin - offset, ymax + offset
        ]

        pl.axis(axis_limits)
        return
Beispiel #2
0
 def make_arrow(index, coord1, coord2, plot):
     startx = sat.data['SM_xyz'][index, coord1]
     starty = sat.data['SM_xyz'][index, coord2]
     lengthx = sat.data['SM_xyz'][index + 10, coord1] - startx
     lengthy = sat.data['SM_xyz'][index + 10, coord2] - starty
     xlims = plot.get_xlim()
     dx = xlims[1] - xlims[0]
     arrow = plt.Arrow(startx,
                       starty,
                       lengthx,
                       lengthy,
                       width=dx / 15.0,
                       fc='g',
                       ec='g')
     plot.add_patch(arrow)
Beispiel #3
0
    def draw_arrow(self, ax):
        """Draws the velocity vector to screen.

        Arguments:
            ax (axes.Axes): Axes object to draw the velocity vector on.
        """
        
        # If a velocity vector already exists on screen, remove it
        if self.__arrow_patch:
            self.__arrow_patch.remove()
        
        # Draw the velocity vector
        r = self.position()
        u = self.velocity() / Ball.rms_speed
        arrow_patch = pl.Arrow(r[0], r[1], u[0], u[1], width = 0.2, ec = "b")
        self.__arrow_patch = ax.add_patch(arrow_patch)
Beispiel #4
0
def drawArrow (axes):
    """
    Рисование стрелки
    """
    arrow_x0 = -1.0
    arrow_y0 = 0.5
    arrow_dx = 1
    arrow_dy = 0.5

    arrow = pylab.Arrow (arrow_x0,
                         arrow_y0,
                         arrow_dx,
                         arrow_dy,
                         width=0.2,
                         color="g")
    axes.add_patch (arrow)
    pylab.text (-0.5, 1.0, "Arrow", horizontalalignment="center")
Beispiel #5
0
 def add_edge(self, p0, p1, normal, marker):
     assert marker < self._num_markers
     self.color_count[marker] += 1
     if self.color_count[marker] == 1:
         pylab.plot([p0[0], p1[0]], [p0[1], p1[1]],
                    label=str(marker),
                    **self._styles[marker])
     else:
         pylab.plot([p0[0], p1[0]], [p0[1], p1[1]], **self._styles[marker])
     # normal
     p0 = (p0 + p1) / 2
     d = normal * 0.1
     pylab.gca().add_patch(
         pylab.Arrow(p0[0],
                     p0[1],
                     d[0],
                     d[1],
                     width=0.05,
                     color=self._styles[marker]["color"]))
Beispiel #6
0
def plotRadial():
    # Constants take from Bender et al. (2005)
    cc = objects.Constants()
    m31mass = 1.4e8
    m31dist = 760000.0

    # Construct an array of radii out to 5 arcsec in steps of 0.05''
    r = (na.arange(12 * 5) * 0.05) + 0.05
    r_au = r * m31dist
    r_pc = r_au / cc.au_in_pc
    r_cm = r_au * cc.cm_in_au

    # Determine the theoretical amount for a vs. r
    a_cm_s2 = cc.G * m31mass * cc.msun / r_cm**2
    a_km_s_yr = a_cm_s2 * cc.sec_in_yr / 1.0e5
    a_mas_yr2 = a_cm_s2 * pow(cc.sec_in_yr, 2) * 1000.0
    a_mas_yr2 /= (cc.cm_in_au * m31dist)

    # Plot circular velocity in both mas/yr and km/s
    v_cm_s = na.sqrt(cc.G * m31mass * cc.msun / r_cm)
    v_km_s = v_cm_s / 1.0e5
    v_mas_yr = v_cm_s * cc.sec_in_yr * 1000.0 / (cc.cm_in_au * m31dist)

    masyr_kms = (1.0 / 1000.0) * m31dist * cc.cm_in_au / (1.0e5 * cc.sec_in_yr)
    masyr2_kmsyr = (1.0 / 1000.0) * m31dist * cc.cm_in_au
    masyr2_kmsyr /= 1.0e5 * pow(cc.sec_in_yr, 2)

    ##########
    #
    # Calculate some useful quantities for Keck/TMT
    #
    ##########
    dKeck = 10.0
    dTMT = 10.0

    resKeckK = 1.0e3 * 0.25 * 2.2 / dKeck  # K (GC) on Keck has similar Strehl
    resTMTZ = 1.0e3 * 0.25 * 1.035 / dTMT  # to obs with Z on TMT (mas).

    posErrKeck = 0.15  # mas
    ratioKeck = resKeckK / posErrKeck

    posErrTMT = resTMTZ / ratioKeck
    print('Estimated positional error for TMT at Z-band: %5.3f' % (posErrTMT))

    # 1 years, 3 sigma
    velLo1 = 3.0 * posErrTMT
    velLoKms1 = velLo1 * masyr_kms

    # 3 years, 3 sigma
    velLo3 = posErrTMT
    velLoKms3 = velLo3 * masyr_kms

    print('Lowest detectable velocities in:')
    print('\t 1 year, 3 sigma -- low vel = %4.2f mas/yr = %4d km/s' % \
          (velLo1, velLoKms1))
    print('\t 3 year, 3 sigma -- low vel = %4.2f mas/yr = %4d km/s' % \
          (velLo3, velLoKms3))

    ##########
    #
    # Velocity vs. Radius
    #
    ##########
    pylab.figure(2, figsize=(7, 7))
    pylab.clf()

    #     pylab.plot(r, v_mas_yr, linewidth=2)
    #     pylab.xlabel('Distance from Mbh (arcsec)')
    #     pylab.ylabel('Circular Velocity (mas/yr)')
    pylab.plot(r, v_km_s, linewidth=2)
    pylab.xlabel('Distance from Mbh (arcsec)')
    pylab.ylabel('Circular Velocity (km/s)')

    # Detection limit
    #     pylab.plot([0, 10], [velLo1, velLo1], 'k--')
    #     pylab.plot([0, 10], [velLo3, velLo3], 'k--')
    #     pylab.text(2.5, velLo1, '1 year')
    #     pylab.text(2.5, velLo3, '3 years')
    pylab.plot([0, 10], [velLoKms1, velLoKms1], 'k--')
    pylab.plot([0, 10], [velLoKms3, velLoKms3], 'k--')
    pylab.plot([0, 10], [30.0, 30.0], 'k--')
    pylab.text(2.5, velLoKms1, '1 year')
    pylab.text(2.5, velLoKms3, '3 years')
    pylab.text(0.3, 35.0, 'Radial Vel.')

    arr1 = pylab.Arrow(2.4, velLoKms1, 0, 0.04 * masyr_kms, width=0.09)
    arr3 = pylab.Arrow(2.4, velLoKms3, 0, 0.04 * masyr_kms, width=0.09)
    arrRv = pylab.Arrow(0.2, 30.0, 0, 0.04 * masyr_kms, width=0.09)
    fig = pylab.gca()
    fig.add_patch(arr1)
    fig.add_patch(arr3)
    fig.add_patch(arrRv)

    str = '0.1 mas/yr = %4d km/s' % (0.1 * masyr_kms)
    pylab.axis([0.0, 3, 0.0, 0.5 * masyr_kms])
    pylab.text(1.3, 0.45 * masyr_kms, str)
    pylab.savefig('m31theory_vel.png')
    pylab.savefig('m31theory_vel.eps')

    pylab.clf()
    pylab.plot(r, a_mas_yr2)
    pylab.xlabel('Distance from Mbh (arcsec)')
    pylab.ylabel('Acceleration (mas/yr^2)')
    str = '1 mas/yr^2 = %5.2f km/s/yr' % (1.0 * masyr2_kmsyr)
    pylab.text(1.0e-3, 1.5, str)
    pylab.savefig('m31theory_acc.eps')
    pylab.savefig('m31theory_acc.png')
Beispiel #7
0
def mass_luminosity():
    # Load up observed data:
    wd1_data = '/u/jlu/data/Wd1/hst/from_jay/EXPORT_WEST1.2012.02.04/wd1_catalog.fits'
    data = atpy.Table(wd1_data)

    iso = load_isochrone()

    # Determine median astrometric and photometric error as a function of
    # magnitude for both F814W and F125W. Use Y as a proxy for astrometric error.
    magBinSize = 0.25
    magBinCenter = np.arange(12, 28, magBinSize)
    yerr814w = np.zeros(len(magBinCenter), dtype=float)
    yerr125w = np.zeros(len(magBinCenter), dtype=float)
    merr814w = np.zeros(len(magBinCenter), dtype=float)
    merr125w = np.zeros(len(magBinCenter), dtype=float)

    for ii in range(len(magBinCenter)):
        mlo = magBinCenter[ii] - (magBinSize/2.0)
        mhi = magBinCenter[ii] + (magBinSize/2.0)

        idx814 = np.where((data.mag814 >= mlo) & (data.mag814 < mhi) &
                          (np.isnan(data.y2005_e) == False))[0]
        idx125 = np.where((data.mag125 >= mlo) & (data.mag125 < mhi) &
                          (np.isnan(data.y2010_e) == False))[0]

        if len(idx814) > 1:
            yerr814w[ii] = statsIter.mean(data.y2005_e[idx814], hsigma=3, lsigma=5, iter=10)
            merr814w[ii] = statsIter.mean(data.mag814_e[idx814], hsigma=3, lsigma=5, iter=10)
        else:
            yerr814w[ii] = np.nan
            merr814w[ii] = np.nan

        if len(idx125) > 1:
            yerr125w[ii] = statsIter.mean(data.y2010_e[idx125], hsigma=3, lsigma=5, iter=10)
            merr125w[ii] = statsIter.mean(data.mag125_e[idx125], hsigma=3, lsigma=5, iter=10)
        else:
            yerr125w[ii] = np.nan
            merr125w[ii] = np.nan

    # Assume we get an additional sqrt(3) by combining the 3 filters together.
    yerr125w /= math.sqrt(3.0)
            
    py.clf()
    py.plot(magBinCenter, yerr814w*scale, 'b.', ms=10,
            label='ACS-WFC F814W')
    py.plot(magBinCenter, yerr125w*scale, 'r.', ms=10,
            label='WFC3-IR F125W')
    py.xlabel('Magnitude')
    py.ylabel('Positional Error (mas)')
    py.legend(numpoints=1, loc='upper left')
    py.ylim(0, 5)
    py.savefig(plotDir + 'avg_poserr_f814w_vs_f125w.png')

    py.clf()
    py.plot(magBinCenter, merr814w, 'b.', ms=10,
            label='ACS-WFC F814W')
    py.plot(magBinCenter, merr125w, 'r.', ms=10,
            label='WFC3-IR F125W')
    py.xlabel('Magnitude')
    py.ylabel('Photometric Error (mag)')
    py.legend(numpoints=1, loc='upper left')
    py.ylim(0, 0.1)
    py.savefig(plotDir + 'avg_magerr_f814w_vs_f125w.png')

    idx814 = np.where((yerr814w*scale < 2) & (merr814w < 0.04))[0]
    idx125 = np.where((yerr125w*scale < 2) & (merr125w < 0.04))[0]

    lim814 = magBinCenter[idx814[-1]]
    lim125 = magBinCenter[idx125[-1]]

    print 'Limit for F814W data (pos err < 2 mas, mag err < 0.04: %5.2f' % \
        lim814
    print 'Limit for F125W data (pos err < 2 mas, mag err < 0.04: %5.2f' % \
        lim125

    ii814 = np.abs(iso.mag814w - lim814).argmin()
    ii125 = np.abs(iso.mag125w - lim125).argmin()

    # massLim814 = iso.M[ii814]
    # magLim814 = iso.mag814w[ii814]
    massLim814 = 0.85
    magLim814 = 23.5
    massLim125 = iso.M[ii125]
    magLim125 = iso.mag125w[ii125]

    py.clf()
    py.semilogx(iso.M, iso.mag814w, 'b-', ms=2, label='ACS-WFC F814W',
                linewidth=2)
    py.semilogx(iso.M, iso.mag125w, 'r-', ms=2, label='WFC3-IR F125W',
                linewidth=2)
    py.gca().invert_yaxis()
    py.plot([massLim814, massLim814], [magLim814-2, magLim814+2], 'b-',
            linewidth=4)
    py.plot([massLim125, massLim125], [magLim125-2, magLim125+2], 'r-',
            linewidth=4)
    ar1 = py.Arrow(massLim814, magLim814+0.1, 1.0, 0, color='blue')
    ar2 = py.Arrow(massLim125, magLim125+0.1, 0.15, 0, color='red')
    py.gca().add_patch(ar1)
    py.gca().add_patch(ar2)
    py.xlabel('Mass (Msun)')
    py.ylabel('Magnitude (F814W or F125W)')
    py.legend(loc='upper left')
    py.savefig(plotDir + 'mass_magnitude_with_limits.png')

    # Also plot a color-magnitude diagram and show the two mass limits
    py.clf()
    py.plot(data.mag814 - data.mag160, data.mag814, 'k.', ms=2)
    py.plot(iso.mag814w - iso.mag160w, iso.mag814w, 'b-', ms=2,
            linewidth=2)
    py.plot(iso.mag814w[ii814] - iso.mag160w[ii814], iso.mag814w[ii814],
            'b^', ms=10)
    py.plot(iso.mag814w[ii125] - iso.mag160w[ii125], iso.mag814w[ii125],
            'r^', ms=10)
    py.gca().invert_yaxis()
    py.xlim(0, 10)
    py.ylim(28, 13)
    py.xlabel('F814W - F160W')
    py.ylabel('F814W')
    py.savefig(plotDir + 'cmd_optical_iso.png')

    py.clf()
    py.plot(data.mag125 - data.mag160, data.mag125, 'k.', ms=2)
    py.plot(iso.mag125w - iso.mag160w, iso.mag125w, 'r-', ms=2,
            linewidth=2)
    py.plot(iso.mag125w[ii814] - iso.mag160w[ii814], iso.mag125w[ii814],
            'b^', ms=10)
    py.plot(iso.mag125w[ii125] - iso.mag160w[ii125], iso.mag125w[ii125],
            'r^', ms=10)
    py.gca().invert_yaxis()
    py.xlim(0, 3)
    py.ylim(24, 10)
    py.xlabel('F125W - F160W')
    py.ylabel('F125W')
    py.savefig(plotDir + 'cmd_infrared_iso.png')
Beispiel #8
0
def lag():

    font = {'color': '#909090', 'fontsize': 6}
    extractMe = {
        'RequestQueue.queueRequest': "Q",
        'Connection.openHttpConnection()': "O",
        'Request.sendRequest()': "S",
        'Request.requestSent()': "T",
        'processRequests()': 'R',
        'Request.readResponse():': "D",         # done
        'clearPipe()': 'U',	                    # unqueue
        'Request.readResponse()': 'B',          # read data block
        'Request.readResponseStatus():': 'HR',  # read http response line
        'hdr': 'H',                             # http header
        }
    keys = extractMe.keys()

    f = open(sys.argv[1], "r")

    t0 = None

    # thread, queued, opened, send, sent, reading, read, uri, server, y
    # 0       1       2       3     4     5        6     7    8       9
    vals = []

    queued = Queue()
    opened = {"http0": None,
              "http1": None,
              "http2": None,
              "http3": None,
              "http4": None,
              "http5": None}
    active = {"http0": [],
              "http1": [],
              "http2": [],
              "http3": [],
              "http4": [],
              "http5": []}
    connectionCount = 0
    byteCount = 0
    killed = [[], []]

    while (True):
        line = f.readline()
        if len(line) == 0: break

        splitup = line.split()

        # http only
        if splitup[0] != "V/http": continue

        x = splitup[3:]

        # filter to named lines
        if x[2] not in keys: continue
        x[2] = extractMe[x[2]]

        # normalize time
        if t0 == None: t0 = int(x[0])
        x[0] = int(x[0]) - t0

        thread, action = x[1], x[2]
        if action == "Q":
            time, url = x[0], x[3]
            queued.add(url, time)
        elif action == "O":
            # save opened time and server for this thread, so we can stuff it in l8r
            time, thread, host = x[0], x[1], x[4]
            opened[thread] = [time, host, connectionCount]
            connectionCount += 1
        elif action == "S":
            time, thread, url = x[0], x[1], x[3]
            opentime, host, connection = opened[thread]
            qtime = queued.get(url)
            record = [thread, qtime, opentime, time, None, None, None, url, host, connection]
            active[thread].append(record)
        elif action == "T":
            time, thread = x[0], x[1]
            record = active[thread][-1]
            record[4] = time
        elif action == "R":
            print x
            if x[3] in ["sleep", "no", "wait"]: continue
            time, thread, = x[0], x[1]
            record = active[thread][0]
            record[5] = time
        elif action == 'U':
            thread = x[1]
            record = active[thread][0]
            killed[0].append(record[9])
            killed[1].append(x[0])
            queued.add(record[7], record[1])
            del active[thread][0]
        elif action == "D":
            time, thread = x[0], x[1]
            record = active[thread][0]
            record[6] = time
            vals.append(record)
            del active[thread][0]
            print record
            # print record[3] / 1000, record[6] / 1000, record[7]
        elif action == "B":
            byteCount += int(x[3])
        elif action == "HR":
            byteCount += int(x[2])

    f.close()

    rng = range(connectionCount)

    opened = []
    drawn = [False for x in rng]
    for val in vals:
        y= val[9]
        if not drawn[y]:
            drawn[y] = True
            opened.append(val[2])
            pylab.text(0, y - 0.25, "%s %s %s" % (val[9], val[0][4], val[8]), font)

    # define limits
    # pylab.plot([vals[-1][6]], rng)

    print opened, rng
    pylab.plot(opened, rng, 'ro')
    pylab.plot(killed[1], killed[0], 'rx')

    for val in vals:
        thread, queued, opened, send, sent, reading, read, uri, server, y = val
        # send arrow
        arrow = pylab.Arrow(send, y, sent - send, 0)
        arrow.set_facecolor("g")
        ax = pylab.gca()
        ax.add_patch(arrow)
        # read arrow
        arrow = pylab.Arrow(reading, y, read - reading, 0)
        arrow.set_facecolor("r")
        ax = pylab.gca()
        ax.add_patch(arrow)

    caption = \
            "\nrequests: %s\n" % len(vals) + \
            "byteCount: %s\n" % byteCount + \
            "data rate: %s\n" % (1000 * byteCount / vals[-1][6])+ \
            "connections: %s\n" % connectionCount

    pylab.figtext(0.82, 0.30, caption, bbox=dict(facecolor='lightgrey', alpha=0.5))

    # print lines, [[x, x] for x in range(len(vals))]
    # pylab.plot(lines, [[x, x] for x in range(len(vals))], 'r-')

    pylab.grid()
    pylab.show()
def plot_connect_powerspec(fn,
                           psdsize=32,
                           largescalecutoff=250,
                           savefigs=False,
                           **kwargs):
    powerspec_grid = pyfits.getdata(
        os.path.splitext(fn)[0] + "_powerspec_grid_%i.fits" % psdsize)
    header = pyfits.getheader(
        os.path.splitext(fn)[0] + "_powerspec_grid_%i.fits" % psdsize)
    powerlaw_fit_grid = pyfits.getdata(
        os.path.splitext(fn)[0] + "_powerlaw_fit_grid_%i.fits" % psdsize)
    data = pyfits.getdata(fn)
    angle_grid = pyfits.getdata(
        os.path.splitext(fn)[0] + "_angle_fit_grid_%i.fits" % psdsize)
    anglespec_grid = pyfits.getdata(
        os.path.splitext(fn)[0] + "_anglespec_grid_%i.fits" % psdsize)
    angleheader = pyfits.getheader(
        os.path.splitext(fn)[0] + "_anglespec_grid_%i.fits" % psdsize)

    rr = (np.arange(header.get('NAXIS3')) - header.get('CRPIX3') +
          1) * header.get('CD3_3') + header.get('CRVAL3')
    rr_as = (header.get('CD2_2') / float(psdsize) * 3600.) / rr
    az = (np.arange(angleheader.get('NAXIS3')) - angleheader.get('CRPIX3') +
          1) * angleheader.get('CD3_3') + angleheader.get('CRVAL3')
    OK = rr_as < largescalecutoff

    pylab.figure(1)
    pylab.clf()
    ax = pylab.imshow(np.arcsinh(data), **kwargs).axes
    modulus_lon = data.shape[1] % psdsize
    modulus_lat = data.shape[0] % psdsize
    ax.xaxis.set_major_locator(OffsetMultipleLocator(psdsize,
                                                     modulus_lon / 2.))
    ax.yaxis.set_major_locator(OffsetMultipleLocator(psdsize,
                                                     modulus_lat / 2.))
    ax.xaxis.grid(True, 'major')
    ax.yaxis.grid(True, 'major')

    def plot_powerfit(event, powerspec_grid=powerspec_grid):
        if event.xdata is not None and event.ydata is not None:
            print event.xdata, event.ydata, event.xdata / psdsize, event.ydata / psdsize
            zz = powerspec_grid[:, event.ydata / psdsize,
                                event.xdata / psdsize]
            zaz = anglespec_grid[:, event.ydata / psdsize,
                                 event.xdata / psdsize]
            if zz.sum() == 0:
                print "No data at that point"
            else:
                (scale1, scale2, breakpoint, pow1,
                 pow2), mpf = powerfit.brokenpowerfit(rr[OK],
                                                      zz[OK],
                                                      breakpoint=0.23,
                                                      alphaguess1=-2.0,
                                                      alphaguess2=0.0,
                                                      scaleguess=np.median(zz))
                pylab.figure(3)
                pylab.clf()
                pylab.loglog(rr, zz, 'gray')
                pylab.loglog(rr[OK], zz[OK], 'k')
                pylab.plot(
                    rr,
                    scale1 * rr**pow1 * (rr < breakpoint) + scale2 * rr**pow2 *
                    (rr >= breakpoint), 'r')
                pylab.annotate("p1 =    %8.3f" % pow1, [0.75, 0.85],
                               xycoords='figure fraction')
                pylab.annotate("p2 =    %8.3f" % pow2, [0.75, 0.80],
                               xycoords='figure fraction')
                pylab.annotate("break = %8.3f" % breakpoint, [0.75, 0.75],
                               xycoords='figure fraction')
                pylab.xlabel("Spatial Frequency (image size / length)")
                pylab.ylabel("Azimuthally Averaged Flux$^2$")
                pylab.title(os.path.split(fn)[1].replace(".fits", ""))
                if savefigs:
                    pylab.savefig(
                        fn.replace(
                            ".fits", "_powerspectrum_%i_%ix%i.png" %
                            (psdsize, event.xdata / psdsize,
                             event.ydata / psdsize)))

                pylab.figure(4)
                pylab.clf()
                pylab.plot(az, zaz, 'k')
                pylab.plot(
                    az,
                    sinfunc(*angle_grid[:, event.ydata / psdsize,
                                        event.xdata / psdsize])(az), 'r')
                pylab.xlabel("Position Angle")
                pylab.ylabel("Radially Averaged Flux$^2$")
                pylab.title(os.path.split(fn)[1].replace(".fits", ""))
                if savefigs:
                    pylab.savefig(
                        fn.replace(
                            ".fits", "_anglespectrum_%i_%ix%i.png" %
                            (psdsize, event.xdata / psdsize,
                             event.ydata / psdsize)))

                pylab.draw()

            for R in pylab.figure(1).axes[0].patches:
                R.set_visible(False)
                pylab.figure(1).axes[0].patches.remove(R)
            print "Click point: %10.2f,%10.2f   Rectangle coords: %10.2f,%10.2f" % (
                event.xdata, event.ydata, event.xdata - event.xdata % psdsize,
                event.ydata - event.ydata % psdsize)
            rect = Rectangle([
                event.xdata - event.xdata % psdsize + modulus_lon / 2.,
                event.ydata - event.ydata % psdsize + modulus_lat / 2.
            ],
                             psdsize,
                             psdsize,
                             facecolor='none')
            pylab.figure(1).axes[0].add_patch(rect)
            pylab.figure(1).canvas.draw()
            return rr, zz

    fig = pylab.figure(2)
    for ii in range(256):
        fig.canvas.mpl_disconnect(ii)
    pylab.clf()
    vmin, vmax = None, None
    if powerlaw_fit_grid.min() < -7: vmin = -7
    if powerlaw_fit_grid.max() > 0: vmax = 0
    imax = pylab.imshow(powerlaw_fit_grid,
                        vmin=vmin,
                        vmax=vmax,
                        extent=[
                            0, powerlaw_fit_grid.shape[1] * psdsize, 0,
                            powerlaw_fit_grid.shape[0] * psdsize
                        ])
    ax = imax.axes
    yy, xx = np.indices(angle_grid.shape[1:])
    for x, y, z in zip(
            xx.ravel(), yy.ravel(),
            np.reshape(
                angle_grid.swapaxes(0, 1).swapaxes(1, 2), [
                    angle_grid.shape[1] * angle_grid.shape[2],
                    angle_grid.shape[0]
                ])):
        arr = pylab.Arrow(
            x * psdsize + psdsize / 2.,
            y * psdsize + psdsize / 2.,
            psdsize / 2. * np.cos(z[2] - np.pi / 2.) * np.abs(z[1] / z[0]),
            psdsize / 2. * np.sin(z[2] - np.pi / 2.) * np.abs(z[1] / z[0]),
            edgecolor='white',
            facecolor='black',
            width=psdsize / 4.)
        ax.add_patch(arr)
    pylab.colorbar()
    return fig.canvas.mpl_connect('button_press_event', plot_powerfit)
Beispiel #10
0
def map_psf_stars(fitsfile, outfile, stars, title, vmin=10, vmax=1500):
    """
    Plot combo image for each field in W49 G48.9-0.3 and overlay the PSF
    stars.
    """
    datadir = '/u/jlu/data/w49/'
    outdir = '/u/jlu/work/w49/maps/'

    ##########
    # Load the fits file
    ##########
    img = pyfits.getdata(fitsfile)

    ##########
    # Calculate the coordinates in arcsec
    ##########
    scale = 0.00995

    # Image extent
    xaxis = (np.arange(img.shape[0]) - stars[0]['xpix']) * scale * -1.0
    yaxis = (np.arange(img.shape[1]) - stars[0]['ypix']) * scale

    for star in stars:
        # RA and Dec Offsets (in arcsec)
        star['x'] = (star['xpix'] - stars[0]['xpix']) * scale * -1.0
        star['y'] = (star['ypix'] - stars[0]['ypix']) * scale

    ##########
    # Plot Image
    ##########
    py.rc('font', **{'weight': 'bold'})
    py.clf()
    py.imshow(np.log10(img),
              cmap=py.cm.YlOrBr_r,
              vmin=math.log10(vmin),
              vmax=math.log10(vmax),
              extent=[xaxis[0], xaxis[-1], yaxis[0], yaxis[-1]])

    py.xlabel('R.A. Offset (arcsec)', fontweight='bold')
    py.ylabel('Dec. Offset (arcsec)', fontweight='bold')

    py.setp(py.getp(py.gca(), 'xticklabels'), fontweight='bold')
    py.setp(py.getp(py.gca(), 'yticklabels'), fontweight='bold')

    py.title(title, fontweight='bold')

    fig = py.gca()

    # Draw East/North arrows
    arr0 = np.array([xaxis[0] - 1.7, yaxis[0] + 0.3])
    arrLen = 1.0
    arrColor = 'black'
    north = py.Arrow(arr0[0],
                     arr0[1],
                     0,
                     arrLen,
                     width=0.3 * arrLen,
                     fill=True,
                     fc=arrColor,
                     ec=arrColor)
    east = py.Arrow(arr0[0],
                    arr0[1],
                    arrLen,
                    0,
                    width=0.3 * arrLen,
                    fill=True,
                    fc=arrColor,
                    ec=arrColor)

    fig.add_patch(north)
    fig.add_patch(east)

    py.text(arr0[0],
            arr0[1] + (1.1 * arrLen),
            'N',
            color=arrColor,
            weight='bold',
            horizontalalignment='center',
            verticalalignment='bottom')
    py.text(arr0[0] + (1.1 * arrLen),
            arr0[1],
            'E',
            color=arrColor,
            weight='bold',
            horizontalalignment='right',
            verticalalignment='center')

    ##########
    # Plot each PSF star.
    ##########
    for star in stars:
        # Encircle and Label coo star
        psfRadius = 0.2
        psfLabel = '%s\n[%6.3f, %6.3f]' % (star['name'], star['x'], star['y'])
        psfStar = py.Circle([star['x'], star['y']],
                            radius=psfRadius,
                            fill=False,
                            ec='black',
                            linewidth=3)
        fig.add_patch(psfStar)
        py.text(star['x'],
                star['y'] - (1.2 * psfRadius),
                psfLabel,
                fontweight='bold',
                color='black',
                fontsize=10,
                horizontalalignment='center',
                verticalalignment='top')

    # Save
    py.savefig(outfile)

    ##########
    # Generate a PSF star list for Starfinder... only print out to the screen.
    ##########
    print '########'
    print '#'
    print '# PRINTING PSF starlist for input to Starfinder.'
    print '#  -- paste everything below to a file.'
    print '#  -- example file is /u/jlu/code/idl/w49/psftables/w49_f1_psf.list'
    print '#'
    print '########'
    print '\n'

    print '# This file should contain sources we absolutely know exist '
    print '# (with names). Additionally, all sources should have velocities '
    print '# so that they can be found across multiple epochs. The Filt column '
    print '# shows what filters this star should NOT be used in '
    print '# (K=speckle, Kp,Lp,Ms = NIRC2). The PSF column specifies whether '
    print '# this is a PSF star (1) or just a secondary source (0).'
    print '#%-12s  %-4s  %-7s  %-7s  %-7s  %-7s  %-8s  %-4s  %-4s' % \
        ('Name', 'Mag', 'Xarc', 'Yarc', 'Vx', 'Vy', 't0', 'Filt', 'PSF?')
    for star in stars:
        print '%-13s  %4.1f  %7.3f  %7.3f  %7.3f  %7.3f  %8.3f  %-4s  %1d' % \
            (star['name'], star['mag'], star['x'], star['y'],
             0.0, 0.0, 2009.0, '-', 1)
Beispiel #11
0
def map_stars(fitsfile, outfile, coords, title, vmin=100, vmax=1500):
    """
    Plot 'first' image for each field in W49 G48.9-0.3. 
    """
    datadir = '/u/jlu/data/w49/'
    outdir = '/u/jlu/work/w49/maps/'

    ##########
    # W49 - Field 1
    ##########
    f_fits = pyfits.getdata(fitsfile)
    f_coo = coords

    py.clf()
    py.imshow(np.log10(f_fits),
              cmap=py.cm.YlOrBr_r,
              vmin=math.log10(vmin),
              vmax=math.log10(vmax))
    py.xlabel('X Axis (NIRC2 pixels)')
    py.ylabel('Y Axis (NIRC2 pixels)')

    fig = py.gca()

    py.text(512,
            1024,
            title,
            weight='bold',
            horizontalalignment='center',
            verticalalignment='bottom')

    # Encircle and Label coo star
    cooRadius = 40
    cooLabel = '[%d, %d]' % (f_coo[0], f_coo[1])
    cooStar = py.Circle(f_coo,
                        radius=cooRadius,
                        fill=False,
                        ec='black',
                        linewidth=3)
    fig.add_patch(cooStar)
    py.text(f_coo[0],
            f_coo[1] - (1.2 * cooRadius),
            cooLabel,
            weight='bold',
            color='black',
            horizontalalignment='center',
            verticalalignment='top')

    # Draw East/North arrows
    arr0 = [170, 30]
    arrLen = 100
    arrColor = 'black'
    north = py.Arrow(arr0[0],
                     arr0[1],
                     0,
                     arrLen,
                     width=0.3 * arrLen,
                     fill=True,
                     fc=arrColor,
                     ec=arrColor)
    east = py.Arrow(arr0[0],
                    arr0[1],
                    -arrLen,
                    0,
                    width=0.3 * arrLen,
                    fill=True,
                    fc=arrColor,
                    ec=arrColor)

    fig.add_patch(north)
    fig.add_patch(east)

    py.text(arr0[0],
            arr0[1] + (1.1 * arrLen),
            'N',
            color=arrColor,
            weight='bold',
            horizontalalignment='center',
            verticalalignment='bottom')
    py.text(arr0[0] - (1.1 * arrLen),
            arr0[1],
            'E',
            color=arrColor,
            weight='bold',
            horizontalalignment='right',
            verticalalignment='center')

    # Save
    py.savefig(outfile)
Beispiel #12
0
def plot_head_connectivity(connectivity,
                           sensorlocations,
                           plotsensors=False,
                           vmin=None,
                           vmax=None,
                           cm=cm.jet,
                           plothead=True,
                           plothead_kwargs=None,
                           ax=P,
                           view='top',
                           **kwargs):
    """Plot connectivity on a head surface, derived from some sensor locations.

        The sensor locations are first projected onto the best fitting sphere and
        finally projected onto a circle (by simply ignoring the z-axis).

        :param connectivity: Connectivity matrix
        :type connectivity: matrix
        :param sensorlocations: array (nsensors x 3), 3D coordinates of each sensor. The order of the sensors has to match with the `connectivity` matrix.
        :param plotsensors: bool; if True, sensor will be plotted on their projected coordinates. No sensors are shown otherwise.
        :param plothead: bool; If True, a head outline is plotted.
        :param plothead_kwargs: Additional keyword arguments passed to `plot_head_outline()`.
        :param vmin,vmax: Minimum and maximum value to be used for graphics.
        :param ax: matplotlib axes to plot to. Standard is pylab.
        :param view: one of 'top' and 'rear'; Defines from where the head is viewed.
        :param kwargs: All additional arguments will be passed to `P.imshow()`.
        :returns: (map, head, sensors)

        The corresponding matplotlib objects are returned if plotted, i.e.,
        if plothead is set to `False`, head will be `None`.

          map
            The colormap that makes the actual plot, a
            matplotlib.image.AxesImage instance.
          head
            What is returned by :py:meth:`plot_head_outline`.
          sensors
            The dots marking the electrodes, a matplotlib.lines.Line2d
            instance.

        ..seealso: :py:meth:`plot_head_topography`
    """
    #Some assertions:
    assert len(connectivity.shape) == 2 and connectivity.shape[
        0] == connectivity.shape[1], "connectivity must be a quadratic matrix"
    assert connectivity.shape[0] == sensorlocations.shape[
        0], "connectivity and sensorlocations must have same length"
    if vmin != None and vmax != None:
        assert vmin < vmax, "vmin(=%f) must be smaller than vmax(=%f)" % (vmin,
                                                                          vmax)
    # give sane defaults
    if plothead_kwargs is None:
        plothead_kwargs = {}

    #assert sensorlocations is an numpy-arrays and swap x and y coordinates
    #swapping is necessary as the eeglab .ced files have another interpretation of this
    sensorlocations = N.array(sensorlocations)
    tmp = sensorlocations[:, 1].copy()
    sensorlocations[:, 1] = sensorlocations[:, 0]
    sensorlocations[:, 0] = tmp[:]
    sensorlocations[:, 0] *= -1
    del tmp

    # error function to fit the sensor locations to a sphere
    def err(params):
        r, cx, cy, cz = params
        #print r,cx,cy,cz
        rv = (sensorlocations[:, 0] -
              cx)**2 + (sensorlocations[:, 1] -
                        cy)**2 + (sensorlocations[:, 2] - cz)**2 - r**2
        rv = abs(rv.sum())
        #print "rv: ",rv
        return rv

    # initial guess of sphere parameters (radius and center)
    params = N.array([1.0, 0.0, 0.0, 0.0])

    # do fit
    r, cx, cy, cz = fmin(err, params, disp=0)  #leastsq(err, params)#
    #print "Results of fit:", r, cx,cy,cz

    # project the sensor locations onto the sphere
    sphere_center = N.array((cx, cy, cz))
    sproj = sensorlocations - sphere_center
    sproj = r * sproj / N.c_[N.sqrt(N.sum(sproj**2, axis=1))]
    sproj += sphere_center
    #print "sproj.shape:",sproj.shape

    #vmin, vmax: give sane defaults
    #first, make copy of connectivity  and set diagonal elements to zero
    conn = connectivity.copy()
    conn *= N.ones((conn.shape[0]), "d") - N.diag(N.ones((conn.shape[0]), "d"))
    if vmin == None:
        vmin = conn.min()
    if vmax == None:
        vmax = conn.max()
    #Now transform values of conn to be between 0 and 1
    conn = (conn - vmin) / (vmax - vmin)
    conn[conn > 1] = N.ones(conn[conn > 1].shape, "d")
    conn[conn < 0] = N.zeros(conn[conn < 0].shape, "d")

    if view == 'top':
        #
        fig = ax.gca()
        for i in range(connectivity.shape[0]):
            for j in range(i):
                dx = sproj[j, 0] - sproj[i, 0]
                dy = sproj[j, 1] - sproj[i, 1]
                if conn[i, j] != conn[j, i]:
                    if conn[i, j] > 0.0:
                        #ax.arrow(sproj[i,0],sproj[i,1],dx,dy,lw=conn[i,j]*5+1,ec=cm(conn[i,j]),head_width=N.sqrt(dx**2+dy**2)*conn[i,j]*0.03,zorder=100-conn[i,j])
                        arr1 = P.Arrow(sproj[i, 0],
                                       sproj[i, 1],
                                       dx,
                                       dy,
                                       width=(conn[i, j] * 5 + 1) / 30,
                                       ec=cm(conn[i, j]),
                                       fc=cm(conn[i, j]),
                                       zorder=100 + conn[i, j])
                        fig.add_patch(arr1)
                    if conn[j, i] > 0.0:
                        #ax.arrow(sproj[i,0],sproj[i,1],dx,dy,lw=conn[j,i]*5+1,ec=cm(conn[j,i]),head_width=N.sqrt(dx**2+dy**2)*conn[j,i]*0.03,zorder=100-conn[j,i])
                        arr1 = P.Arrow(sproj[i, 0],
                                       sproj[i, 1],
                                       dx,
                                       dy,
                                       width=(conn[j, i] * 5 + 1) / 30,
                                       ec=cm(conn[j, i]),
                                       fc=cm(conn[j, i]),
                                       zorder=100 + conn[j, i])
                        fig.add_patch(arr1)
                else:
                    if conn[i, j] > 0.0:
                        ax.arrow(sproj[i, 0],
                                 sproj[i, 1],
                                 sproj[j, 0] - sproj[i, 0],
                                 sproj[j, 1] - sproj[i, 1],
                                 lw=conn[i, j] * 5 + 1,
                                 ec=cm(conn[i, j]),
                                 zorder=100 - conn[i, j])
    #elif view=='rear':
    #    pass
    else:
        raise ValueError("view must be one of 'top' and 'rear'")

    # show surface
    #map = ax.imshow(topo, origin="lower", extent=(-r, r, -r, r), **kwargs)
    ax.axis('off')
    ax.axis('equal')

    if plothead:
        # plot scaled head outline
        head = plot_head_outline(scale=r,
                                 shift=(cx, cy),
                                 view=view,
                                 **plothead_kwargs)
    else:
        head = None

    if plotsensors:
        sensors = plot_sensors(sproj, ax, "wo", view=view)
    else:
        sensors = None

    if view == 'top':
        ax.xlim((cx - (r * 1.2), cx + (r * 1.2)))
        ax.ylim((cy - (r * 1.2), cy + (r * 1.2)))
    elif view == 'rear':
        ax.xlim((cx - (r * 1.2), cx + (r * 1.2)))
        ax.ylim((cz - (r * 0.4), cz + (r * 1.2)))

    return map, head, sensors
Beispiel #13
0
def avg_mauna_kea_weather(measured=None):
    """
    Plot the distribution of Mauna Kea weather valuse
    (humidity, temperature, pressure) during
    observing hours to estimate whether your particular
    observing conditions were average or not. Use data
    from 2008-2009 in May through August.

    Optional Inputs:
    measured - (def=None) A length-3 tuple containing the measured
               temperature, pressure, and humidity. These values
               will be overplotted on the histograms and the probabilities
               will be calculated of encountering these values to
               within the 1% bin width of the histograms.
    """
    years = [2008, 2009]
    months = np.arange(5, 9)  # May through August

    logDir = '/u/ghezgroup/code/python/keckdar/'

    atmTemp = np.array([], dtype=float)
    atmHumidity = np.array([], dtype=float)
    atmPressure = np.array([], dtype=float)

    for year in years:
        for month in months:
            logFile = logDir + 'cfht-wx.' + str(year) + '.' + \
                str(month).zfill(2) + '.dat'

            atm = asciidata.open(logFile)

            hour = atm[3].tonumpy()
            temp = atm[7].tonumpy()
            humidity = atm[8].tonumpy()
            pressure = atm[9].tonumpy()

            # Assume observing hours are 8 pm to 6 am.
            idx = np.where((hour > 20) | (hour < 6))[0]

            atmTemp = np.append(atmTemp, temp[idx])  # Celsius
            atmHumidity = np.append(atmHumidity, humidity[idx])  # percent
            atmPressure = np.append(atmPressure, pressure[idx])  # mbars

    py.close(2)
    py.figure(2, figsize=(16, 6))
    py.clf()
    py.subplots_adjust(left=0.05, right=0.97, wspace=0.25)

    # ----------
    # Temperature Plot
    # ----------
    py.subplot(1, 3, 1)
    (nT, binsT, patchesT) = py.hist(atmTemp,
                                    bins=25,
                                    normed=1,
                                    histtype='step')
    py.xlabel('Temperature (Celsius)')
    py.ylabel('Probability Density')
    py.ylim(0, nT.max() * 1.05)

    if measured != None:
        arr = py.Arrow(measured[0], nT.max() * 1.05, 0, -nT.max() * 0.1)
        py.gca().add_patch(arr)

    # ----------
    # Pressure Plot
    # ----------
    py.subplot(1, 3, 2)
    (nP, binsP, patchesP) = py.hist(atmPressure,
                                    bins=25,
                                    normed=1,
                                    histtype='step')
    py.xlabel('Pressure (milli-bars)')
    py.ylabel('Probability Density')
    py.ylim(0, nP.max() * 1.05)
    py.title('Mauna Kea Weather Conditions in Months %d - %d of %d - %d\n' % \
                 (months[0], months[-1], years[0], years[-1]))

    if measured != None:
        arr = py.Arrow(measured[1], nP.max() * 1.05, 0, -nP.max() * 0.1)
        py.gca().add_patch(arr)

    # ----------
    # Relative Humdity Plot
    # ----------
    py.subplot(1, 3, 3)
    (nH, binsH, patchesH) = py.hist(atmHumidity,
                                    bins=25,
                                    range=[0, 100],
                                    normed=1,
                                    histtype='step')
    py.xlabel('Relative Humidity (%)')
    py.ylabel('Probability Density')
    py.ylim(0, nH.max() * 1.05)

    if measured != None:
        arr = py.Arrow(measured[2],
                       nH.max() * 1.05,
                       0,
                       -nH.max() * 0.1,
                       width=5)
        py.gca().add_patch(arr)

    # Save the figure
    py.savefig('avg_mauna_kea_weather.png')

    # ----------
    # Print out some stats
    # ----------
    if measured != None:
        idx = abs(nT - measured[0]).argmin()
        probTemp = nT[idx] * (binsT[idx + 1] - binsT[idx])

        idx = abs(nP - measured[1]).argmin()
        probPressure = nP[idx] * (binsP[idx + 1] - binsP[idx])

        idx = abs(nH - measured[2]).argmin()
        probHumidity = nH[idx] * (binsH[idx + 1] - binsH[idx])

    print 'Temperature (Celsius)'
    print '   Mean = %.1f +/- %.1f' % (atmTemp.mean(), atmTemp.std())
    print '   Median = %.1f' % (np.median(atmTemp))
    if measured != None:
        print '   Probility of Measured Value = %.2f' % probTemp
    print ''

    print 'Pressure (milli-bars)'
    print '   Mean = %.1f +/- %.1f' % (atmPressure.mean(), atmPressure.std())
    print '   Median = %.1f' % (np.median(atmPressure))
    if measured != None:
        print '   Probility of Measured Value = %.2f' % probPressure
    print ''

    print 'Relative Humidity (%)'
    print '   Mean = %.1f +/- %.1f' % (atmHumidity.mean(), atmHumidity.std())
    print '   Median = %.1f' % (np.median(atmHumidity))
    if measured != None:
        print '   Probility of Measured Value = %.2f' % probHumidity