Exemplo n.º 1
0
def mapWind(nest, time):
    """Creates a map of the domain, showing
    wind barbs for the given time
    """
    nc = openWRF(nest)
    nc1 = openWRF(nest + 1)
    Nx, Ny, _Nz, longitude, latitude, _dx, _dy, _x, _y = getDimensions(nc)
    m = _getMapForNC(nc, False, _getDL(nest), 100)
    _makeDots(m)
    u10 = nc.variables["U10"][time, :, :]
    v10 = nc.variables["V10"][time, :, :]
    # Use data from every 10th grid point
    windx = 1 + Nx / 10
    windy = 1 + Ny / 10
    lat10 = np.zeros((windy, windx))
    lon10 = np.zeros((windy, windx))
    uwind = np.zeros((windy, windx))
    vwind = np.zeros((windy, windx))
    for j in range(windy):
        for i in range(windx):
            uwind[j, i] = 0.5 * (u10[j * 10, i * 10] + u10[j * 10, i * 10 + 1])
            # print 'u: ' + str(uwind[j,i])
            vwind[j, i] = 0.5 * (v10[j * 10, i * 10] + v10[j * 10 + 1, i * 10])
            # print 'v: ' + str(vwind[j,i])
            lat10[j, i] = latitude[j * 10, i * 10]
            lon10[j, i] = longitude[j * 10, i * 10]

    x10, y10 = m(lon10, lat10)
    plt.barbs(x10, y10, uwind, vwind, barb_increments=barb_increments, linewidth=1.0, color="green")

    if nc1 is not None:
        _plotBorder(nc1, m, "black")
    plt.show()
    plt.close()
Exemplo n.º 2
0
    def graphDB(self,graphName):
        print self.dbFile
        csv_reader = csv.reader(open(self.dbFile,'r'))
        bigx = float(-sys.maxint -1)
        bigy = float(-sys.maxint -1)
        smallx = float(sys.maxint)
        smally = float(sys.maxint)
        
        verts = []
        for row in csv_reader:
            print row
            verts.append(row)

        x_arr = []
        y_arr = []
        for vert in verts:
            date = vert[0].split(':')
            print float(date[0])+(float(date[1])/60)
            x_arr.append(float(date[0])+(float(date[1])/60))
            y_arr.append(vert[1])
        
#         dates.date2num(x_arr)
        fig = plt.figure()
        ax = fig.add_axes([0.1,0.1,0.8,0.8])
        ax.set_xlabel('Time (hh:mm:ss)')
        ax.set_ylabel('Decibels (db)')
        #ax.set_xlim()
        ax.set_ylim(30,80)
        ax.plot(x_arr,y_arr)
        plt.show()
        plt.savefig(graphName)
Exemplo n.º 3
0
def mapTerrain(nest, includePMSL=False, includeTemp=False):
    """Creates a map of the domain, showing
    filled contours of the terrain
    """
    nc = openWRF(nest)
    met = openWPS(nest)
    nc1 = openWRF(nest + 1)
    _Nx, _Ny, _Nz, longitude, latitude, _dx, _dy, _x, _y = getDimensions(nc)

    m = _getMapForNC(nc, False, _getDL(nest), 100)
    x, y = m(longitude, latitude)
    _makeDots(m)

    if includeTemp and met is not None:
        ST = met.variables["TT"][0][0, :, :]
        cs = plt.contour(x, y, ST - T_zero, arange(-48, 50, 2.0), colors="blue", linestyles="solid")
        plt.clabel(cs, inline=1, fmt="%1.0f", fontsize=12)
    if includePMSL and met is not None:
        levels = arange(960.0, 1040.0, 1.0)
        PMSL = met.variables["PMSL"][0]
        cs = plt.contour(x, y, PMSL / 100.0, levels, colors="black", label="Pressure")
        plt.clabel(cs, inline=1, fmt="%1.0f", fontsize=11)

    heightground = (nc.variables["PH"][0][0, :, :] + nc.variables["PHB"][0][0, :, :]) / g
    plt.contourf(x, y, heightground, levels=arange(0, max_h, 100), cmap=cmap_grey, extend="max")
    plt.colorbar()
    if nc1 is not None:
        _plotBorder(nc1, m, "black")
    plt.show()
    plt.close()
Exemplo n.º 4
0
def mapDomains(includePMSL=False):
    """Creates a map of the outer domain, showing
    the location of the inner domains.
    If includePMSL is True contours of sea level pressure is
    plotted as well (if a WPS-file is found)
    """
    nc1 = openWRF(1)
    nc2 = openWRF(2)
    nc3 = openWRF(3)
    nc4 = openWRF(4)
    m = _getMapForNC(nc1)

    if includePMSL:
        met1 = openWPS(1)
        if met1 is not None:
            PMSL = met1.variables["PMSL"][0]
            _Nx1, _Ny1, _Nz1, longitude1, latitude1, _dx, _dy, _x, _y = getDimensions(nc1)
            x, y = m(longitude1, latitude1)
            cs = plt.contour(x, y, PMSL / 100.0, pmsl_int, colors="black")
            plt.clabel(cs, inline=1, fmt="%1.0f", fontsize=11)
        else:
            print "Could not find wps-file, PMSL not plotted"

    if nc2 is not None:
        _plotBorder(nc2, m)
    if nc3 is not None:
        _plotBorder(nc3, m)
    if nc4 is not None:
        _plotBorder(nc4, m)

    plt.show()
    plt.close()
