Пример #1
0
 def place_square(area, x, y, colour=N.array([255, 255, 255])):
     edge_len = int((area**.5) * dpi)
     if edge_len:
         offset = (dpi - edge_len) / 2.
         array = N.ones((edge_len, edge_len, 3))
         array[:, :] = colour
         P.figimage(array, xo=dpi * x + offset, yo=dpi * y + offset)
 def place_square(area, x, y, colour=N.array([255,255,255])):
     edge_len = int((area**.5)*dpi)
     if edge_len:
         offset = (dpi-edge_len)/2.
         array = N.ones((edge_len, edge_len, 3))
         array[:,:] = colour
         P.figimage(array, xo=dpi*x+offset, yo=dpi*y+offset)
Пример #3
0
    def plot_image(self,
                   bstack=False,
                   bsigma=False,
                   minval=None,
                   maxval=None,
                   figsize=9,
                   bsave=False,
                   filename="fig_image.pdf",
                   title='',
                   bfullresolution=False,
                   dpi=80,
                   colorscale='jet',
                   bcolorbar=True,
                   colorbar_label=''):

        arr = self.get_array(bstack=bstack)

        minval, maxval = PlotTools.set_minmax(arr,
                                              minval=minval,
                                              maxval=maxval,
                                              bsigma=bsigma)

        if bfullresolution:

            import matplotlib.cm as cm
            fig = pylab.figure(figsize=(self.columns * 0.01, self.rows * 0.01))
            #pylab.figimage(arr,cmap=cm.jet,vmin=minval,vmax=maxval,origin='upper')
            pylab.figimage(arr,
                           cmap=cm.hot,
                           vmin=minval,
                           vmax=maxval,
                           origin='upper')

        else:

            fig = pylab.figure(1, (4 / 3. * figsize, figsize))
            ax = fig.add_subplot(111)
            image = pylab.imshow(arr, interpolation='nearest')

            norm = matplotlib.colors.Normalize(vmin=minval, vmax=maxval)
            image.set_norm(norm)

            pylab.title(title)

            image.set_cmap(colorscale)  # gray/hot/jet

            if bcolorbar: pylab.colorbar(label=colorbar_label)

        if bsave:
            print("Saving image: %s" % filename)
            if bfullresolution:
                pylab.savefig(filename)
            else:
                pylab.savefig(filename, dpi=dpi)
            pylab.clf()
            pylab.close()
        else:
            pylab.show()
Пример #4
0
def disp_save_image(ser, mask_data, out_filename):
    pixels = read_data(ser)
    
    pixels = np.array(pixels,dtype='uint16')
    
    pixels -= mask_data

    img = pylab.figure()
    pylab.figimage(pixels, cmap = pylab.cm.Greys_r)

    img.set_size_inches(1, 1)

    pylab.savefig(out_filename, dpi=112)
Пример #5
0
def disp_save_images(image_file, mask_data, out_filename):
    images = read_all_packed_images(image_file)

    img = pylab.figure()
    for i, image in enumerate(images):
        image -= mask_data

        pylab.figimage(image, cmap = pylab.cm.Greys_r)

        img.set_size_inches(1, 1)

        if (len(images) == 1):
            pylab.savefig(out_filename + ".png", dpi=112)
        else:
            pylab.savefig(out_filename + str(i) + ".png", dpi=112)
Пример #6
0
def conditional_logo(joint):
    """
    Produces an image summarising the marginal, conditional and joint distributions of 2 bases.
    """
    import pylab as P, numpy as N, hmm.pssm.logo as L

    #dpi = 150
    #fig = P.figure(figsize=(9,10), dpi=dpi, facecolor='white')

    #dpi = 150
    fig = P.figure(figsize=(6, 6), facecolor='white')
    dpi = fig.dpi

    def logo_from_dist(dist):
        return L.dist_as_image(dist / dist.sum(), (dpi, dpi))

    def place_logo(logo, x, y):
        P.figimage(N.asarray(logo, dtype=N.float32) / 255., x * dpi, y * dpi)

    # conditionals: logo
    for x in xrange(4):
        cond = joint[x]
        place_logo(logo_from_dist(cond / cond.sum()), x + 1, 0)
    for y in xrange(4):
        cond = joint[:, y]
        place_logo(logo_from_dist(cond / cond.sum()), 5, 4 - y)

    # marginals: logo
    x_marg = joint.sum(axis=1)
    place_logo(logo_from_dist(x_marg / x_marg.sum()), 2.5, 5)
    y_marg = joint.sum(axis=0)
    place_logo(logo_from_dist(y_marg / y_marg.sum()), 0, 2.5)

    # joint distribution: heat map
    Z = N.ones((dpi, dpi))
    for x in xrange(4):
        for y in xrange(4):
            area = joint[x, y]
            edge_len = int(area * dpi)
            if edge_len:
                offset = (dpi - edge_len) / 2.
                P.figimage(N.ones((edge_len, edge_len)),
                           xo=dpi * (x + 1) + offset,
                           yo=dpi * (4 - y) + offset)

    return fig
Пример #7
0
def generate_mask(data_file, mask_output):
    pixels = read_packed_image(data_file)

    pixels = np.array(pixels,dtype='uint16')

    # pixels[0] = pixels[1]
    
    pixels -= np.amin(pixels)
    
    pickle.dump(pixels, mask_output)

    img = pylab.figure()
    pylab.figimage(pixels, cmap = pylab.cm.Greys_r)

    img.set_size_inches(1, 1)

    pylab.savefig("mask.png", dpi=112)
def conditional_logo(joint):
    """
    Produces an image summarising the marginal, conditional and joint distributions of 2 bases.
    """
    import pylab as P, numpy as N, hmm.pssm.logo as L

    #dpi = 150
    #fig = P.figure(figsize=(9,10), dpi=dpi, facecolor='white')

    #dpi = 150
    fig = P.figure(figsize=(6, 6), facecolor='white')
    dpi = fig.dpi

    def logo_from_dist(dist):
        return L.dist_as_image(dist/dist.sum(), (dpi, dpi))

    def place_logo(logo, x, y):
        P.figimage(N.asarray(logo, dtype=N.float32) / 255., x*dpi, y*dpi)

    # conditionals: logo
    for x in xrange(4):
        cond = joint[x]
        place_logo(logo_from_dist(cond/cond.sum()), x+1, 0)
    for y in xrange(4):
        cond = joint[:,y]
        place_logo(logo_from_dist(cond/cond.sum()), 5, 4-y)

    # marginals: logo
    x_marg = joint.sum(axis=1)
    place_logo(logo_from_dist(x_marg/x_marg.sum()), 2.5, 5)
    y_marg = joint.sum(axis=0)
    place_logo(logo_from_dist(y_marg/y_marg.sum()), 0, 2.5)

    # joint distribution: heat map
    Z = N.ones((dpi, dpi))
    for x in xrange(4):
        for y in xrange(4):
            area = joint[x,y]
            edge_len = int(area * dpi)
            if edge_len:
                offset = (dpi-edge_len)/2.
                P.figimage(N.ones((edge_len, edge_len)), xo=dpi*(x+1)+offset, yo=dpi*(4-y)+offset)

    return fig
Пример #9
0
def generate_mask(ser, mask_file):
    pixels = read_data(ser)
    #f = open('mask_'+str(out_voltage)+'_'+str(out_round)+'.txt', 'w')
    #for i in range(0,112):
#	for j in range(0,112):
#		f.write('%d '%pixels[i][j])
#	f.write('\n')
#    f.close()

    pixels = np.array(pixels,dtype='uint16')
    
    pixels -= np.amin(pixels)
    
    pickle.dump(pixels, mask_file)
    
    img = pylab.figure()
    pylab.figimage(pixels, cmap = pylab.cm.Greys_r)
    
    img.set_size_inches(1, 1)
    
    pylab.savefig("mask_test.png", dpi=112)
Пример #10
0
def icons(users, distance):
    """Visualization using user profile images as the points."""

    # It would be pretty cool to put user thumbails where points are.
    # but i'm still not sure how to do this yet.
    images = []

    try:
        print 'getting images..'
        for p in users:
            print p
            f = p.image
            img = imread('image.tmp')
            images.append(img)
    except Exception as e:
        print 'got an error...'
        import traceback
        etype, evalue, tb = sys.exc_info()
        print yellow % '\n'.join(traceback.format_exception(etype, evalue, tb))
        ip()

    (W, H, _) = shape(img)  # thumbnails should all be the same size
    count = len(images)

    pl.figure()

    P2, _ = mds(distance, 2)
    X, Y = P2[:, 0], P2[:, 1]

    ## XXX: not a great transformation b/c we might stretch more in one dimension
    def N(x):
        "force x to fit in interval [0,1]"
        x = (x - x.min())
        x = x / x.max()
        assert all(x >= 0) and all(x <= 1)
        return x

    X = N(X) * 475
    Y = N(Y) * 425

    figimages = [
        pl.figimage(img, xo=x, yo=y) for img, x, y in zip(images, X, Y)
    ]
Пример #11
0
def icons(users, distance):
    """Visualization using user profile images as the points."""

    # It would be pretty cool to put user thumbails where points are.
    # but i'm still not sure how to do this yet.
    images = []

    try:
        print 'getting images..'
        for p in users:
            print p
            f = p.image
            img = imread('image.tmp')
            images.append(img)
    except Exception as e:
        print 'got an error...'
        import traceback
        etype, evalue, tb = sys.exc_info()
        print yellow % '\n'.join(traceback.format_exception(etype, evalue, tb))
        ip()

    (W, H, _) = shape(img)  # thumbnails should all be the same size
    count = len(images)

    pl.figure()

    P2, _ = mds(distance, 2)
    X,Y = P2[:,0], P2[:,1]

    ## XXX: not a great transformation b/c we might stretch more in one dimension
    def N(x):
        "force x to fit in interval [0,1]"
        x = (x - x.min())
        x = x / x.max()
        assert all(x >= 0) and all(x <= 1)
        return x
    X = N(X)*475
    Y = N(Y)*425

    figimages = [pl.figimage(img, xo=x, yo=y) for img, x, y in zip(images, X, Y)]
Пример #12
0
xs = np.linspace(-1,1,size).astype(np.float32)[None,:]
ys = np.linspace(-1,1,size).astype(np.float32)[:,None]

vectors = np.zeros((size,size,2),dtype=np.float32)
#for (x,y) in vortices:
#    rsq = (xs-x)**2+(ys-y)**2
#    vectors[...,0] +=  (ys-y)/rsq
#    vectors[...,1] += -(xs-x)/rsq

print np.shape(vectors)
asdf()
texture = np.random.rand(size,size).astype(np.float32)

plt.bone()
frame=0

kernellen=100
kernel = np.arange(kernellen) #np.sin(np.arange(kernellen)*np.pi/kernellen)
kernel = kernel.astype(np.float32)

image = lic_internal.line_integral_convolution(vectors, texture, kernel)

plt.clf()
plt.axis('off')
plt.figimage(image)
plt.gcf().set_size_inches((size/float(dpi),size/float(dpi)))
plt.savefig("flow-image.png",dpi=dpi)