Exemplo n.º 5
0
def mapDomains(includePMSL=False):
    """Creates a map of the outer domain, showing
    the location of the inner domains.
    If includePMSL is True contours of sea level pressure is
    plotted as well (if a WPS-file is found)
    """
    nc1 = openWRF(1)
    nc2 = openWRF(2)
    nc3 = openWRF(3)
    nc4 = openWRF(4)
    m = _getMapForNC(nc1)

    if includePMSL:
        met1 = openWPS(1)
        if met1 is not None:
            PMSL = met1.variables['PMSL'][0]
            _Nx1, _Ny1, _Nz1, longitude1, latitude1, _dx, _dy, _x, _y = getDimensions(
                nc1)
            x, y = m(longitude1, latitude1)
            cs = plt.contour(x, y, PMSL / 100., pmsl_int, colors='black')
            plt.clabel(cs, inline=1, fmt='%1.0f', fontsize=11)
        else:
            print 'Could not find wps-file, PMSL not plotted'

    if (nc2 is not None):
        _plotBorder(nc2, m)
    if (nc3 is not None):
        _plotBorder(nc3, m)
    if (nc4 is not None):
        _plotBorder(nc4, m)

    plt.show()
    plt.close()
Exemplo n.º 6
0
    def graphSpec(self,graphName):
        csv_reader = csv.reader(open(self.specFile,'r'))
        cnt = 0
        frequencies = None
        decibels = None
        for line in csv_reader:
            if cnt == 0:
                frequencies = line
                cnt += 1
            else:
                decibels = line
#         decibels = [(decibels)]
        print frequencies, decibels

        cnt=0
        frequencies_floats=[]
        for x in frequencies:
            frequencies_floats.append(float(x))
            cnt+=1
        cnt=0
        decibels_floats=[]
        for x in decibels:
            decibels_floats.append(float(x))
            cnt+=1
        N=len(decibels)
        ind = np.arange(N)
        width = .35
        fig = plt.figure()
        plt.bar(ind,decibels_floats,width)
        plt.xticks(ind+width/2., frequencies,rotation=40, size='small')
        plt.xlabel("Frequency (Hz)")
        plt.ylabel("Decibels (db)")
        plt.show()
Exemplo n.º 7
0
def mapTerrain(nest,includePMSL=False,includeTemp=False):
    """Creates a map of the domain, showing
    filled contours of the terrain
    """
    nc = openWRF(nest)
    met = openWPS(nest)
    nc1 = openWRF(nest+1)
    _Nx,_Ny,_Nz,longitude,latitude,_dx,_dy,_x,_y = getDimensions(nc)

    m = _getMapForNC(nc,False,_getDL(nest),100)
    x, y = m(longitude,latitude)
    _makeDots(m)
    
    if (includeTemp and met is not None):
        ST = met.variables['TT'][0][0,:,:]
        cs = plt.contour(x,y, ST-T_zero,arange(-48,50,2.),colors='blue',linestyles='solid')
        plt.clabel(cs, inline=1,  fmt='%1.0f', fontsize=12)
    if (includePMSL and met is not None):
        levels = arange(960.,1040.,1.)
        PMSL = met.variables['PMSL'][0]
        cs = plt.contour(x,y, PMSL/100.,levels,colors='black',label='Pressure')
        plt.clabel(cs, inline=1,  fmt='%1.0f', fontsize=11)

    heightground = (nc.variables['PH'][0][0,:,:] + nc.variables['PHB'][0][0,:,:])/g
    plt.contourf(x, y, heightground, levels=arange(0,max_h,100),cmap=cmap_grey,extend='max')
    plt.colorbar()
    if (nc1 is not None):
        _plotBorder(nc1,m,'black')
    plt.show()  
    plt.close()
Exemplo n.º 8
0
def get_scanpos_given_circles(XY_roi, XY, Circs, stm_r_roi, stm_r,
                              ax=None, max_pipette_xovershoot=300.):

    """
    Parameters
    ----------
    XY_roi                 - center positions of circular regions of interest
    XY                     - 
    Circs                  - 
    stm_r_roi              - radius of circular regions of interest, in microns
    stm_r                  - radius of light stimulus, in microns
    ax                     - matplotlib axes object on which IM is plotted. 
    max_pipette_xovershoot - In microns. Max x distance to move to the right 
                             of pipette tip. Go to far and the objective will 
                             touch the pipette and destroy the patch. 
                             Assumes that the pipette enters from the right.
                             In microns.
    Returns
    -------
                         
    """
    
    # If no axes was set, plot on the currently active.
    if ax is None:
        ax = plt.gca()
    step_len = np.floor(sqrt(2*stm_r**2))
    xlim, ylim = np.sort(ax.get_xlim()), np.sort(ax.get_ylim())
    # Draw a grid with spacing 'step_len' covering the entire image
    y, x = np.ogrid[ylim[0]:ylim[1]:step_len,xlim[0]:xlim[1]:step_len]
    mask = np.zeros((y.shape[0],x.shape[1]))
    for xcntr,ycntr in XY_roi:
        mask = logical_or(mask,
                          ((y - ycntr)**2 + (x - xcntr)**2) <= stm_r_roi**2) 
    labeled_mask, n_labels = label( mask )
    mask_labels = np.unique( labeled_mask )[1:]
    ix0 = XY.shape[0]
    XY.resize(ix0+mask.sum(), refcheck=False)
    for ix, ml in enumerate(mask_labels):
        y_ix, x_ix = nonzero(labeled_mask == ml)
        ix1 = x_ix.shape[0] + ix0
        XY[ix0:ix1] = zip(x[0,x_ix],y[y_ix,0])
        ix0 = ix1
    # Remove positions outside of max_pipette_xovershoot
    if max_pipette_xovershoot > 0:
        XY = XY[XY['X'] <= max_pipette_xovershoot]
    elif max_pipette_xovershoot < 0:
        XY = XY[XY['X'] >= max_pipette_xovershoot]

    for x,y in XY:
        c = Circle((x,y), stm_r, ec=prestm_col, ls='dotted', fill=False)
        Circs.append(ax.add_patch(c)) 
    plt.title(ax.get_title()+r', $N_{'+str(int(round(stm_r*2)))+'}='+str(len(XY))+'$')
    plt.show()
    plt.draw()
    sleep(1e-3)
              
    return XY, Circs
Exemplo n.º 9
0
def mapCloud(nest, time):
    """Creates a map of the domain, showing
    filled contours of the cloud water
    """
    nc = openWRF(nest)
    _Nx, _Ny, _Nz, longitude, latitude, _dx, _dy, _x, _y = getDimensions(nc)

    m = _getMapForNC(nc, False, _getDL(nest), 100)
    x, y = m(longitude, latitude)

    qcloud = 1000.0 * np.sum(nc.variables["QCLOUD"][time, :, :, :], axis=0)
    plt.contourf(x, y, qcloud, cmap=cmap_red)
    plt.colorbar()
    plt.show()
    plt.close()
Exemplo n.º 10
0
def mapCloud(nest, time):
    """Creates a map of the domain, showing
    filled contours of the cloud water
    """
    nc = openWRF(nest)
    _Nx, _Ny, _Nz, longitude, latitude, _dx, _dy, _x, _y = getDimensions(nc)

    m = _getMapForNC(nc, False, _getDL(nest), 100)
    x, y = m(longitude, latitude)

    qcloud = 1000.0 * np.sum(nc.variables['QCLOUD'][time, :, :, :], axis=0)
    plt.contourf(x, y, qcloud, cmap=cmap_red)
    plt.colorbar()
    plt.show()
    plt.close()
Exemplo n.º 11
0
def mapTerrain(nest, includePMSL=False, includeTemp=False):
    """Creates a map of the domain, showing
    filled contours of the terrain
    """
    nc = openWRF(nest)
    met = openWPS(nest)
    nc1 = openWRF(nest + 1)
    _Nx, _Ny, _Nz, longitude, latitude, _dx, _dy, _x, _y = getDimensions(nc)

    m = _getMapForNC(nc, False, _getDL(nest), 100)
    x, y = m(longitude, latitude)
    _makeDots(m)

    if (includeTemp and met is not None):
        ST = met.variables['TT'][0][0, :, :]
        cs = plt.contour(x,
                         y,
                         ST - T_zero,
                         arange(-48, 50, 2.),
                         colors='blue',
                         linestyles='solid')
        plt.clabel(cs, inline=1, fmt='%1.0f', fontsize=12)
    if (includePMSL and met is not None):
        levels = arange(960., 1040., 1.)
        PMSL = met.variables['PMSL'][0]
        cs = plt.contour(x,
                         y,
                         PMSL / 100.,
                         levels,
                         colors='black',
                         label='Pressure')
        plt.clabel(cs, inline=1, fmt='%1.0f', fontsize=11)

    heightground = (nc.variables['PH'][0][0, :, :] +
                    nc.variables['PHB'][0][0, :, :]) / g
    plt.contourf(x,
                 y,
                 heightground,
                 levels=arange(0, max_h, 100),
                 cmap=cmap_grey,
                 extend='max')
    plt.colorbar()
    if (nc1 is not None):
        _plotBorder(nc1, m, 'black')
    plt.show()
    plt.close()