Пример #13
0
def skewtlogp(olga, si):
    """ 
    Get directory of script for saving arrays
    """
    tmpPath = os.path.dirname(os.path.realpath(__file__)) + '/tmp/'
    if (not os.path.isdir(tmpPath)):
        os.mkdir(tmpPath)
    """
    Settings for high and low sounding top
    """
    if (si.stype == 0):
        pbottom = 105000.  # highest pressure in diagram (bottom)
        ptop = 20000.  # lowest pressue in diagram (top)
        ptop_thd = 40000  # top of dry adiabats
        ptop_mxr = 60000  # top of mixing ratio lines
        pbottom_thw = pbottom  # bottom of moist adiabats
        dp = 100.  # pressure interval used in some calculations
        Tleft = -35.  # lowest temperature (@pb) in diagram (left)
        Tright = 35.  # highest temperature (@pb) in diagram (right)
        dp_label = 7000

        isotherms = np.arange(-100, 30.001, 10)
        isobars = np.array([
            1050., 1000., 850., 700., 500., 400., 300., 250., 200., 150., 100.,
            50
        ]) * 100.
        dryadiabats = np.arange(-30, 50.001, 10)
        moistadiabats = np.array([28., 24., 20., 16., 12., 8., 4., 0.])
        mixrat = np.array([20., 12., 8., 5., 3., 2., 1.])
    elif (si.stype == 1):
        pbottom = 105000.  # highest pressure in diagram (bottom)
        ptop = 50000.  # lowest pressue in diagram (top)
        ptop_thd = 70000  # top of dry adiabats
        ptop_mxr = 70000  # top of mixing ratio lines
        pbottom_thw = pbottom  # bottom of moist adiabats
        dp = 100.  # pressure interval used in some calculations
        Tleft = -11.  # lowest temperature (@pb) in diagram (left)
        Tright = 35.  # highest temperature (@pb) in diagram (right)
        dp_label = 2500  # spacing (in pressure coords) of some label placement

        isotherms = np.arange(-100, 60.001, 10)
        isobars = np.array([1050., 1000., 900., 850., 700., 600., 500.]) * 100.
        dryadiabats = np.arange(-10, 30.001, 5)
        moistadiabats = np.array([28., 24., 20., 16., 12., 8., 4., 0.])
        mixrat = np.array([20., 12., 8., 5., 3., 2., 1.])
    else:
        sys.exit('stype=%i not supported!' % stype)
    """
    Setup figure
    """
    if (olga != -1):
        fig = pl.figure(figsize=(olga.fig_width_px / float(olga.fig_dpi),
                                 olga.fig_width_px / float(olga.fig_dpi)))
    else:
        fig = pl.figure(figsize=(8, 8))

    #                   L    B    R    T    ws  hs
    fig.subplots_adjust(0.08, 0.10, 1.0, 0.93, 0.2, 0.08)
    pl.subplot(111)

    # Calculate bounds in figure coordinates
    y00 = skewty(pbottom)
    y11 = skewty(ptop)
    x00 = skewtx(Tleft, y00)
    x11 = skewtx(Tright, y00)

    # Spacing for some labels
    hs = np.abs(x11 - x00) / 200.
    vs = np.abs(y11 - y00) / 200.
    """
    1. Create isotherms
    """
    for T in isotherms:
        y = np.array([skewty(pbottom), skewty(ptop)])
        x = np.array([skewtx(T, y[0]), skewtx(T, y[1])])

        # Check if partially out of bounds
        lloc = 0
        if (x[0] < x00):
            x[0] = x00
            y[0] = iskewtxT(x00, T)
        if (x[1] > x11):
            x[1] = x11
            y[1] = iskewtxT(x11, T)

        if (x[1] >= x00 and y[1] >= y00):
            pl.plot(x, y, color=c2, alpha=a1)
            if (x[0] > x00 and x[0] < x11):
                pl.text(x[0],
                        y[0] - 2 * hs,
                        int(T),
                        ha='center',
                        va='top',
                        color=c2)
            else:
                pl.text(x[1] - 5 * hs,
                        y[1] - 5 * vs,
                        int(T),
                        ha='center',
                        va='center',
                        color=c2,
                        alpha=a2)
    """
    2. Create isobars
    """
    for p in isobars:
        # Check if out of bounds
        if ((p >= ptop) and (p <= pbottom)):
            y = skewty(p)
            pl.plot([x00, x11], [y, y], color=c2, alpha=a1)
            pl.text(x00 - hs,
                    y,
                    int(p / 100.),
                    ha='right',
                    va='center',
                    color=c2)
    """
    3. Create dry adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath + 'theta_p_%i.arr' % si.stype)
        y = np.load(tmpPath + 'theta_y_%i.arr' % si.stype)
        x = np.load(tmpPath + 'theta_x_%i.arr' % si.stype)
    except:
        p = np.arange(pbottom, (np.max(([ptop, ptop_thd])) - dp), -dp)
        x = np.zeros((dryadiabats.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(dryadiabats.size):
            x[i, :] = 0.
            for k in range(p.size):
                xtmp = skewtx(((dryadiabats[i] + T0) * exner(p[k])) - T0, y[k])
                if (xtmp >= x00 and xtmp <= x11):
                    x[i, k] = xtmp
                else:
                    x[i, k] = -9999

        p.dump(tmpPath + 'theta_p_%i.arr' % si.stype)
        y.dump(tmpPath + 'theta_y_%i.arr' % si.stype)
        x.dump(tmpPath + 'theta_x_%i.arr' % si.stype)

    # Plot the dry adiabats
    for i in range(dryadiabats.size):
        doPlot = np.where(x[i, :] != -9999)[0]
        if (doPlot[0].size > 0):
            lloc = max(0, np.size(x[i, doPlot]) - int(5000. / dp))
            pl.plot(x[i, doPlot], y[doPlot], color=c1)
            pl.text(x[i, doPlot][lloc],
                    y[doPlot][lloc],
                    int(dryadiabats[i]),
                    color=c1,
                    ha='center',
                    va='center',
                    backgroundcolor='w')
    """ 
    4. Create moist adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath + 'thetam_p_%i.arr' % si.stype)
        y = np.load(tmpPath + 'thetam_y_%i.arr' % si.stype)
        x = np.load(tmpPath + 'thetam_x_%i.arr' % si.stype)
    except:
        p = np.arange(np.min(([pbottom, pbottom_thw])), ptop - dp, -dp)
        x = np.zeros((moistadiabats.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(moistadiabats.size):
            for k in range(p.size):
                thw = dsatlftskewt(moistadiabats[i], p[k])
                xtmp = skewtx(thw, y[k])
                if (xtmp >= x00 and xtmp <= x11):
                    x[i, k] = xtmp
                else:
                    x[i, k] = -9999

        p.dump(tmpPath + 'thetam_p_%i.arr' % si.stype)
        y.dump(tmpPath + 'thetam_y_%i.arr' % si.stype)
        x.dump(tmpPath + 'thetam_x_%i.arr' % si.stype)

    # Plot the moist adiabats
    for i in range(moistadiabats.size):
        doPlot = np.where(x[i, :] != -9999)[0]
        if (doPlot[0].size > 0):
            lloc = max(0, np.size(x[i, doPlot]) - int(8000. / dp))
            pl.plot(x[i, doPlot], y[doPlot], '--', color=c3)
            pl.text(x[i, doPlot][lloc],
                    y[doPlot][lloc],
                    int(moistadiabats[i]),
                    color=c3,
                    ha='center',
                    va='center',
                    backgroundcolor='w')
    """ 
    5. Create isohumes / mixing ratio lines
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath + 'mixr_p_%i.arr' % si.stype)
        y = np.load(tmpPath + 'mixr_y_%i.arr' % si.stype)
        x = np.load(tmpPath + 'mixr_x_%i.arr' % si.stype)
    except:
        p = np.arange(pbottom, (np.max(([ptop, ptop_mxr])) - dp), -dp)
        x = np.zeros((mixrat.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(mixrat.size):
            for k in range(p.size):
                mix = Td(mixrat[i] / 1000., p[k]) - T0
                xtmp = skewtx(mix, y[k])
                if (xtmp >= x00 and xtmp <= x11):
                    x[i, k] = xtmp
                else:
                    x[i, k] = -9999

        p.dump(tmpPath + 'mixr_p_%i.arr' % si.stype)
        y.dump(tmpPath + 'mixr_y_%i.arr' % si.stype)
        x.dump(tmpPath + 'mixr_x_%i.arr' % si.stype)

    # Plot the mixing ratio lines
    for i in range(mixrat.size):
        doPlot = np.where(x[i, :] != -9999)[0]
        if (doPlot[0].size > 0):
            pl.plot(x[i, doPlot], y[doPlot], color=c5, dashes=[3, 2])
            pl.text(x[i, doPlot][-1],
                    y[doPlot][-1] + vs,
                    int(mixrat[i]),
                    color=c5,
                    ha='center',
                    va='bottom',
                    backgroundcolor='w')
    """
    6. Add sounding data
    """
    # 6.1 Temperature and dewpoint temperature
    if (si.T.size > 0):
        y = skewty(si.p)
        x1 = skewtx(si.T - T0, y)
        x2 = skewtx(si.Td - T0, y)

        pl.plot(x1, y, '-', color=cT, linewidth=2)
        pl.plot(x2, y, '-', color=cTd, linewidth=2)

    # 6.2 Add height labels to axis
    if (si.z.size > 0 and si.z.size == si.p.size):
        y = skewty(si.p)
        p_last = 1e9
        for k in range(si.z.size):
            if (y[k] <= y11 and np.abs(si.p[k] - p_last) > dp_label):
                pl.text(x11 + hs,
                        y[k],
                        str(int(si.z[k])) + 'm',
                        color=c2,
                        ha='right',
                        va='center',
                        size=7,
                        backgroundcolor='w')
                p_last = si.p[k]

    # 6.2 Wind barbs
    if (si.u.size > 0):
        y = skewty(si.p)
        u = si.u * 1.95
        v = si.v * 1.95
        xb = x11 + 9 * hs

        p_last = 1e9
        for k in range(si.z.size):
            if (y[k] <= y11 and np.abs(si.p[k] - p_last) > dp_label):
                pl.barbs(xb,
                         y[k],
                         u[k],
                         v[k],
                         length=5.2,
                         linewidth=0.5,
                         pivot='middle')
                p_last = si.p[k]
    """
    6.1 :) Try to add measured data
    """
    # 6.1 Temperature and dewpoint temperature
    if (si.Tm.size > 0):
        y = skewty(si.pm)
        x1 = skewtx(si.Tm, y)
        x2 = skewtx(si.Tdm, y)

        pl.plot(x1, y, '--', color=cT, linewidth=1)
        pl.plot(x2, y, '--', color=cTd, linewidth=1)
    """
    7. Lauch parcel
    """
    if (si.parcel == True):
        # Plot starting position:
        p0s = skewty(si.ps)
        T0s = skewtx(si.Ts - T0, p0s)
        Td0s = skewtx(Td(si.rs, si.ps) - T0, p0s)
        pl.scatter(T0s, p0s, facecolor='none')
        pl.scatter(Td0s, p0s, facecolor='none')

        # Lists to hold parcel pressure, temp and dewpoint temp during ascent
        pp = [si.ps]
        Tp = [si.Ts]
        Tdp = [Td(si.rs, si.ps)]

        # Launch parcel
        n = 0
        while (Tp[-1] > Tdp[-1] and n < 1000):
            n += 1
            dp2 = max(1, (Tp[-1] - Tdp[-1]) * 300)  # bit weird, but fast
            pp.append(pp[-1] - dp2)
            Tp.append(si.Ts * exner(pp[-1], si.ps))
            Tdp.append(Td(si.rs, pp[-1]))

        # Plot lines from surface --> LCL
        ps = skewty(np.array(pp))
        Tps = skewtx(np.array(Tp) - T0, ps)
        Tdps = skewtx(np.array(Tdp) - T0, ps)
        pl.plot(Tps, ps, 'k', linewidth=1.5, dashes=[4, 2])
        pl.plot(Tdps, ps, 'k', linewidth=1.5, dashes=[4, 2])
        pl.scatter(Tps[-1], ps[-1], facecolor='none')

        # Iteratively find the moist adiabat starting at p0, which goes through the temperature at LCL
        Ths = si.Ts / exner(si.ps, p0)  # potential temperature surface (@p0)
        ThwsLCL = dsatlftskewt(
            Ths - T0, pp[-1]) + T0  # Temp moist adiabat at plcl, through Ths
        thw0 = Ths - (ThwsLCL - Tp[-1]
                      )  # First estimate of moist adiabat passing through Tlcl

        ThwLCL = dsatlftskewt(thw0 - T0, pp[-1]) + T0
        while (np.abs(ThwLCL - Tp[-1]) > 0.1):
            thw0 -= ThwLCL - Tp[-1]
            ThwLCL = dsatlftskewt(thw0 - T0, pp[-1]) + T0

        # Plot moist adiabat from LCL upwards
        p = np.arange(pp[-1], ptop, -dp)
        x = np.zeros(p.size)
        y = np.zeros(p.size)
        for k in range(p.size):
            thw = dsatlftskewt(thw0 - T0, p[k])
            y[k] = skewty(p[k])
            x[k] = skewtx(thw, y[k])

        pl.plot(x, y, 'k', linewidth=1.5, dashes=[4, 2])
    """
    Add info from TEMF boundary layer scheme
    """
    if (si.Tu.size > 0):
        # Cloud fraction
        dw = (x11 - x00)  # width of diagram
        y = skewty(si.p)
        x = x00 + si.cfru * 0.2 * (x11 - x00)
        pl.plot(x, y, '-', linewidth=1.5, color=c6)  # cloud cover

        cfr_pos = np.where(si.cfru > 0.001)[0]
        if (np.size(cfr_pos) > 1):
            pl.text(x00,
                    y[cfr_pos[0] - 1],
                    '- %im' % (si.z[cfr_pos[0] - 1]),
                    ha='left',
                    va='center',
                    size=8,
                    color=c6)
            pl.text(x00,
                    y[cfr_pos[-1]],
                    '- %im' % (si.z[cfr_pos[-1]]),
                    ha='left',
                    va='center',
                    size=8,
                    color=c6)
            kmax = np.where(si.cfru == si.cfru.max())[0][0]
            pl.text(x.max(),
                    y[kmax],
                    '- %i%%' % (si.cfru[kmax] * 100.),
                    ha='left',
                    va='center',
                    size=8,
                    color=c6)
    """
    6. Finish diagram
    """
    pl.xticks([])
    pl.yticks([])
    pl.box('off')
    pl.xlim(x00 - 0.1, x11 + 16 * hs)
    pl.ylim(y00 - 0.1, y11 + 0.1)

    # draw axis
    pl.plot([x00, x11], [y00, y00], 'k-')
    pl.plot([x00, x00], [y00, y11], 'k-')

    pl.figtext(0.5, 0.05, 'Temperature (C)', ha='center')
    pl.figtext(0.015, 0.52, 'Pressure (hPa)', rotation=90)
    label = 'Skew-T log-P, %s, %s UTC' % (si.name, si.time)
    pl.figtext(0.5, 0.97, label, ha='center')

    if (olga != -1):
        img = image.imread(olga.olgaRoot + 'include/olga_left.png')
        pl.figimage(img, 7, 5)
        #pl.figimage(img,10,olga.fig_width_px-45)
        pl.figtext(0.99, 0.011, '%s' % olga.map_desc[0], size=7, ha='right')

    return fig
Пример #14
0
 def place_image(logo, x, y):
     P.figimage(N.asarray(logo, dtype=N.float32) / 255., x * dpi, y * dpi)
Пример #15
0
def createFigure(olga, dom, wrf, basem, var, t, figwi, fighi, dpi, axl, axb,
                 axw, axh):
    # This is ugly :( TODO: fix
    if (var == 'pfd' or var == 'pfd2'):
        nFig = np.size(olga.pfdNames)
    else:
        nFig = 1

    for n in range(nFig):
        fig = pl.figure(figsize=(figwi, fighi), dpi=dpi)
        m = deepcopy(basem)
        axloc = [axl, axb, axw, axh]
        ax = fig.add_axes(axloc)
        lon, lat = m(wrf.lon, wrf.lat)
        minlon = lon.min()
        maxlon = lon.max()
        minlat = lat.min()
        maxlat = lat.max()
        doplot = False

        # Default color line country boundaries
        countryLines = '0.3'

        # -------------------------------------------------
        # stream lines of wind
        # -------------------------------------------------
        if (var[:4] == 'wind'):
            doplot = True
            units = 'kts'
            fsigma = 0.5

            if (var == 'wind10m'):
                title = '10m wind (kts)'
                ufilt = gaussianFilter(wrf.U10[t, :, :],
                                       fsigma,
                                       mode='reflect')
                vfilt = gaussianFilter(wrf.V10[t, :, :],
                                       fsigma,
                                       mode='reflect')
                sf = 25.
            elif (var == 'wind1000m'):
                title = '1000m wind'
                ufilt = gaussianFilter(wrf.U1000[t, :, :],
                                       fsigma,
                                       mode='reflect')
                vfilt = gaussianFilter(wrf.V1000[t, :, :],
                                       fsigma,
                                       mode='reflect')
                sf = 35.

            umax = 40.
            levs = np.arange(0, umax + 0.01, 1.)
            utot = ((ufilt[:, :] * m2k)**2. + (vfilt[:, :] * m2k)**2.)**0.5
            cf = m.contourf(lon, lat, utot, levs, extend='both', cmap=wnd)
            stream = m.streamplot(lon[0, :],
                                  lat[:, 0],
                                  ufilt[:, :],
                                  vfilt[:, :],
                                  density=3,
                                  linewidth=utot / sf,
                                  color='k')

        # -------------------------------------------------
        # rain
        # -------------------------------------------------
        elif (var == 'rain'):
            doplot = True
            title = 'Precip. between t=%02i-%02i UTC (mm, //=convective)' % (
                wrf.hour[t - 1], wrf.hour[t])
            units = 'mm'
            fSigma = 0.25

            # At first output time instantaneous precipitation field is given
            # At consecutive steps, precipitation is accumulated. Calculate difference
            # between output time steps, so plotted field is precipitation over last period!
            if (t == 0):
                rr = wrf.rr_mp[t, :, :] + wrf.rr_con[t, :, :]
                rrc = wrf.rr_con[t, :, :]
            else:
                rr = wrf.rr_mp[t, :, :] + wrf.rr_con[t, :, :] - wrf.rr_mp[
                    t - 1, :, :] - wrf.rr_con[t - 1, :, :]
                rrc = wrf.rr_con[t, :, :] - wrf.rr_con[t - 1, :, :]

            if (smoothPlot):
                rr = gaussianFilter(rr, fSigma, mode='reflect')
                rrc = gaussianFilter(rrc, fSigma, mode='reflect')

            # Draw shaded contours for precipitation intensity
            levs = [
                0, 0.1, 0.2, 0.4, 0.8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14
            ]
            cf = m.contourf(lon,
                            lat,
                            rr,
                            levs,
                            alpha=1.,
                            extend='both',
                            cmap=rain3nl)

            # Hatch area where precipitation is convective
            levs = [0.1, 100]
            cf2 = m.contourf(lon,
                             lat,
                             rrc,
                             levs,
                             colors='none',
                             hatches=['//'])

        # -------------------------------------------------
        # Cloud cover
        # -------------------------------------------------
        elif (var == 'clouds'):
            doplot = True
            title = 'Cloud fraction (- low  / mid  . high)'
            units = 'fraction'
            fSigma = 0.25

            cclow = gaussianFilter(
                wrf.cclow[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.cclow[t, :, :]
            ccmid = gaussianFilter(
                wrf.ccmid[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.ccmid[t, :, :]
            cchig = gaussianFilter(
                wrf.cchig[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.cchig[t, :, :]
            ccsum = gaussianFilter(
                wrf.ccsum[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.ccsum[t, :, :]

            # Draw shaded contours for cloud cover
            levs = np.arange(0.00, 1.001, 0.1)
            levs[0] = 0.02
            cf = m.contourf(lon, lat, ccsum, levs, alpha=1., cmap=cm.GnBu)

            # Hatch areas of low/mid/high clouds
            levs = [0.05, 100]
            cf2 = m.contourf(lon,
                             lat,
                             cclow,
                             levs,
                             colors='none',
                             hatches=['-'])
            cf2 = m.contourf(lon,
                             lat,
                             ccmid,
                             levs,
                             colors='none',
                             hatches=['/'])
            cf2 = m.contourf(lon,
                             lat,
                             cchig,
                             levs,
                             colors='none',
                             hatches=['.'])

        # -------------------------------------------------
        # Fraction of potential incoming shortwave radiation at surface
        # -------------------------------------------------
        elif (var == 'swd'):
            doplot = True
            title = 'Incoming solar radiation (// = night)'
            units = 'percentage'
            fSigma = 0.25

            data = gaussianFilter(
                wrf.swdf[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.swdf[t, :, :]

            # Draw shaded contours for cloud cover
            levs = np.arange(0.00, 100.01, 5)
            cf = m.contourf(lon,
                            lat,
                            data * 100.,
                            levs,
                            extend='both',
                            alpha=1.,
                            cmap=cloud)

            # Hatch night area
            levs = [-2, -0.5]
            cf2 = m.contourf(lon,
                             lat,
                             data,
                             levs,
                             colors='none',
                             hatches=['/'])

        # -------------------------------------------------
        # Updraft velocity wstar
        # -------------------------------------------------
        elif (var == 'wglider'):
            doplot = True
            title = 'Updraft velocity w* - %.1f m/s' % olga.sinkGlider
            units = 'm/s'
            fSigma = 0.5

            levs = np.arange(0, 3.001, 0.5)
            data = gaussianFilter(
                wrf.wglider[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.wglider[t, :, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Updraft velocity TEMF
        # -------------------------------------------------
        elif (var == 'wgliderTEMF'):
            doplot = True
            title = 'Updraft velocity TEMF - %.1f m/s' % olga.sinkGlider
            units = 'm/s'
            fSigma = 0.5

            levs = np.arange(0, 3.001, 0.5)
            data = gaussianFilter(
                wrf.wglider2[t, :, :], fSigma,
                mode='reflect') if smoothPlot else wrf.wglider2[t, :, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Top of updraft (dry convection)
        # -------------------------------------------------
        elif (var == 'zidry'):
            doplot = True
            units = 'm AMSL'
            title = 'Updraft height [m AMSL]'
            fSigma = 0.5

            levs = np.arange(0, 2500.01, 300.)
            data = gaussianFilter(
                wrf.zi[t, :, :] + wrf.hgt[:, :], fSigma, mode='reflect'
            ) if smoothPlot else wrf.zi[t, :, :] + wrf.hgt[:, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Top of updraft (minus glider sink)
        # -------------------------------------------------
        elif (var == 'ziglider'):
            doplot = True
            units = 'm AMSL'
            title = 'Updraft height with %.1f m/s sink [m AMSL]' % olga.sinkGlider
            fSigma = 0.5

            levs = np.arange(0, 2500.01, 300.)
            data = gaussianFilter(
                wrf.zi2[t, :, :] + wrf.hgt[:, :], fSigma, mode='reflect'
            ) if smoothPlot else wrf.zi2[t, :, :] + wrf.hgt[:, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Cumulus depth
        # -------------------------------------------------
        elif (var == 'cudepth'):
            doplot = True
            title = 'Cumulus depth [m]'
            units = 'm'
            fSigma = 0.5

            levs = np.arange(0, 4000, 400)
            data = gaussianFilter(
                wrf.zct[t, :, :] - wrf.zi[t, :, :], fSigma, mode='reflect'
            ) if filter else wrf.zct[t, :, :] - wrf.zi[t, :, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wupnl)

        # -------------------------------------------------
        # Potential flight distance per day
        # -------------------------------------------------
        elif ((var == 'pfd') and t < np.size(wrf.date_PFD)):
            doplot = True
            title = 'PFD (w*) %s [km]' % olga.pfdNotes[n]
            units = 'km'
            fSigma = 0.5

            levs = np.arange(0, 800.1, 100)
            data = gaussianFilter(
                wrf.PFD1[t, n, :, :], fSigma,
                mode='reflect') if filter else wrf.PFD1[t, n, :, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Potential flight distance per day: TEMF corrected updraft velocity / height
        # -------------------------------------------------
        elif ((var == 'pfd2') and t < np.size(wrf.date_PFD)):
            doplot = True
            title = 'PFD (TEMF) %s [km]' % olga.pfdNotes[n]
            units = 'km'
            fSigma = 0.5

            levs = np.arange(0, 800.1, 100)
            data = gaussianFilter(
                wrf.PFD2[t, n, :, :], fSigma,
                mode='reflect') if filter else wrf.PFD2[t, n, :, :]
            cf = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Finish plot!
        # -------------------------------------------------
        if (doplot):
            # Plot terrain height contours
            if (False):
                levs = arange(50, 4000.01, 50.)
                contour(lon, lat, wrf.hgt, levs, cmap=cm.PuBu, alpha=0.5)

            # Plot cities
            if (olga.drawCities[dom]):
                for i in range(len(olga.cityLonM)):
                    m.scatter(olga.cityLonM[i],
                              olga.cityLatM[i],
                              s=4,
                              alpha=1.0)
                    pl.text(olga.cityLonM[i],
                            olga.cityLatM[i],
                            ' ' + olga.cityLoc[dom].shortName[i],
                            size=8,
                            ha='left',
                            va='center',
                            color='0.1')

            # Plot airspace
            if (False):
                plotairspace(m)

            # If filled contour, add colorbar
            if (cf != False):
                cax = pl.axes(
                    [axl + axw + 0.02, axb + 0.1 * axh, 0.02, 0.8 * axh])
                cb = pl.colorbar(cf, drawedges=True, cax=cax)
                cb.ax.tick_params(labelsize=8)
                cb.ax.yaxis.set_tick_params(width=0)
                #                cb.outline.set_color('white')
                cb.set_label(units)
            pl.axes(ax)

            # Draw coast and country outlines
            m.drawcoastlines(linewidth=1.5, color=countryLines)
            m.drawcountries(linewidth=1.5, color=countryLines)

            # Draw rivers
            if (olga.drawRivers[dom]):
                m.drawrivers(linewidth=0.5, color='#0066FF')

            # Add description variables, units, OLGA label, logo, etc.
            pl.figtext(axl,
                       axb / 2,
                       '%s' % olga.map_desc[dom],
                       size=7,
                       ha='left',
                       va='center')

            if (var == 'pfd'):
                subtitle = 'cumulative distance over: %s' % str(
                    wrf.date_PFD[t])
            else:
                subtitle = 'valid: %s UTC' % str(wrf.datetime[t])

            # Add figure info (variable, units, time)
            ax.set_title(title, loc='left', size=8)
            ax.set_title(subtitle, loc='right', size=8)

            # Add OLGA logo
            pl.figimage(olga.olga_logo, olga.fig_width_px - 121, 4)

            # Get name and save figure
            if (var == 'pfd' or var == 'pfd2'):
                tmp = '%06i' % (olga.islice * 24 * 100)
            else:
                xtime = wrf.time[t] / 3600.
                hour = int(np.floor(xtime))
                minute = int((xtime - hour) * 60.)
                tmp = str(hour).zfill(4) + str(minute).zfill(2)

            if (var == 'pfd' or var == 'pfd2'):
                name = '%s%04i%02i%02i_t%02iz/%s_%s_%02i_%s.png' % (
                    olga.figRoot, olga.year, olga.month, olga.day, olga.cycle,
                    var, olga.pfdNames[n], dom + 1, tmp)
            else:
                name = '%s%04i%02i%02i_t%02iz/%s_%02i_%s.png' % (
                    olga.figRoot, olga.year, olga.month, olga.day, olga.cycle,
                    var, dom + 1, tmp)

            pl.savefig(name, dpi=olga.fig_dpi)

        # Cleanup!
        fig.clf()
        pl.close()
        gc.collect()
Пример #16
0
def createFigure(olga, dom, wrf, basem, var, t, figwi, fighi, dpi, axl, axb, axw, axh):
    # This is ugly :( TODO: fix
    if(var == 'pfd' or var == 'pfd2'):
        nFig = np.size(olga.pfdNames)
    else:
        nFig = 1

    for n in range(nFig):
        fig        = pl.figure(figsize=(figwi, fighi), dpi=dpi)
        m          = deepcopy(basem)
        axloc      = [axl, axb, axw, axh]
        ax         = fig.add_axes(axloc)
        lon,lat    = m(wrf.lon, wrf.lat)
        minlon     = lon.min()
        maxlon     = lon.max()
        minlat     = lat.min()
        maxlat     = lat.max()
        doplot     = False

        # Default color line country boundaries
        countryLines = '0.3'

        # -------------------------------------------------
        # stream lines of wind
        # -------------------------------------------------
        if(var[:4] == 'wind'):
            doplot = True 
            units  = 'kts'
            fsigma = 0.5

            if(var=='wind10m'):
                title = '10m wind (kts)'
                ufilt = gaussianFilter(wrf.U10[t,:,:], fsigma, mode='reflect')
                vfilt = gaussianFilter(wrf.V10[t,:,:], fsigma, mode='reflect')
                sf    = 25.
            elif(var=='wind1000m'):
                title = '1000m wind'
                ufilt = gaussianFilter(wrf.U1000[t,:,:], fsigma, mode='reflect')
                vfilt = gaussianFilter(wrf.V1000[t,:,:], fsigma, mode='reflect')
                sf    = 35.

            umax   = 40. 
            levs   = np.arange(0, umax+0.01, 1.)
            utot   = ((ufilt[:,:]*m2k)**2. + (vfilt[:,:]*m2k)**2.)**0.5
            cf     = m.contourf(lon, lat, utot, levs, extend='both', cmap=wnd)
            stream = m.streamplot(lon[0,:], lat[:,0], ufilt[:,:], vfilt[:,:], density=3, linewidth=utot/sf, color='k')
 
        # -------------------------------------------------
        # rain
        # -------------------------------------------------
        elif(var == 'rain'):
            doplot = True
            title  = 'Precip. between t=%02i-%02i UTC (mm, //=convective)'%(wrf.hour[t-1],wrf.hour[t])
            units  = 'mm'
            fSigma = 0.25

            # At first output time instantaneous precipitation field is given
            # At consecutive steps, precipitation is accumulated. Calculate difference
            # between output time steps, so plotted field is precipitation over last period!
            if(t==0):
                rr  = wrf.rr_mp[t,:,:] + wrf.rr_con[t,:,:]
                rrc = wrf.rr_con[t,:,:]
            else:
                rr  = wrf.rr_mp[t,:,:] + wrf.rr_con[t,:,:] - wrf.rr_mp[t-1,:,:] - wrf.rr_con[t-1,:,:]  
                rrc = wrf.rr_con[t,:,:] - wrf.rr_con[t-1,:,:] 

            if(smoothPlot):
                rr  = gaussianFilter(rr,  fSigma, mode='reflect') 
                rrc = gaussianFilter(rrc, fSigma, mode='reflect') 

            # Draw shaded contours for precipitation intensity
            levs   = [0,0.1,0.2,0.4,0.8,1,2,3,4,5,6,7,8,9,10,12,14]
            cf     = m.contourf(lon, lat, rr, levs, alpha=1., extend='both', cmap=rain3nl)

            # Hatch area where precipitation is convective
            levs   = [0.1,100] 
            cf2    = m.contourf(lon, lat, rrc, levs, colors='none', hatches=['//']) 

        # -------------------------------------------------
        # Cloud cover
        # -------------------------------------------------
        elif(var == 'clouds'):
            doplot = True
            title  = 'Cloud fraction (- low  / mid  . high)'
            units  = 'fraction'
            fSigma = 0.25

            cclow  = gaussianFilter(wrf.cclow[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.cclow[t,:,:]
            ccmid  = gaussianFilter(wrf.ccmid[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.ccmid[t,:,:]
            cchig  = gaussianFilter(wrf.cchig[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.cchig[t,:,:]
            ccsum  = gaussianFilter(wrf.ccsum[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.ccsum[t,:,:]

            # Draw shaded contours for cloud cover
            levs   = np.arange(0.00, 1.001, 0.1)
            levs[0] = 0.02
            cf     = m.contourf(lon, lat, ccsum, levs, alpha=1., cmap=cm.GnBu)

            # Hatch areas of low/mid/high clouds
            levs   = [0.05,100] 
            cf2    = m.contourf(lon, lat, cclow, levs, colors='none', hatches=['-']) 
            cf2    = m.contourf(lon, lat, ccmid, levs, colors='none', hatches=['/']) 
            cf2    = m.contourf(lon, lat, cchig, levs, colors='none', hatches=['.']) 

        # -------------------------------------------------
        # Fraction of potential incoming shortwave radiation at surface
        # -------------------------------------------------
        elif(var == 'swd'):
            doplot = True
            title  = 'Incoming solar radiation (// = night)'
            units  = 'percentage'
            fSigma = 0.25

            data  = gaussianFilter(wrf.swdf[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.swdf[t,:,:]

            # Draw shaded contours for cloud cover
            levs   = np.arange(0.00, 100.01, 5)
            cf     = m.contourf(lon, lat, data*100., levs, extend='both', alpha=1., cmap=cloud)

            # Hatch night area
            levs   = [-2,-0.5] 
            cf2    = m.contourf(lon, lat, data, levs, colors='none', hatches=['/']) 

        # -------------------------------------------------
        # Updraft velocity wstar
        # -------------------------------------------------
        elif(var == 'wglider'):
            doplot = True 
            title  = 'Updraft velocity w* - %.1f m/s'%olga.sinkGlider
            units  = 'm/s'
            fSigma = 0.5

            levs   = np.arange(0, 3.001, 0.5)
            data   = gaussianFilter(wrf.wglider[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.wglider[t,:,:]
            cf     = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Updraft velocity TEMF
        # -------------------------------------------------
        elif(var == 'wgliderTEMF'):
            doplot = True 
            title  = 'Updraft velocity TEMF - %.1f m/s'%olga.sinkGlider
            units  = 'm/s'
            fSigma = 0.5

            levs   = np.arange(0, 3.001, 0.5)
            data   = gaussianFilter(wrf.wglider2[t,:,:], fSigma, mode='reflect') if smoothPlot else wrf.wglider2[t,:,:]
            cf     = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Top of updraft (dry convection)
        # -------------------------------------------------
        elif(var == 'zidry'):
            doplot = True 
            units  = 'm AMSL'
            title  = 'Updraft height [m AMSL]'
            fSigma = 0.5

            levs   = np.arange(0, 2500.01, 300.)
            data   = gaussianFilter(wrf.zi[t,:,:] + wrf.hgt[:,:], fSigma, mode='reflect') if smoothPlot else wrf.zi[t,:,:] + wrf.hgt[:,:]
            cf     = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)
       
        # -------------------------------------------------
        # Top of updraft (minus glider sink)
        # -------------------------------------------------
        elif(var == 'ziglider'):
            doplot = True 
            units  = 'm AMSL'
            title  = 'Updraft height with %.1f m/s sink [m AMSL]'%olga.sinkGlider
            fSigma = 0.5

            levs   = np.arange(0, 2500.01, 300.)
            data   = gaussianFilter(wrf.zi2[t,:,:] + wrf.hgt[:,:], fSigma, mode='reflect') if smoothPlot else wrf.zi2[t,:,:] + wrf.hgt[:,:]
            cf     = m.contourf(lon, lat, data, levs, extend='both', cmap=wup)
 
        # -------------------------------------------------
        # Cumulus depth
        # -------------------------------------------------
        elif(var == 'cudepth'):
            doplot = True 
            title  = 'Cumulus depth [m]'
            units  = 'm'
            fSigma = 0.5

            levs   = np.arange(0, 4000, 400)
            data   = gaussianFilter(wrf.zct[t,:,:] - wrf.zi[t,:,:], fSigma, mode='reflect') if filter else wrf.zct[t,:,:] - wrf.zi[t,:,:]
            cf     =  m.contourf(lon, lat, data, levs, extend='both', cmap=wupnl)

        # -------------------------------------------------
        # Potential flight distance per day
        # -------------------------------------------------
        elif((var == 'pfd') and t < np.size(wrf.date_PFD)):
            doplot = True 
            title  = 'PFD (w*) %s [km]'%olga.pfdNotes[n]
            units  = 'km'
            fSigma = 0.5

            levs   = np.arange(0, 800.1, 100)
            data   = gaussianFilter(wrf.PFD1[t,n,:,:], fSigma, mode='reflect') if filter else wrf.PFD1[t,n,:,:]
            cf     =  m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Potential flight distance per day: TEMF corrected updraft velocity / height
        # -------------------------------------------------
        elif((var == 'pfd2') and t < np.size(wrf.date_PFD)):
            doplot = True 
            title  = 'PFD (TEMF) %s [km]'%olga.pfdNotes[n]
            units  = 'km'
            fSigma = 0.5

            levs   = np.arange(0, 800.1, 100)
            data   = gaussianFilter(wrf.PFD2[t,n,:,:], fSigma, mode='reflect') if filter else wrf.PFD2[t,n,:,:]
            cf     =  m.contourf(lon, lat, data, levs, extend='both', cmap=wup)

        # -------------------------------------------------
        # Finish plot!
        # -------------------------------------------------
        if(doplot):
            # Plot terrain height contours
            if(False):
                levs = arange(50, 4000.01, 50.)
                contour(lon, lat, wrf.hgt, levs, cmap=cm.PuBu, alpha=0.5)

            # Plot cities
            if(olga.drawCities[dom]):
                for i in range(len(olga.cityLonM)):
                    m.scatter(olga.cityLonM[i], olga.cityLatM[i], s=4, alpha=1.0)
                    pl.text(olga.cityLonM[i], olga.cityLatM[i],' '+olga.cityLoc[dom].shortName[i], size=8, ha='left', va='center', color='0.1')

            # Plot airspace
            if(False):
                plotairspace(m)

            # If filled contour, add colorbar
            if(cf != False):
                cax = pl.axes([axl+axw+0.02, axb+ 0.1*axh, 0.02, 0.8*axh])
                cb  = pl.colorbar(cf, drawedges=True, cax=cax)
                cb.ax.tick_params(labelsize = 8) 
                cb.ax.yaxis.set_tick_params(width = 0)
#                cb.outline.set_color('white')
                cb.set_label(units)
            pl.axes(ax)
        
            # Draw coast and country outlines 
            m.drawcoastlines(linewidth=1.5, color=countryLines)
            m.drawcountries(linewidth=1.5, color=countryLines)
        
            # Draw rivers 
            if(olga.drawRivers[dom]):
                m.drawrivers(linewidth=0.5, color='#0066FF')
 
            # Add description variables, units, OLGA label, logo, etc. 
            pl.figtext(axl, axb/2,'%s'%olga.map_desc[dom],size=7,ha='left', va='center')

            if(var=='pfd'):
                subtitle = 'cumulative distance over: %s'%str(wrf.date_PFD[t]) 
            else:
                subtitle = 'valid: %s UTC'%str(wrf.datetime[t])

            # Add figure info (variable, units, time)
            ax.set_title(title, loc='left', size=8)
            ax.set_title(subtitle, loc='right', size=8)

            # Add OLGA logo
            pl.figimage(olga.olga_logo, olga.fig_width_px-121, 4)

            # Get name and save figure 
            if(var=='pfd' or var == 'pfd2'):
                tmp    = '%06i'%(olga.islice*24*100) 
            else:
                xtime  = wrf.time[t] / 3600.
                hour   = int(np.floor(xtime))
                minute = int((xtime - hour) * 60.)
                tmp    = str(hour).zfill(4) + str(minute).zfill(2)

            if(var == 'pfd' or var == 'pfd2'):
                name = '%s%04i%02i%02i_t%02iz/%s_%s_%02i_%s.png'%(olga.figRoot, olga.year, olga.month, olga.day, olga.cycle, var, olga.pfdNames[n], dom+1, tmp)
            else:
                name = '%s%04i%02i%02i_t%02iz/%s_%02i_%s.png'%(olga.figRoot, olga.year, olga.month, olga.day, olga.cycle, var, dom+1, tmp)

            pl.savefig(name, dpi=olga.fig_dpi)
        
        # Cleanup!
        fig.clf()
        pl.close()
        gc.collect()
 def place_image(logo, x, y):
     P.figimage(N.asarray(logo, dtype=N.float32) / 255., x*dpi, y*dpi)
Пример #18
0
def create_timeseries(olga, wrfout, dom, times):

    # colormap for cloud cover
    cld = make_colormap({0.: '#05b5ff', 0.3: '#bdecff', 1.0: '#ffffff'})

    olga_logo = pl.matplotlib.image.imread(olga.olgaRoot +
                                           'include/olga_left.png')

    # Loop over requested locations
    for name, longName, lon, lat, type in zip(olga.soundLoc[dom].shortName,
                                              olga.soundLoc[dom].longName,
                                              olga.soundLoc[dom].lon,
                                              olga.soundLoc[dom].lat,
                                              olga.soundLoc[dom].type):
        if (type == 0 or type == 2):
            # Read WRF data
            d = readwrf_loc(olga, wrfout, lon, lat, times[0], times[-1])

            # DEBUGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
            #figure()
            #for t in range(np.size(d.t0_ana)):
            #    t0 = d.t0_ana[t]
            #    t1 = d.t1_ana[t]
            #    figure()
            #    for tt in range(t0,t1):
            #        sp = tt-t0
            #        ax=subplot(5,4,sp+1)
            #        title(str(tt))
            #        d.w[tt,d.w[tt,:]<0] = 0
            #        plot(d.w[tt,:], d.zf[tt,:],'r-',label='w_up')
            #        plot(d.qltemf[tt,:]*10000, d.zf[tt,:],'b-',label='ql_up*1e4')
            #        ylim(0,3000)
            #        xlim(0,3)
            #        if(tt == t0): legend(frameon=False)
            #        if(sp % 4 != 0): ax.tick_params(labelleft='off')
            #        if(sp < 16): ax.tick_params(labelbottom='off')
            #        grid()

            #    savefig('test_%s.png'%name)

            # Loop over diffent day (if available):
            for t in range(np.size(d.t0_ana)):
                t0 = d.t0_ana[t]
                t1 = d.t1_ana[t]
                x0 = d.hour[t0]
                x1 = d.hour[t1]

                fig = pl.figure(
                    figsize=(olga.fig_width_px / float(olga.fig_dpi),
                             olga.fig_width_px / float(olga.fig_dpi)))
                #                   L    B    R    T    ws  hs
                fig.subplots_adjust(0.10, 0.11, 0.98, 0.88, 0.35, 0.55)
                pl.figtext(0.5,
                           0.95,
                           '%s [%.2fN, %.2fE]' % (longName, lat, lon),
                           size=9,
                           ha='center')
                pl.figtext(0.5, 0.93, '%s' % (d.date[t0]), size=8, ha='center')
                gs = pl.matplotlib.gridspec.GridSpec(
                    4, 2, height_ratios=[1., 1., 0.4, 1], width_ratios=[2, 1])

                # -------------------------------------------------
                # Updraft velocity / height: wstar
                # -------------------------------------------------
                #ax = pl.subplot(gs[:2,0]); modplot(ax)
                #ax.set_title('Updraft velocity and height',loc='left')
                #zs = d.z[0,0]  # terrain height (lowest half level)
                #wm = 3.5       # scaling for colormap
                #bw1 = 0.6      # width of sub-cloud updrafts
                #bw2 = 0.8      # width of cloud updrafts
                #for i in range(t0,t1+1):
                #    if(d.wglider[i] > 0.0):
                #        color = wup((np.floor(d.wglider[i])+0.5)/wm)
                #        pl.bar(d.hour[i]-0.5*bw1, d.zi[i],         width=bw1, bottom=zs,         color=color,           edgecolor='none')
                #        pl.bar(d.hour[i]-0.5*bw2, d.ct[i]-d.zi[i], width=bw2, bottom=d.zi[i]+zs, color='k',  alpha=0.3, edgecolor='none')

                ## Add surface
                #pl.plot([d.hour[t0], d.hour[t1]],[zs, zs], 'k:')
                #pl.text(d.hour[t0]+0.2,zs,'surface',size=7,ha='left',va='bottom')

                ## Add sort-of colorbar
                #wups = ([0.5,1.5,2.5,3.5])
                #names = (['0-1 m/s','1-2 m/s','2-3 m/s','>3 m/s'])
                #for wu,nam in zip(wups,names):
                #    pl.scatter([-10],[300],color=wup(wu/wm),label=nam)
                #pl.legend(frameon=False,loc=2)
                #pl.xlim(d.hour[t0],d.hour[t1])
                #pl.ylim(0,3000)
                #pl.ylabel('z [m AMSL]')
                #pl.xticks(np.arange(d.hour[t0],d.hour[t1]+0.001,2))
                #pl.yticks(np.arange(0,3000.001,500))

                # -------------------------------------------------
                # Updraft velocity / height: vertical velocity TEMF
                # -------------------------------------------------
                ax = pl.subplot(gs[:2, 0])
                modplot(ax)
                ax.set_title('Updraft velocity and height', loc='left', size=8)
                zs = d.z[0, 0]  # terrain height (lowest half level)
                wm = 4  # scaling for colormap
                bw1 = 0.70  # width of sub-cloud updrafts
                bw2 = 0.85  # width of cloud updrafts

                # Loop over all time steps
                for tt in range(d.nt):
                    # TO-DO: TEMF often doesn't decay updraft velocity after convection stop.
                    # Limit plot to conditions with unstable near-surface layer:
                    if (d.thv[tt, 1] < d.thv[tt, 0]):
                        # Plot updraft velocity
                        wc_p, cc_p = w_discretized(d.w[tt, 0])
                        k_p = 0
                        wc_max = 0
                        for k in range(key_nearest(d.zf[tt, :], 3000) + 1):
                            # Current discretized updraft velocity
                            wc_a, cc_a = w_discretized(d.w[tt, k])
                            wc_max = np.max((wc_max, wc_a))

                            # If current velocity differs from previous, draw bar from k_p to k
                            if (wc_a != wc_p):
                                pl.bar(d.hour[tt] - 0.5 * bw1,
                                       d.z[tt, k] - d.z[tt, k_p],
                                       width=bw1,
                                       bottom=d.z[tt, k_p],
                                       color=cc_p,
                                       edgecolor='none')
                                wc_p = wc_a
                                cc_p = cc_a
                                k_p = k

                        # Plot cumulus clouds, only if there is something like an updraft below
                        if (wc_max > 0):
                            cloud = False  # flag to see if we have cumulus
                            for k in range(key_nearest(d.zf[tt, :], 3000) + 1):
                                ql = np.max((0, d.qltemf[tt, k]))

                                if (ql >= 5e-5 and cloud == False):
                                    cloud = True
                                    kc_p = k

                                if (ql < 5e-5 and cloud == True):
                                    pl.bar(d.hour[tt] - 0.5 * bw2,
                                           d.z[tt, k + 1] - d.z[tt, kc_p],
                                           width=bw2,
                                           bottom=d.z[tt, kc_p],
                                           color='0.9',
                                           edgecolor='k',
                                           alpha=0.5)
                                    cloud = False

                # Add line at surface
                pl.plot([d.hour[t0], d.hour[t1]], [zs, zs], 'k:')
                pl.text(d.hour[t0] + 0.2,
                        zs,
                        'surface',
                        size=7,
                        ha='left',
                        va='bottom')

                # Add sort-of colorbar
                wups = ([0.7, 1, 2, 3])
                names = (['0.7-1 m/s', '1-2 m/s', '2-3 m/s', '>3 m/s'])
                for wu, nam in zip(wups, names):
                    tmp, cc = w_discretized(wu)
                    pl.scatter([-10], [300], marker='s', color=cc, label=nam)
                pl.plot([-10, -10], [300, 300], 'k-', label='cumulus')
                pl.legend(frameon=False, loc=2, scatterpoints=1)
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.ylim(0, 3000)
                pl.ylabel('z [m AMSL]')
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.yticks(np.arange(0, 3000.001, 500))

                # -------------------------------------------------
                # Pressure
                # -------------------------------------------------
                ax = pl.subplot(gs[0, 1])
                modplot(ax)
                ax.set_title('Surface pressure', loc='left', size=8)
                slp = d.slps[t0:t1] / 100.
                pl.plot(d.hour[t0:t1], slp, 'k-')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.ylabel('hPa')
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                if (slp.max() - slp.min() < 10):
                    pl.ylim(
                        roundNumber(slp.mean(), 1, DOWN) - 5,
                        roundNumber(slp.mean(), 1, UP) + 5)

                # -------------------------------------------------
                # Air temperature / dew poiunt temperature
                # -------------------------------------------------
                ax = pl.subplot(gs[1, 1])
                modplot(ax)
                ax.set_title('T and Td at 2m', loc='left', size=8)
                pl.plot(d.hour[t0:t1], d.T2[t0:t1] - 273.15, 'k-', label='T')
                pl.plot(d.hour[t0:t1],
                        d.Td2[t0:t1] - 273.15,
                        'k-',
                        label='Td',
                        dashes=[4, 2])
                pl.ylabel('celcius')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.legend(frameon=False, loc=2)

                # -------------------------------------------------
                # Rain
                # -------------------------------------------------
                ax = pl.subplot(gs[2, 1])
                modplot(ax)
                ax.set_title('Rain', loc='left', size=8)
                pl.bar(d.hour[t0:t1],
                       d.drr_mp[t0:t1],
                       color='g',
                       edgecolor='none')
                pl.bar(d.hour[t0:t1],
                       d.drr_con[t0:t1],
                       bottom=d.drr_mp[t0:t1],
                       color='b',
                       edgecolor='none')
                pl.ylabel('mm')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.ylim(
                    0,
                    max(
                        1,
                        roundNumber((d.drr_mp[t0:t1] + d.drr_con[t0:t1]).max(),
                                    1, UP)))

                # -------------------------------------------------
                # Shortwave radiation
                # -------------------------------------------------
                ax = pl.subplot(gs[3, 1])
                modplot(ax)
                ax.set_title('Shortwave radiation', loc='left', size=8)
                pl.plot(d.hour[t0:t1], d.swd[t0:t1], 'k-')
                pl.plot(d.hour[t0:t1],
                        d.swdc[t0:t1],
                        'k-',
                        label='Pot.',
                        dashes=[4, 2])
                pl.ylabel('W/m2')
                pl.xlabel('time UTC [h]')
                pl.xlim(d.hour[t0], d.hour[t1])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.ylim(0, 1000)
                pl.yticks(np.arange(0, 1000.01, 200))
                pl.legend(frameon=False, loc=2, borderpad=0)

                # -------------------------------------------------
                # Cloud cover
                # -------------------------------------------------
                ax = pl.subplot(gs[2, 0])
                modplot(ax)
                ax.set_title('Cloud cover', loc='left', size=8)
                pl.pcolormesh(d.ccl, cmap=cld, vmin=0, vmax=1)
                pl.text(d.hour[t0] - 0.4,
                        0.5,
                        'low',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        1.5,
                        'middle',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        2.5,
                        'high',
                        size=7,
                        ha='right',
                        va='center')
                pl.xlim(d.hour[t0], d.hour[t1])
                ax.set_yticks([])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))

                # -------------------------------------------------
                # Wind
                # -------------------------------------------------
                ax = pl.subplot(gs[3, 0])
                modplot(ax)
                ax.set_title('Wind', loc='left', size=8)
                k500 = key_nearest(d.zf[0, :], 500)
                k1000 = key_nearest(d.zf[0, :], 1000)
                k2000 = key_nearest(d.zf[0, :], 2000)
                pl.barbs(d.hour[t0:t1 + 1],
                         0.5,
                         d.u10[t0:t1 + 1] * m2k,
                         d.v10[t0:t1 + 1] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.barbs(d.hour[t0:t1 + 1],
                         1.5,
                         d.u[t0:t1 + 1, k500] * m2k,
                         d.v[t0:t1 + 1, k500] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.barbs(d.hour[t0:t1 + 1],
                         2.5,
                         d.u[t0:t1 + 1, k1000] * m2k,
                         d.v[t0:t1 + 1, k1000] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.barbs(d.hour[t0:t1 + 1],
                         3.5,
                         d.u[t0:t1 + 1, k2000] * m2k,
                         d.v[t0:t1 + 1, k2000] * m2k,
                         length=5,
                         linewidth=0.5,
                         pivot='middle')
                pl.text(d.hour[t0] - 0.4,
                        0.5,
                        '10m',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        1.5,
                        '500m',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        2.5,
                        '1000m',
                        size=7,
                        ha='right',
                        va='center')
                pl.text(d.hour[t0] - 0.4,
                        3.5,
                        '2000m',
                        size=7,
                        ha='right',
                        va='center')
                pl.xlim(0, 24)
                pl.xlim(d.hour[t0], d.hour[t1])
                ax.set_yticks([])
                pl.xticks(np.arange(d.hour[t0], d.hour[t1] + 0.001, 2))
                pl.xlabel('time UTC [h]')

                # Add logo (105px wide)
                pl.figimage(olga_logo, 10, olga.fig_width_px - 40)
                pl.figtext(0.01,
                           0.011,
                           '%s' % (olga.map_desc[dom]),
                           size=7,
                           ha='left')

                # Save figure
                tmp = '%06i' % (olga.islice * 24 * 100)
                name = '%s%04i%02i%02i_t%02iz/tser_%s_%02i_%s.png' % (
                    olga.figRoot, olga.year, olga.month, olga.day, olga.cycle,
                    name, dom + 1, tmp)
                pl.savefig(name, dpi=olga.fig_dpi)
Пример #19
0
plt.bone()
frame = 0

if video:
    kernellen = 31
    steps = 125
    turns = 3
    for t in np.linspace(0, turns, steps, endpoint=False):
        k = kernels.hanning_ripples(shift=t)
        k = k.astype(np.float32)

        image = lic_internal.line_integral_convolution(u, v, texture, k)

        plt.clf()
        plt.axis('off')
        plt.figimage(image)
        plt.gcf().set_size_inches((size / float(dpi), size / float(dpi)))
        plt.savefig("flow-%04d.png" % frame, dpi=dpi)
        frame += 1
else:
    kernellen = 31
    kernel = np.sin(np.arange(kernellen) * np.pi / kernellen)
    kernel = kernel.astype(np.float32)

    image = lic_internal.line_integral_convolution(u, v, texture, kernel)

    plt.clf()
    plt.axis('off')
    plt.figimage(image)
    plt.gcf().set_size_inches((size / float(dpi), size / float(dpi)))
    plt.savefig("flow-image.png", dpi=dpi)
Пример #20
0
def skewtlogp(olga, si):
    """ 
    Get directory of script for saving arrays
    """
    tmpPath = os.path.dirname(os.path.realpath(__file__))+'/tmp/'
    if(not os.path.isdir(tmpPath)):
        os.mkdir(tmpPath)

    """
    Settings for high and low sounding top
    """
    if(si.stype==0):
        pbottom = 105000.       # highest pressure in diagram (bottom)
        ptop = 20000.           # lowest pressue in diagram (top)
        ptop_thd = 40000        # top of dry adiabats
        ptop_mxr = 60000        # top of mixing ratio lines
        pbottom_thw = pbottom   # bottom of moist adiabats
        dp = 100.               # pressure interval used in some calculations
        Tleft = -35.            # lowest temperature (@pb) in diagram (left)
        Tright = 35.            # highest temperature (@pb) in diagram (right)
        dp_label = 7000

        isotherms     = np.arange(-100,30.001,10)
        isobars       = np.array([1050.,1000.,850.,700.,500.,400.,300.,250.,200.,150.,100.,50])*100.
        dryadiabats   = np.arange(-30,50.001,10) 
        moistadiabats = np.array([28.,24.,20.,16.,12.,8.,4.,0.])
        mixrat        = np.array([20.,12.,8.,5.,3.,2.,1.])
    elif(si.stype==1):
        pbottom = 105000.       # highest pressure in diagram (bottom)
        ptop = 50000.           # lowest pressue in diagram (top)
        ptop_thd = 70000        # top of dry adiabats
        ptop_mxr = 70000        # top of mixing ratio lines
        pbottom_thw = pbottom   # bottom of moist adiabats
        dp = 100.               # pressure interval used in some calculations
        Tleft = -11.            # lowest temperature (@pb) in diagram (left)
        Tright = 35.            # highest temperature (@pb) in diagram (right)
        dp_label = 2500         # spacing (in pressure coords) of some label placement

        isotherms     = np.arange(-100,60.001,10)
        isobars       = np.array([1050.,1000.,900.,850.,700.,600.,500.])*100.
        dryadiabats   = np.arange(-10,30.001,5) 
        moistadiabats = np.array([28.,24.,20.,16.,12.,8.,4.,0.])
        mixrat        = np.array([20.,12.,8.,5.,3.,2.,1.])
    else:
        sys.exit('stype=%i not supported!'%stype)

    """
    Setup figure
    """
    if(olga != -1):
        fig = pl.figure(figsize=(olga.fig_width_px/float(olga.fig_dpi), olga.fig_width_px/float(olga.fig_dpi)))
    else:
        fig = pl.figure(figsize=(8,8))

    #                   L    B    R    T    ws  hs
    fig.subplots_adjust(0.08,0.10,1.0,0.93,0.2,0.08)
    pl.subplot(111)

    # Calculate bounds in figure coordinates
    y00 = skewty(pbottom)
    y11 = skewty(ptop)
    x00 = skewtx(Tleft,y00)
    x11 = skewtx(Tright,y00)

    # Spacing for some labels
    hs = np.abs(x11-x00)/200.
    vs = np.abs(y11-y00)/200.
 
    """
    1. Create isotherms
    """
    for T in isotherms:
        y = np.array([skewty(pbottom),skewty(ptop)])
        x = np.array([skewtx(T,y[0]),skewtx(T,y[1])])

        # Check if partially out of bounds
        lloc = 0
        if(x[0] < x00):
            x[0] = x00
            y[0] = iskewtxT(x00,T)
        if(x[1] > x11):
            x[1] = x11
            y[1] = iskewtxT(x11,T)

        if(x[1] >= x00 and y[1] >= y00):
            pl.plot(x,y,color=c2,alpha=a1)
            if(x[0] > x00 and x[0] < x11):
              pl.text(x[0],y[0]-2*hs,int(T),ha='center',va='top',color=c2)
            else:
              pl.text(x[1]-5*hs,y[1]-5*vs,int(T),ha='center',va='center',color=c2,alpha=a2)

    """
    2. Create isobars
    """
    for p in isobars:
        # Check if out of bounds
        if((p >= ptop) and (p <= pbottom)):
            y = skewty(p)
            pl.plot([x00,x11],[y,y],color=c2,alpha=a1)
            pl.text(x00-hs,y,int(p/100.),ha='right',va='center',color=c2)
         
    """
    3. Create dry adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath+'theta_p_%i.arr'%si.stype)
        y = np.load(tmpPath+'theta_y_%i.arr'%si.stype)
        x = np.load(tmpPath+'theta_x_%i.arr'%si.stype)
    except:
        p = np.arange(pbottom,(np.max(([ptop,ptop_thd]))-dp),-dp)
        x = np.zeros((dryadiabats.size, p.size))   
        y = np.zeros(p.size)   

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(dryadiabats.size):
            x[i,:] = 0.
            for k in range(p.size):
                xtmp = skewtx(((dryadiabats[i]+T0) * exner(p[k]))-T0, y[k])
                if(xtmp >= x00 and xtmp <= x11):
                    x[i,k] = xtmp
                else:
                    x[i,k] = -9999

        p.dump(tmpPath+'theta_p_%i.arr'%si.stype)
        y.dump(tmpPath+'theta_y_%i.arr'%si.stype)
        x.dump(tmpPath+'theta_x_%i.arr'%si.stype)

    # Plot the dry adiabats
    for i in range(dryadiabats.size): 
        doPlot = np.where(x[i,:] != -9999)[0]
        if(doPlot[0].size > 0):
            lloc = max(0,np.size(x[i,doPlot])-int(5000./dp))
            pl.plot(x[i,doPlot],y[doPlot],color=c1)
            pl.text(x[i,doPlot][lloc],y[doPlot][lloc],int(dryadiabats[i]),color=c1,ha='center',va='center',backgroundcolor='w')

    """ 
    4. Create moist adiabats
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath+'thetam_p_%i.arr'%si.stype)
        y = np.load(tmpPath+'thetam_y_%i.arr'%si.stype)
        x = np.load(tmpPath+'thetam_x_%i.arr'%si.stype)
    except:
        p = np.arange(np.min(([pbottom,pbottom_thw])),ptop-dp,-dp)
        x = np.zeros((moistadiabats.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(moistadiabats.size):
            for k in range(p.size):
                thw = dsatlftskewt(moistadiabats[i], p[k])
                xtmp = skewtx(thw, y[k])
                if(xtmp >= x00 and xtmp <= x11):
                    x[i,k] = xtmp
                else:
                    x[i,k] = -9999
        
        p.dump(tmpPath+'thetam_p_%i.arr'%si.stype)
        y.dump(tmpPath+'thetam_y_%i.arr'%si.stype)
        x.dump(tmpPath+'thetam_x_%i.arr'%si.stype)
    
    # Plot the moist adiabats
    for i in range(moistadiabats.size):
        doPlot = np.where(x[i,:] != -9999)[0]
        if(doPlot[0].size > 0):
            lloc = max(0,np.size(x[i,doPlot])-int(8000./dp))
            pl.plot(x[i,doPlot],y[doPlot],'--',color=c3)
            pl.text(x[i,doPlot][lloc],y[doPlot][lloc],int(moistadiabats[i]),color=c3,ha='center',va='center',backgroundcolor='w')
 
    """ 
    5. Create isohumes / mixing ratio lines
    """
    # Try loading the data from the tmp directory. If not available, calculate
    # and save the arrays
    try:
        p = np.load(tmpPath+'mixr_p_%i.arr'%si.stype)
        y = np.load(tmpPath+'mixr_y_%i.arr'%si.stype)
        x = np.load(tmpPath+'mixr_x_%i.arr'%si.stype)
    except:
        p = np.arange(pbottom,(np.max(([ptop,ptop_mxr]))-dp),-dp)
        x = np.zeros((mixrat.size, p.size))
        y = np.zeros(p.size)

        for k in range(p.size):
            y[k] = skewty(p[k])
        for i in range(mixrat.size):
            for k in range(p.size):
                mix = Td(mixrat[i]/1000.,p[k])-T0 
                xtmp = skewtx(mix,y[k])
                if(xtmp >= x00 and xtmp <= x11):
                    x[i,k] = xtmp
                else:
                    x[i,k] = -9999

        p.dump(tmpPath+'mixr_p_%i.arr'%si.stype)
        y.dump(tmpPath+'mixr_y_%i.arr'%si.stype)
        x.dump(tmpPath+'mixr_x_%i.arr'%si.stype)

    # Plot the mixing ratio lines
    for i in range(mixrat.size):
        doPlot = np.where(x[i,:] != -9999)[0]
        if(doPlot[0].size > 0):
            pl.plot(x[i,doPlot],y[doPlot],color=c5,dashes=[3,2])
            pl.text(x[i,doPlot][-1],y[doPlot][-1]+vs,int(mixrat[i]),color=c5,ha='center',va='bottom',backgroundcolor='w')

    """
    6. Add sounding data
    """
    # 6.1 Temperature and dewpoint temperature
    if(si.T.size > 0):
        y = skewty(si.p)
        x1 = skewtx(si.T-T0,y)
        x2 = skewtx(si.Td-T0,y)

        pl.plot(x1,y,'-',color=cT,linewidth=2)
        pl.plot(x2,y,'-',color=cTd,linewidth=2)

    # 6.2 Add height labels to axis
    if(si.z.size > 0 and si.z.size==si.p.size):
        y = skewty(si.p)
        p_last = 1e9 
        for k in range(si.z.size):
            if(y[k] <= y11 and np.abs(si.p[k]-p_last) > dp_label):
                pl.text(x11+hs,y[k],str(int(si.z[k]))+'m',color=c2,ha='right',va='center',size=7,backgroundcolor='w')
                p_last = si.p[k]

    # 6.2 Wind barbs
    if(si.u.size > 0):
        y   = skewty(si.p)
        u   = si.u * 1.95
        v   = si.v * 1.95 
        xb  = x11 + 9*hs 

        p_last = 1e9 
        for k in range(si.z.size):
            if(y[k] <= y11 and np.abs(si.p[k]-p_last) > dp_label):
                pl.barbs(xb,y[k],u[k],v[k],length=5.2,linewidth=0.5,pivot='middle')  
                p_last = si.p[k]

    """
    6.1 :) Try to add measured data
    """
    # 6.1 Temperature and dewpoint temperature
    if(si.Tm.size > 0):
        y  = skewty(si.pm)
        x1 = skewtx(si.Tm,y)
        x2 = skewtx(si.Tdm,y)

        pl.plot(x1,y,'--',color=cT,linewidth=1)
        pl.plot(x2,y,'--',color=cTd,linewidth=1)

    """
    7. Lauch parcel
    """
    if(si.parcel == True):
        # Plot starting position:
        p0s  = skewty(si.ps)
        T0s  = skewtx(si.Ts-T0, p0s)
        Td0s = skewtx(Td(si.rs,si.ps)-T0, p0s)
        pl.scatter(T0s, p0s, facecolor='none')
        pl.scatter(Td0s,p0s, facecolor='none')

        # Lists to hold parcel pressure, temp and dewpoint temp during ascent
        pp  = [si.ps]
        Tp  = [si.Ts]
        Tdp = [Td(si.rs, si.ps)]

        # Launch parcel
        n = 0
        while(Tp[-1] > Tdp[-1] and n<1000):
            n  += 1
            dp2 = max(1,(Tp[-1] - Tdp[-1])*300) # bit weird, but fast
            pp. append(pp[-1] - dp2)
            Tp. append(si.Ts*exner(pp[-1], si.ps))
            Tdp.append(Td(si.rs, pp[-1]))

        # Plot lines from surface --> LCL
        ps   = skewty(np.array(pp))
        Tps  = skewtx(np.array(Tp)-T0,  ps)
        Tdps = skewtx(np.array(Tdp)-T0, ps)
        pl.plot(Tps,  ps, 'k', linewidth=1.5, dashes=[4,2])
        pl.plot(Tdps, ps, 'k', linewidth=1.5, dashes=[4,2])
        pl.scatter(Tps[-1], ps[-1], facecolor='none')

        # Iteratively find the moist adiabat starting at p0, which goes through the temperature at LCL
        Ths      = si.Ts / exner(si.ps, p0)         # potential temperature surface (@p0)
        ThwsLCL  = dsatlftskewt(Ths-T0, pp[-1])+T0  # Temp moist adiabat at plcl, through Ths
        thw0     = Ths - (ThwsLCL - Tp[-1])         # First estimate of moist adiabat passing through Tlcl

        ThwLCL   = dsatlftskewt(thw0-T0, pp[-1])+T0
        while(np.abs(ThwLCL-Tp[-1]) > 0.1):
            thw0    -= ThwLCL-Tp[-1] 
            ThwLCL   = dsatlftskewt(thw0-T0, pp[-1])+T0

        # Plot moist adiabat from LCL upwards
        p = np.arange(pp[-1], ptop, -dp)
        x = np.zeros(p.size)
        y = np.zeros(p.size)
        for k in range(p.size):
            thw = dsatlftskewt(thw0-T0,p[k])
            y[k] = skewty(p[k])
            x[k] = skewtx(thw,y[k])

        pl.plot(x,y,'k', linewidth=1.5, dashes=[4,2])


    """
    Add info from TEMF boundary layer scheme
    """
    if(si.Tu.size > 0):
        # Cloud fraction
        dw = (x11-x00)    # width of diagram
        y  = skewty(si.p)
        x = x00 + si.cfru * 0.2 * (x11-x00)
        pl.plot(x,y,'-',linewidth=1.5,color=c6) # cloud cover

        cfr_pos = np.where(si.cfru > 0.001)[0]
        if(np.size(cfr_pos)>1):
            pl.text(x00,y[cfr_pos[0]-1],'- %im'%(si.z[cfr_pos[0]-1]),ha='left',va='center',size=8,color=c6)
            pl.text(x00,y[cfr_pos[-1]],'- %im'%(si.z[cfr_pos[-1]]),ha='left',va='center',size=8,color=c6)
            kmax=np.where(si.cfru == si.cfru.max())[0][0]
            pl.text(x.max(),y[kmax],'- %i%%'%(si.cfru[kmax]*100.),ha='left',va='center',size=8,color=c6)

    """
    6. Finish diagram
    """ 
    pl.xticks([])
    pl.yticks([])
    pl.box('off')
    pl.xlim(x00-0.1,x11+16*hs)
    pl.ylim(y00-0.1,y11+0.1)

    # draw axis
    pl.plot([x00,x11],[y00,y00],'k-')
    pl.plot([x00,x00],[y00,y11],'k-')

    pl.figtext(0.5,0.05,'Temperature (C)',ha='center')
    pl.figtext(0.015,0.52,'Pressure (hPa)',rotation=90)
    label = 'Skew-T log-P, %s, %s UTC'%(si.name,si.time) 
    pl.figtext(0.5,0.97,label,ha='center')

    if(olga != -1):
        img = image.imread(olga.olgaRoot+'include/olga_left.png')
        pl.figimage(img,7,5)
        #pl.figimage(img,10,olga.fig_width_px-45)
        pl.figtext(0.99,0.011,'%s'%olga.map_desc[0],size=7,ha='right')

    return fig
Пример #21
0
def plot_light_curves(pfn, ucal=False):
    lightcurves = unpickle_from_file(pfn)

    if ucal:
        tag = 'ucal-'
    else:
        tag = ''

    survey = LegacySurveyData()
    brickname = '0364m042'
    catfn = survey.find_file('tractor', brick=brickname)
    print('Reading catalog from', catfn)
    cat = fits_table(catfn)
    print(len(cat), 'catalog entries')
    cat.cut(cat.brick_primary)
    print(len(cat), 'brick primary')

    I = []
    for i, oid in enumerate(cat.objid):
        if (brickname, oid) in lightcurves:
            I.append(i)
    I = np.array(I)
    cat.cut(I)
    print('Cut to', len(cat), 'with light curves')

    S = fits_table('specObj-dr12-trim-2.fits')

    from astrometry.libkd.spherematch import match_radec
    I, J, d = match_radec(S.ra, S.dec, cat.ra, cat.dec, 2. / 3600.)
    print('Matched', len(I), 'to spectra')

    plt.subplots_adjust(hspace=0)

    movie_jpegs = []
    movie_wcs = None

    for i in range(28):
        fn = os.path.join('des-sn-movie', 'epoch%i' % i, 'coadd',
                          brickname[:3], brickname,
                          'legacysurvey-%s-image.jpg' % brickname)
        print(fn)
        if not os.path.exists(fn):
            continue

        img = plt.imread(fn)
        img = np.flipud(img)
        h, w, d = img.shape

        fn = os.path.join('des-sn-movie', 'epoch%i' % i, 'coadd',
                          brickname[:3], brickname,
                          'legacysurvey-%s-image-r.fits' % brickname)
        if not os.path.exists(fn):
            continue
        wcs = Tan(fn)

        movie_jpegs.append(img)
        movie_wcs = wcs

    plt.figure(figsize=(8, 6), dpi=100)
    n = 0

    fluxtags = [('flux', 'flux_ivar', '', 'a')]
    if ucal:
        fluxtags.append(('uflux', 'uflux_ivar', ': ucal', 'b'))

    for oid, ii in zip(cat.objid[J], I):
        print('Objid', oid)
        spec = S[ii]
        k = (brickname, oid)
        v = lightcurves[k]

        # Cut bad CCDs
        v.cut(np.array([e not in [230151, 230152, 230153] for e in v.expnum]))

        plt.clf()
        print('obj', k, 'has', len(v), 'measurements')
        T = v

        for fluxtag, fluxivtag, fluxname, plottag in fluxtags:
            plt.clf()

            filts = np.unique(T.filter)
            for i, f in enumerate(filts):
                from tractor.brightness import NanoMaggies

                plt.subplot(len(filts), 1, i + 1)

                fluxes = np.hstack(
                    [T.get(ft[0])[T.filter == f] for ft in fluxtags])
                fluxes = fluxes[np.isfinite(fluxes)]
                mn, mx = np.percentile(fluxes, [5, 95])
                print('Flux percentiles for filter', f, ':', mn, mx)
                # note swap
                mn, mx = NanoMaggies.nanomaggiesToMag(
                    mx), NanoMaggies.nanomaggiesToMag(mn)
                print('-> mags', mn, mx)

                cut = (T.filter == f) * (T.flux_ivar > 0)
                if ucal:
                    cut *= np.isfinite(T.uflux)
                I = np.flatnonzero(cut)

                print('  ', len(I), 'in', f, 'band')
                I = I[np.argsort(T.mjd[I])]
                mediv = np.median(T.flux_ivar[I])
                # cut really noisy ones
                I = I[T.flux_ivar[I] > 0.25 * mediv]

                #plt.plot(T.mjd[I], T.flux[I], '.-', color=dict(g='g',r='r',z='m')[f])
                # plt.errorbar(T.mjd[I], T.flux[I], yerr=1/np.sqrt(T.fluxiv[I]),
                #              fmt='.-', color=dict(g='g',r='r',z='m')[f])
                #plt.errorbar(T.mjd[I], T.flux[I], yerr=1/np.sqrt(T.fluxiv[I]),
                #             fmt='.', color=dict(g='g',r='r',z='m')[f])

                # if ucal:
                #     mag,dmag = NanoMaggies.fluxErrorsToMagErrors(T.flux[I], T.flux_ivar[I])
                # else:
                #     mag,dmag = NanoMaggies.fluxErrorsToMagErrors(T.uflux[I], T.uflux_ivar[I])
                mag, dmag = NanoMaggies.fluxErrorsToMagErrors(
                    T.get(fluxtag)[I],
                    T.get(fluxivtag)[I])

                plt.errorbar(T.mjd[I],
                             mag,
                             yerr=dmag,
                             fmt='.',
                             color=dict(g='g', r='r', z='m')[f])
                #yl,yh = plt.ylim()
                #plt.ylim(yh,yl)
                plt.ylim(mx, mn)

                plt.ylabel(f)

                if i + 1 < len(filts):
                    plt.xticks([])
                #plt.yscale('symlog')

            outfn = 'cutout_%.4f_%.4f.jpg' % (spec.ra, spec.dec)
            if not os.path.exists(outfn):
                url = 'http://legacysurvey.org/viewer/jpeg-cutout/?ra=%.4f&dec=%.4f&zoom=14&layer=sdssco&size=128' % (
                    spec.ra, spec.dec)
                cmd = 'wget -O %s "%s"' % (outfn, url)
                print(cmd)
                os.system(cmd)
            pix = plt.imread(outfn)
            h, w, d = pix.shape
            fig = plt.gcf()

            #print('fig bbox:', fig.bbox)
            #print('xmax, ymax', fig.bbox.xmax, fig.bbox.ymax)
            #plt.figimage(pix, 0, fig.bbox.ymax - h, zorder=10)
            #plt.figimage(pix, 0, fig.bbox.ymax, zorder=10)
            #plt.figimage(pix, fig.bbox.xmax - w, fig.bbox.ymax, zorder=10)
            plt.figimage(pix,
                         fig.bbox.xmax - (w + 2),
                         fig.bbox.ymax - (h + 2),
                         zorder=10)

            plt.suptitle('SDSS spectro object: %s at (%.4f, %.4f)%s' %
                         (spec.label.strip(), spec.ra, spec.dec, fluxname))
            plt.savefig('forced-%s%i-%s.png' % (tag, n, plottag))

        ok, x, y = movie_wcs.radec2pixelxy(spec.ra, spec.dec)
        x = int(np.round(x - 1))
        y = int(np.round(y - 1))
        sz = 32

        plt.clf()
        plt.subplots_adjust(hspace=0, wspace=0)
        k = 1
        for i, img in enumerate(movie_jpegs):
            stamp = img[y - sz:y + sz + 1, x - sz:x + sz + 1]

            plt.subplot(5, 6, k)
            plt.imshow(stamp, interpolation='nearest', origin='lower')
            plt.xticks([])
            plt.yticks([])
            k += 1
        plt.suptitle('SDSS spectro object: %s at (%.4f, %.4f): DES images' %
                     (spec.label.strip(), spec.ra, spec.dec))
        plt.savefig('forced-%s%i-c.png' % (tag, n))

        n += 1