Exemplo n.º 12
0
def xzCloudPlot(nest,time,plotTemp=True,plotRH=False):
    nc = openWRF(nest)
    Nx,Ny,Nz,longitude,_lats,_dx,_dy,x_nr,y_nr = getDimensions(nc)
    
    heightground_x,heighthalf_xz = _getHeight(nc, time, Nx, -1, Nz, -1, y_nr)    
    print 'Model height: ' + str(heightground_x[x_nr])

    theta = nc.variables['T'][time,:,y_nr,:] + T_base 
    P = nc.variables['P'][time,:,y_nr,:] + nc.variables['PB'][time,:,y_nr,:] 
    T = theta*(P/P_bot)**kappa # Temperatur i halvflatene (Kelvin)
    rho = P/(R*T) #[kg/m3]

    qcloud_xz = 1000.0*nc.variables['QCLOUD'][time,:,y_nr,:]*rho # regner om til g/m3
    qrain_xz = 1000.0*nc.variables['QRAIN'][time,:,y_nr,:]*rho 
    qsnow_xz = 1000.0*nc.variables['QSNOW'][time,:,y_nr,:]*rho 
   
    plt.figure()
    plt.set_cmap(cmap_red)
    plt.axis([0,Nx-1,0.0,z_max])
    print u'Cloud water red, snow blue, rain green ($g/m^3$)'
    grid = np.reshape(np.tile(arange(Nx),Nz),(Nz,-1))
    plt.contourf(grid, heighthalf_xz, qcloud_xz, alpha=0.9,levels=xz_cloudwater_levels, cmap=cmap_red)#
    plt.colorbar()
    plt.contourf(grid, heighthalf_xz, qrain_xz, alpha=0.6,levels=xz_rain_levels, cmap=cmap_green)#
    plt.colorbar()
    plt.contourf(grid, heighthalf_xz, qsnow_xz, alpha=0.6,levels=xz_snow_levels,cmap=cmap_blue)# 
    plt.colorbar()

    if plotTemp:
        temp_int = arange(-80.0,50.0,2.0)
        cs = plt.contour(grid, heighthalf_xz, T-T_zero, temp_int,colors='black',linestyles='solid')#linewidths=4
        plt.clabel(cs, inline=1,  fmt='%1.0f', fontsize=12,colors='black')
    if plotRH:
        rh = _getRH(nc,time,-1,y_nr,T,P)
        rh_int = arange(90.,111.,5.)
        cs = plt.contour(grid, heighthalf_xz,rh , rh_int, colors='grey')
        plt.clabel(cs, inline=1,  fmt='%1.0f', fontsize=12, colors='grey')
    plt.plot(arange(Nx),heightground_x,color='black')
    plt.fill_between(arange(Nx),heightground_x,0,facecolor='lightgrey')
    plt.xticks(np.arange(0,Nx,8),np.round(longitude[Ny/2,::8], 1), fontsize='small')
    plt.yticks(np.arange(0,z_max,dz), fontsize='small')
    plt.xlabel('Lengdegrad')
    plt.ylabel(u'Høyde [m]')
    plt.show()
    plt.close()        
Exemplo n.º 13
0
def plot_conv_weights(weights, input_channel=0):
    # Get the lowest and highest values for the weights.
    # This is used to correct the colour intensity across
    # the images so they can be compared with each other.
    import numpy as np
    import math
    import matplotlib, pyplot as plt

    w_min = np.min(weights)
    w_max = np.max(weights)

    # Number of filters used in the conv. layer.
    num_filters = weights.shape[3]

    # Number of grids to plot.
    # Rounded-up, square-root of the number of filters.
    num_grids = math.ceil(math.sqrt(num_filters))

    # Create figure with a grid of sub-plots.
    fig, axes = plt.subplots(num_grids, num_grids)

    # Plot all the filter-weights.
    for i, ax in enumerate(axes.flat):
        # Only plot the valid filter-weights.
        if i < num_filters:
            # Get the weights for the i'th filter of the input channel.
            # See new_conv_layer() for details on the format
            # of this 4-dim tensor.
            img = weights[:, :, input_channel, i]

            # Plot image.
            ax.imshow(img,
                      vmin=w_min,
                      vmax=w_max,
                      interpolation='nearest',
                      cmap='seismic')

        # Remove ticks from the plot.
        ax.set_xticks([])
        ax.set_yticks([])

    # Ensure the plot is shown correctly with multiple plots
    # in a single Notebook cell.
    plt.show()
Exemplo n.º 14
0
def mapWind(nest, time):
    """Creates a map of the domain, showing
    wind barbs for the given time
    """
    nc = openWRF(nest)
    nc1 = openWRF(nest + 1)
    Nx, Ny, _Nz, longitude, latitude, _dx, _dy, _x, _y = getDimensions(nc)
    m = _getMapForNC(nc, False, _getDL(nest), 100)
    _makeDots(m)
    u10 = nc.variables['U10'][time, :, :]
    v10 = nc.variables['V10'][time, :, :]
    # Use data from every 10th grid point
    windx = 1 + Nx / 10
    windy = 1 + Ny / 10
    lat10 = np.zeros((windy, windx))
    lon10 = np.zeros((windy, windx))
    uwind = np.zeros((windy, windx))
    vwind = np.zeros((windy, windx))
    for j in range(windy):
        for i in range(windx):
            uwind[j, i] = 0.5 * (u10[j * 10, i * 10] + u10[j * 10, i * 10 + 1])
            #print 'u: ' + str(uwind[j,i])
            vwind[j, i] = 0.5 * (v10[j * 10, i * 10] + v10[j * 10 + 1, i * 10])
            #print 'v: ' + str(vwind[j,i])
            lat10[j, i] = latitude[j * 10, i * 10]
            lon10[j, i] = longitude[j * 10, i * 10]

    x10, y10 = m(lon10, lat10)
    plt.barbs(x10,
              y10,
              uwind,
              vwind,
              barb_increments=barb_increments,
              linewidth=1.0,
              color='green')

    if (nc1 is not None):
        _plotBorder(nc1, m, 'black')
    plt.show()
    plt.close()
Exemplo n.º 15
0
def skewTPlot(nest, time):
    """
     This is the method to use from the outside
     
     nest: The nesting level of the nc-file from WRF 
     time: The time for which to plot
    """
    nc = openWRF(nest)
    _Nx, _Ny, _Nz, _longs, _lats, _dx, _dy, x, y = getDimensions(nc)

    plt.figure()
    _isotherms()
    _isobars()
    _dry_adiabats()
    _moist_adiabats()

    P = nc.variables['P'][time, :, y, x] + nc.variables['PB'][time, :, y, x]

    _windbarbs(nc, time, y, x, P)
    _temperature(nc, time, y, x, P)
    _dewpoint(nc, time, y, x, P)

    plt.axis([-40, 50, P_b, P_t])
    plt.xlabel('Temperatur ($^{\circ}\! C$) ved 1000hPa')
    xticks = np.arange(-40, 51, 5)
    plt.xticks(xticks,
               ['' if tick % 10 != 0 else str(tick) for tick in xticks])
    plt.ylabel('Trykk (hPa)')
    yticks = np.arange(P_bot, P_t - 1, -10**4)
    plt.yticks(yticks, yticks / 100)

    sfcT = nc.variables['T2'][time, y, x] - T_zero
    sfcP = nc.variables['PSFC'][time, y, x]
    sfcW = nc.variables['Q2'][time, y, x]
    sfcTd = td(e(sfcW, sfcP))
    plt.suptitle('Bakketemp: %4.1f$^{\circ}\! C$  Duggpunkt: %3.1f$^{\circ}\! C$  Trykk: %5.1f hPa' % (sfcT,sfcTd,0.01*sfcP), \
                 fontsize=10, x = 0.5, y = 0.03)

    plt.show()
    plt.close()
Exemplo n.º 16
0
def skewTPlot(nest,time):   
    """
     This is the method to use from the outside
     
     nest: The nesting level of the nc-file from WRF 
     time: The time for which to plot
    """  
    nc = openWRF(nest)
    _Nx,_Ny,_Nz,_longs,_lats,_dx,_dy,x,y = getDimensions(nc)

    plt.figure()
    _isotherms()
    _isobars()
    _dry_adiabats()
    _moist_adiabats()

    P = nc.variables['P'][time,:,y,x] + nc.variables['PB'][time,:,y,x] 
    
    _windbarbs(nc,time,y,x,P)
    _temperature(nc,time,y,x,P)
    _dewpoint(nc,time,y,x,P)
    
    plt.axis([-40,50,P_b,P_t])
    plt.xlabel('Temperatur ($^{\circ}\! C$) ved 1000hPa')
    xticks = np.arange(-40,51,5)
    plt.xticks(xticks,['' if tick%10!=0 else str(tick) for tick in xticks])
    plt.ylabel('Trykk (hPa)')
    yticks = np.arange(P_bot,P_t-1,-10**4)
    plt.yticks(yticks,yticks/100)

    sfcT = nc.variables['T2'][time,y,x]-T_zero
    sfcP = nc.variables['PSFC'][time,y,x]
    sfcW = nc.variables['Q2'][time,y,x]
    sfcTd = td(e(sfcW,sfcP))
    plt.suptitle('Bakketemp: %4.1f$^{\circ}\! C$  Duggpunkt: %3.1f$^{\circ}\! C$  Trykk: %5.1f hPa' % (sfcT,sfcTd,0.01*sfcP), \
                 fontsize=10, x = 0.5, y = 0.03)        

    plt.show()
    plt.close()
Exemplo n.º 17
0
bone()
pcolor(som.distance_map().T)
colorbar()
marker = ['o', 's']
color = ['r', 'g']
for i, x in enumerate(X):
    w = som.winner(X)
    plot(w[0] + 0.5,
         w[1] + 0.5,
         markers[y[i]],
         markeredgecolor=colors[y[i]],
         markerfacecolor=None,
         markersize=10,
         markeredgewidth=2)

show()

#Finding the fraud
mappings = som.win_map(X)
frauds = np.concatenate((mappings[(8, 1)], mappings[(6, 8)]), axis=0)
frauds = sc.inverse_transform(frauds)

#part- 2 Going from Unsupervised to supervised  Deep Learning
#Creating the matrix of feature
customer = dataset.iloc[:, 1:].values
#Creating the dependent variable
is_fraud = np.zeros(len(dataset))
for i in range(len(dataset)):
    if dataset.iloc[i, 0] in frauds:
        is_fraud[i] = 1
Exemplo n.º 18
0
def tzCloudPlot(nest, plotMetar=False, offset=0):
    nc = openWRF(nest)
    Nx, Ny, Nz, _longs, _lats, _dx, _dy, x_nr, y_nr = getDimensions(nc)

    heightground_t, heighthalf_tz = _getHeight(nc, Nx, Ny, Nz, x_nr, y_nr)

    T_tz = np.zeros((Nz, Nt))
    qcloud_tz = np.zeros((Nz, Nt))
    qice_tz = np.zeros((Nz, Nt))
    qsnow_tz = np.zeros((Nz, Nt))
    qrain_tz = np.zeros((Nz, Nt))

    for t in arange(Nt):
        theta = nc.variables['T'][t, :, y_nr, x_nr] + T_base
        P = nc.variables['P'][t, :, y_nr,
                              x_nr] + nc.variables['PB'][t, :, y_nr, x_nr]
        T_tz[:,
             t] = theta * (P /
                           P_bot)**kappa  # Temperatur i halvflatene (Kelvin)
        rho = P[:] / (R * T_tz[:, t])  # regner om til g/m3
        qcloud_tz[:,
                  t] = 1000.0 * nc.variables['QCLOUD'][t, :, y_nr, x_nr] * rho
        qice_tz[:, t] = 1000.0 * nc.variables['QICE'][t, :, y_nr, x_nr] * rho
        qsnow_tz[:, t] = 1000.0 * nc.variables['QSNOW'][t, :, y_nr, x_nr] * rho
        qrain_tz[:, t] = 1000.0 * nc.variables['QRAIN'][t, :, y_nr, x_nr] * rho

    for s in [u'Snø', 'Regn']:
        plt.figure()
        plt.axis([-offset, Nt - 1, 0.0, z_max])
        grid = np.reshape(np.tile(arange(Nt), Nz), (Nz, -1))
        if (s == u"Snø"):
            var = qsnow_tz
            cm = cmap_blue
            levs = tz_snow_levels
        else:
            var = qrain_tz
            cm = cmap_green
            levs = tz_rain_levels
        plt.contourf(grid,
                     heighthalf_tz,
                     qcloud_tz,
                     alpha=0.9,
                     levels=tz_cloudwater_levels,
                     cmap=cmap_red)  #
        plt.colorbar()
        plt.contourf(grid, heighthalf_tz, var, alpha=0.6, levels=levs,
                     cmap=cm)  #
        plt.colorbar()
        cs = plt.contour(grid,
                         heighthalf_tz,
                         T_tz - T_zero,
                         temp_int,
                         colors='black',
                         linestyles='solid')
        plt.clabel(cs, inline=1, fmt='%1.0f', fontsize=12, colors='black')
        plt.fill_between(arange(-offset, Nt),
                         heightground_t[0],
                         0,
                         facecolor='lightgrey')
        if plotMetar:
            _metar()
        print s + ' ($g/m^3$)'
        plt.xlabel('Timer etter ' + date + 'T00:00Z')
        plt.ylabel(u'Høyde [m]')
        plt.yticks(np.arange(0, z_max, dz), fontsize='small')
        plt.show()
        plt.close()

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.set_xlim(0, Nt - 1)
    ax1.plot(np.sum(qcloud_tz, axis=0), color='black', label=u"skyvann")
    ax1.plot(np.sum(qsnow_tz, axis=0), color='green', label=u"snø")
    ax1.set_xlabel('Timer etter ' + date + 'T00:00Z')
    ax1.set_ylabel(u'Skyvann og snø ($g/m^2$)')
    ax2 = ax1.twinx()
    ax2.plot(np.sum(qice_tz, axis=0), color='blue', label="is")
    ax2.plot(np.sum(qrain_tz, axis=0), color='red', label="regn")
    ax2.set_ylabel('Regn og is ($g/m^2$)')
    ax1.set_xlim(0, Nt - 1)
    ax1.legend(loc='upper left')
    ax2.legend(loc='upper right')
    plt.show()
    plt.close()
Exemplo n.º 19
0
def yzCloudPlot(nest, time, plotTemp=True, plotRH=False):
    nc = openWRF(nest)
    Nx, Ny, Nz, _longs, latitude, _dx, _dy, x_nr, y_nr = getDimensions(nc)

    heightground_y, heighthalf_yz = _getHeight(nc, time, -1, Ny, Nz, x_nr, -1)
    print 'Model height: ' + str(heightground_y[y_nr])

    theta = nc.variables['T'][time, :, :, x_nr] + T_base
    P = nc.variables['P'][time, :, :, x_nr] + nc.variables['PB'][time, :, :,
                                                                 x_nr]
    T = theta * (P / P_bot)**kappa  # Temperatur i halvflatene (Kelvin)
    rho = P / (R * T)  #[kg/m3]

    qcloud_yz = 1000.0 * nc.variables['QCLOUD'][
        time, :, :, x_nr] * rho  # regner om til g/m3
    qrain_yz = 1000.0 * nc.variables['QRAIN'][time, :, :, x_nr] * rho
    qsnow_yz = 1000.0 * nc.variables['QSNOW'][time, :, :, x_nr] * rho

    plt.figure()
    plt.set_cmap(cmap_red)
    plt.axis([0, Ny - 1, 0.0, z_max])
    print u'Cloud water red, snow blue, rain green ($g/m^3$)'
    grid = np.reshape(np.tile(arange(Ny), Nz), (Nz, -1))
    plt.contourf(grid,
                 heighthalf_yz,
                 qcloud_yz,
                 alpha=0.9,
                 levels=xz_cloudwater_levels,
                 cmap=cmap_red)  #
    plt.colorbar()
    plt.contourf(grid,
                 heighthalf_yz,
                 qrain_yz,
                 alpha=0.6,
                 levels=xz_rain_levels,
                 cmap=cmap_green)  #
    plt.colorbar()
    plt.contourf(grid,
                 heighthalf_yz,
                 qsnow_yz,
                 alpha=0.6,
                 levels=xz_snow_levels,
                 cmap=cmap_blue)  #
    plt.colorbar()

    if plotTemp:
        cs = plt.contour(grid,
                         heighthalf_yz,
                         T - T_zero,
                         temp_int,
                         colors='black',
                         linestyles='solid')  #linewidths=4
        plt.clabel(cs, inline=1, fmt='%1.0f', fontsize=12, colors='black')
    if plotRH:
        rh = _getRH(nc, time, x_nr, -1, T, P)
        rh_int = arange(90., 111., 5.)
        cs = plt.contour(grid, heighthalf_yz, rh, rh_int, colors='grey')
        plt.clabel(cs, inline=1, fmt='%1.0f', fontsize=12, colors='grey')
    plt.plot(arange(Ny), heightground_y, color='black')
    plt.fill_between(arange(Ny), heightground_y, 0, facecolor='lightgrey')
    plt.xticks(np.arange(0, Ny, 8),
               np.round(latitude[::8, Nx / 2], 1),
               fontsize='small')
    plt.yticks(np.arange(0, z_max, dz), fontsize='small')
    plt.xlabel('Breddegrad')
    plt.ylabel(u'Høyde [m]')
    plt.show()
    plt.close()
Exemplo n.º 20
0
 def figshow():
     """`pyplot.show` to make a plotted figure show up"""
     # is_interactive = matplotlib.is_interactive()
     import pyplot  # like this it doesn't show up in the interface
     pyplot.ion()
     pyplot.show()
Exemplo n.º 21
0
def get_scanpos_given_4_sides(stm_r,
                              corners,
                              ax=None,
                              max_pipette_xovershoot=300.):
    """
    """
    # If no axes was set, plot on the currently active.
    if ax is None:
        ax = plt.gca()
        
    step_len = np.floor(np.sqrt(2*stm_r**2))
    flk = step_len/2.0

    lo_l, up_l = corners["lo_left"], corners["up_left"]
    lo_r, up_r = corners["lo_right"], corners["up_right"]
    
    # Clean out x and ys outside outer border of ROI.
    lbord_m = (lo_l[1] - up_l[1]) / (lo_l[0] - up_l[0])
    lbord_b = lo_l[1] - lbord_m*lo_l[0]
    rbord_m = (lo_r[1] - up_r[1]) / (lo_r[0] - up_r[0])
    rbord_b = lo_r[1] - rbord_m*lo_r[0]
    upbord_m = (up_l[1] - up_r[1]) / (up_l[0] - up_r[0])
    upbord_b = up_l[1] - upbord_m*up_l[0]
    lobord_m = (lo_l[1] - lo_r[1]) / (lo_l[0] - lo_r[0])
    lobord_b = lo_l[1] - lobord_m*lo_l[0]
        
    lbord = lambda x, y: x > (y - lbord_b) / lbord_m - flk
    rbord = lambda x, y: x < (y - rbord_b) / rbord_m + flk
    lobord = lambda x, y: y > lobord_m*x + lobord_b - flk
    upbord = lambda x, y: y < upbord_m*x + upbord_b + flk
    
    X_tmp = np.arange(min(lo_l[0],up_l[0]),
                      max(lo_r[0]+100,up_r[0]+100),
                      step_len)
    Y_tmp = np.arange(min(lo_l[1],lo_r[1]),
                      max(up_l[1]+100,up_r[1]+100),
                      step_len)
    # Remove positions outside of max_pipette_xovershoot
    if max_pipette_xovershoot > 0:
        X_tmp = X_tmp[X_tmp <= max_pipette_xovershoot]
    elif max_pipette_xovershoot < 0:
        X_tmp = X_tmp[X_tmp >= max_pipette_xovershoot]

    X,Y = [],[]
    Circs = [];pos_num = 0
    for x in X_tmp:
        for y in Y_tmp:
            if lbord(x,y) and rbord(x,y) and lobord(x,y) and upbord(x,y) :
                c = Circle((x, y), stm_r,ec=prestm_col,
                           ls='dotted', fill=False)
                Circs.append(ax.add_patch(c))
                X.append(x)
                Y.append(y)
                plt.text(x, y, str(pos_num))
                pos_num += 1
    nstmloc = len(X)
    title(r'Stm pos: $N_{'+str(int(round(stm_r*2)))+'}='+str(nstmloc)+'$')
    plt.show()
    plt.draw()
    sleep(1e-3)
    XY = np.recarray(len(X), dtype=[('X',float),('Y',float)])
    XY['X'], XY['Y'] = X, Y
    
    return XY, Circs
Exemplo n.º 22
0
import numpy as np
import pyplot as pl
from scipy import interpolate
from scipy import integrate

file = np.loadtxt('podaci.txt')
L = file[:,0]
I = file[:,1]

spl = interpolate.splrep(L,I,k=3)
Lk = file[:,0]
Ik = spl(xs)
pl.plot(xs, ys)
pl.show()
Exemplo n.º 23
0
from sklearn.linear_model import LinearRegression  #scikit-learn(sklearn)에 선형회귀 라이브러리가 포함되어 있어서 사용한다.

line_fitter = LinearRegression()

# fit()함수의 기능
# line_fitter.coef_ : 기울기를 저장한다. (coef : 기울기)
# line_fitter.intercept_ : 절편을 저장 (intercept : 절편)

line_fitter.fit(height, math)  #height와 math관의 상관관계를 구한다.

score_predict = line_fitter.predict(
    height)  ##height와 math관의 상관관계를 구하는 선형회귀선을 그린다. (score_predict : 점수 예측)

plt.plot(height, math, 'x')  #x는 height에 따른 math이다. (그래프에 나타내는 표시를 x로 한다.)
plt.plot(height, score_predict)
plt.show()  #데이터들을 나타낸 선형회귀선과 height에 따른 math을 나타내는 x를 출력한다.

#위에서 구현한 그래프에 기울기와 절편을 표현해보자.

line_fitter.coef_  #기울기 구하기

line_fitter.intercept_  #절편 구하기

#MSE를 이용해서 성능평가 진행 (성능평가를 위해서 mse를 import한다.)
from sklearn.metrics import mean_squared_error

print("Mean_Squared_Error(Mse) :", mean_squared_error(score_predict,
                                                      math))  #mse값을 구한다.

#RMSE를 이용해서 성능평가 진행(RMSE는 MSE에 루트값을 씌우면 된다.)
print("RMSE : ",
Exemplo n.º 24
0
8/15: plt.bar
8/16: from matplotlib import pyplot as plt
8/17: pmf
8/18: pm
8/19: pm(a,lambda_[0])
8/20: poi.pmf(a,lambda_[0])
8/21: poi.pmf(a,lambda_[0])
8/22: plt.bar(a,poi.pmf(a,lambda_[0]),color=colors[0],lable="$\lambda = %.1f$" % lambda_[0],alpha=0.60,edgecolor=colors[0],lw="3")
8/23: plt.bar(a,poi.pmf(a,lambda_[0]),color=colors[0],label="$\lambda = %.1f$" % lambda_[0],alpha=0.60,edgecolor=colors[0],lw="3")
8/24: plt.bar(a,poi.pmf(a,lambda_[1]),color=colors[1],label="$\lambda = %.1f$" % lambda_[1],alpha=0.60,edgecolor=colors[1],lw="3")
8/25: plt.xticks( a + 0.4,a)
8/26: plt.legend()
8/27: plt.ylabel("Probability of $k$")
8/28: plt.xlabel("$k$")
8/29: plt.title("Probability mass funciton of a Poisson random \$\lambda$ values")
8/30: plt.show()
 9/1: from pymc import DiscreteUniform, Exponential, deterministic, Poisson, Uniform
 9/2: import numpy as np
 9/3:
disasters_array =   \
     np.array([ 4, 5, 4, 0, 1, 4, 3, 4, 0, 6, 3, 3, 4, 0, 2, 6,
                   3, 3, 5, 4, 5, 3, 1, 4, 4, 1, 5, 5, 3, 4, 2, 5,
                   2, 2, 3, 4, 2, 1, 3, 2, 2, 1, 1, 1, 1, 3, 0, 0,
                   1, 0, 1, 1, 0, 0, 3, 1, 0, 3, 2, 2, 0, 1, 1, 1,
                   0, 1, 0, 1, 0, 0, 0, 2, 1, 0, 0, 0, 1, 1, 0, 2,
                   3, 3, 1, 1, 2, 1, 1, 1, 1, 2, 4, 2, 0, 0, 1, 4,
                   0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1])
 9/4: switchPoint = DiscreteUniform('switchpoint', lower=0, upper=110, doc='Switchpoint[year]')
 9/5: early_mean = Exponential('early_mean', beta=1.)
 9/6: late_mean = Exponential('late_mean', beta=1.)
 9/7:
#
#            indien mathplotlib nog niet geinstalleerd is run:
#            pip install mathplotlib
#
#            Nadat een grafiek wordt gelsoten wordt de volgende getoond.
#
import pyplot as plt

# Voorbeeld1: 1 grafieken in een afbeelding
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.title('Titel van de grafiek voorbeeld1')
plt.ylabel('Y-as')
plt.xlabel('X-as')
plt.show()


# Voorbeeld2: 2 grafieken in een afbeelding
#from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
x1 = [0,1,2,3,4,5]
y1 = [0,1,4,9,16,25]
x2 = x1
y2 = [5,7,9,11,13,15]
# can plot specifically, after just showing the defaults:
plt.plot(x1,y1,linewidth=5, label='$f1(x)=x^2$', color='red')     # label maken gebruik van Latex express
plt.plot(x2,y2,linewidth=5, label='$f2(x)=2x+5$', color='green')  # label maken gebruik van Latex express
plt.title('Titel van de grafiek voorbeeld2')
plt.ylabel('Y-as')
Exemplo n.º 26
0
# coding: utf-8
import numerical1 as num
from defns import *
def anal(t, g):
    x=np.exp(-g/2. t)*np.cos(np.sqrt(4-g**2)/2. t)
    p=np.exp(-g/2. t)*np.sin(np.sqrt(4-g**2)/2. t)
    return x,p
def anal(t, g):
    x=np.exp(-g/2.*t)*np.cos(np.sqrt(4-g**2)/2.*t)
    p=np.exp(-g/2.*t)*np.sin(np.sqrt(4-g**2)/2.*t)
    return x,p
get_ipython().set_next_input(u't=np.arange');get_ipython().magic(u'pinfo np.arange')
t=np.arange(0., 100., 0.5)
x,p=anl(t, g) 
x,p=anal(t, g)
x
import pyplot as plt
import matplotlib.pyplot as plt
plt.figure()
plt.plot(t, x, t, p)
plt.show()
get_ipython().magic(u'save "commands.py"')