Exemple #1
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()
Exemple #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)
Exemple #3
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()        
Exemple #4
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()
Exemple #5
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()
Exemple #6
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()
Exemple #7
0
def from_file_home_outside_calls(): 
    
    file1 = "/home/sscepano/D4D res/ORGANIZED/SET3/Clustering/usr res/usr_home_calls.tsv"
    file2 = "/home/sscepano/D4D res/ORGANIZED/SET3/Clustering/usr res/usr_outside_calls.tsv"
   
    usr_home_c = n.zeros(500001)
    usr_outside_c = n.zeros(500001)

    i = 0
    f1 = open(file1, 'r')    
    f2 = open(file2, 'r') 
    
    
    # read the file1
    for line in f1:
        i = i + 1
        u, home_c = line.split('\t')
        home_c = float(home_c)
        u = int(u)
        usr_home_c[u] = home_c
        
            # read the file
    for line in f2:
        i = i + 1
        u, outside_c = line.split('\t')
        outside_c = float(outside_c)
        u = int(u)
        usr_outside_c[u] = outside_c

############################################################################################################################
# THIS is to plot pdf of home calls
############################################################################################################################

    fig1 = plt.figure(1)
    ax = fig1.add_subplot(211)
    nn, bins, rectangles = ax.hist(usr_home_c, 100, normed=True)

    #plt.plot(nc_distr_pct, 'ro', linewidth=0.5, label= 'pdf Num of calls')
    
    plt.xlabel('NcH, number of calls from the home subprefecture')
    plt.ylabel('P(NcH)')
    plt.legend()   
    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
    plt.yscale('log')
    plt.xscale('log')
#    figure_name = "/home/sscepano/D4D res/allstuff/rg/pdf rg loglog.png"
    
    #this is a regular plot file, then comment the previous loglog block
    #figure_name = "/home/sscepano/D4D res/allstuff/rg/pdf home calls.png"
      
    #print(figure_name)
    #plt.savefig(figure_name, format = "png")        
    
############################################################################################################################
# THIS is to plot pdf of outside calls
############################################################################################################################

    #fig1 = plt.figure(1)
    ax = fig1.add_subplot(212)
    nn, bins, rectangles = ax.hist(usr_outside_c, 100, normed=True)

    #plt.plot(nc_distr_pct, 'ro', linewidth=0.5, label= 'pdf Num of calls')
    
    plt.xlabel('NcO, number of calls from outside the home subprefecture')
    plt.ylabel('P(NcO)')
    plt.legend()   
    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
    plt.yscale('log')
    plt.xscale('log')
    figure_name = "/home/sscepano/D4D res/allstuff/rg/pdf home outside calls.png"
    
#    #this is a regular plot file, then comment the previous loglog block
#    figure_name = "/home/sscepano/D4D res/allstuff/rg/pdf home outside calls.png"
      
    print(figure_name)
    plt.savefig(figure_name, format = "png")        
    
    return   

# invoke the function for plotting number of calls and frequency probability distribution (percents of users)
#from_file_home_outside_calls()
Exemple #8
0
def from_fq_files_hist_pdf(): 
    
    file_name= "/home/sscepano/D4D res/ORGANIZED/SET3/Distr of Num and Fq of Calls/new results -- check the same/Users_and_their_total_calls_number.tsv"
    file_name2 = "/home/sscepano/D4D res/ORGANIZED/SET3/Distr of Num and Fq of Calls/new results -- check the same/Users_and_their_calling_fq.tsv"
   
    # here we store the num of calls made by a user
    usr_and_his_num_calls = n.zeros(500001, dtype=n.int)

    nc_distr = n.zeros(max_num_calls, dtype=n.int)

    # a loop where we populate those two arrays from the file
    i = 0
    f = open(file_name, 'r')    
    # read the file
    for line in f:
        i = i + 1
        u, nc = line.split('\t')
        nc = int(nc)
        u = int(u)
        usr_and_his_num_calls[u] = nc
        nc_distr[nc] += 1

    mi = min(usr_and_his_num_calls)
    mx = max(usr_and_his_num_calls)
    print("Minimum number of calls ", mi)
    print("Maximum number of calls ", mx)
    
    total_u = float(sum(nc_distr))
    print("Total users found ", total_u)
    


############################################################################################################################
# THIS is to plot number of users pdf
############################################################################################################################

#    fig1 = plt.figure(1)
#    ax = fig1.add_subplot(111)
#    nn, bins, rectangles = ax.hist(usr_and_his_num_calls, 100, normed=True)
#
#    plt.xlabel('N, num of calls')
#    plt.ylabel('P(N)')
#    plt.legend()   
#    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
#    plt.yscale('log')
#    plt.xscale('log')
#    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/hist of num of calls loglog.png" 
#    
##    #this is a regular plot file, then comment the previous loglog block
##    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/hist of num of calls.png"
#      
#    print(figure_name)
#    plt.savefig(figure_name, format = "png")
#    
#    plt.clf()       
    
###############################################################################################################################
# THIS is to plot fq pdf
###############################################################################################################################

    # here we store the num of calls made by a user
    usr_and_his_fq = n.zeros(500001)

    # a loop where we populate those two arrays from the file
    i = 0
    f2 = open(file_name2, 'r')    
    # read the file
    for line in f2:
        i = i + 1
        u, fq = line.split('\t')
        fq = float(fq)
        u = int(u)
        usr_and_his_fq[u] = fq

    mi = min(usr_and_his_fq)
    mx = max(usr_and_his_fq)
    print("Minimum fq of calls ", mi)
    print("Maximum fq of calls ", mx)
        
    fig2 = plt.figure(2)
    ax = fig2.add_subplot(111)
    nn, bins, rectangles = ax.hist(usr_and_his_fq, 100, normed=True)
    
    plt.xlabel('fq of calls')
    plt.ylabel('P(fq)')
    plt.legend()   
    
    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/hist of fq of calls.png" 
    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
#    plt.yscale('log')
#    plt.xscale('log')
#    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/hist of fq of calls loglog.png" 
      
    print(figure_name)
    plt.savefig(figure_name, format = "png")   
    

    return   
Exemple #9
0
def from_file_num_calls(file_name): 
   
    # here we store the num of calls made by a user
    usr_and_his_num_calls = n.zeros(500001, dtype=n.int)
    # here we store the fq of calls made by a user, but we calculate it from the num_calls
    fq_distr = n.zeros(max_num_calls)
    # from the previous array obtained by counting users who made the same total number of calls
    nc_distr = n.zeros(max_num_calls, dtype=n.int)
    # here we just save percents of users
    nc_distr_pct = n.zeros(max_num_calls)
    
    
    # a loop where we populate those two arrays from the file
    i = 0
    f = open(file_name, 'r')    
    # read the file
    for line in f:
        i = i + 1
        u, nc = line.split('\t')
        nc = int(nc)
        u = int(u)
        usr_and_his_num_calls[u] = nc
        nc_distr[nc] += 1

    mi = min(usr_and_his_num_calls)
    mx = max(usr_and_his_num_calls)
    print("Minimum number of calls ", mi)
    print("Maximum number of calls ", mx)
    
    total_u = float(sum(nc_distr))
    print("Total users found ", total_u)
    
#   test_file_out = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/Obtained_num_calls_and_its_pct.tsv"
#   fto =  open(test_file_out,"w")
    for j in range(0, max_num_calls):
        nc_distr_pct[j] = (nc_distr[j] / total_u)
#        fto.write(str(j) + '\t' + str(nc_distr_pct[j]) + '\n')

#    # I was just checking that the total percents sums up to 100 and they do but it looked funny as we have so small values
#    total = 0    
#    for i in range (max_num_calls):
#        total += percent_users[i]
#    print ("Check ", total)

############################################################################################################################
# THIS is to plot number of users pdf
############################################################################################################################

    plt.figure(1)

    plt.plot(nc_distr_pct, 'r', linewidth=0.5, label= 'distribution of N')
    
    plt.xlabel('N, num of calls')
    plt.ylabel('% Users')
    plt.legend()   
    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
    plt.yscale('log')
    plt.xscale('log')
#    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/SET3 distr of num of calls loglog.png" 
    
    #this is a regular plot file, then comment the previous loglog block
    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/distr of num of calls2.png"
      
    print(figure_name)
    plt.savefig(figure_name, format = "png", pdi=300) 
    #plt.show()       
    
###############################################################################################################################
# THIS is to plot fq pdf
###############################################################################################################################

    plt.figure(2)
    
#    fq = []
#    
#    for j in range(max_num_calls):
#        fq.append( float(j / 3360.0))
#
#    ffq = []
#    
#    for j in range(max_num_calls):
#        ffq.append(nc_distr_pct[j])

#    for j in range(0, max_num_calls):
#        nc_distr_pct[j] = (nc_distr[j] / total_u)

    fq = []
    
    for j in range(max_num_calls):
        fq.append( float(j / 3360.0))

    ffq = []
    
    for j in range(max_num_calls):
        ffq.append(nc_distr_pct[j])
        
   
#    test_file_out2 = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/Calculated_fq_calls_and_its_pct2.tsv"
#    fto2 =  open(test_file_out2,"w")
#    for j in range(0, max_num_calls):
#        fto2.write(str(fq[j]) + '\t' + str(ffq[j]) + '\n')    


    # Finally understood here -- when I give two arrays: x, y (at least append values IN ORDER like here) -- pyplot will plot y versus x
    plt.plot(fq, ffq, 'g', linewidth=0.3, label= 'distribution of Fq')
    
    plt.xlabel('Fq of calls')
    plt.ylabel('% Users')
    plt.legend()   
    
    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
    plt.yscale('log')
    plt.xscale('log')
    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/distr of fq of calls2.png" 
    
#    # this is a regular plot file, then comment the previous loglog block
#    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/SET3 distr of fq of calls.png"
      
    print(figure_name)
    plt.savefig(figure_name, format = "png")   
    

    return   
Exemple #10
0
def save_to_plot(avg_usr_traj):
    
    nits = []
    its = []
    
    # a loop where we populate those two arrays from the file
    i = 0
#    f = open(file_name, 'r')    
#    # read the file
    for usr in range(500001):
        i = i + 1
        nits.append(int(avg_usr_traj[usr]))
        its.append(usr)

    mi = min(nits)
    mx = max(nits)
    print("Minimum radius of gyr ", mi)
    print("Maximum radius of gyr ", mx)
    
    total_nit = float(sum(nits))
    print("Total radius of gyr ", total_nit)
    
    pdf_nits = defaultdict(int)
    
    for j in range(0, len(nits)):
        pdf_nits[nits[j]] += 1
        
    ordered = OrderedDict(sorted(pdf_nits.items(), key=lambda t: t[0]))
    
    nits7s = []
    its7s = []
    
    test = 0
    
    for j in ordered.iterkeys():
        nits7s.append(ordered[j]/500000.0)
        test += ordered[j]/500000.0
        its7s.append(j)
        
    print test
        
############################################################################################################################
# THIS is to plot number of users pdf
############################################################################################################################

    plt.figure(7)

    plt.plot(its7s, nits7s, 'o', linewidth=0.5, label= 'distribution of Rg')
    
    plt.xlabel('rg [km]')
    plt.ylabel('P(rg)')
    plt.legend()   
    
    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
    plt.yscale('log')
    plt.xscale('log')
    figure_name = "/home/sscepano/D4D res/allstuff/traj/avg daily/avg_daily_traj_total.png"
          
    print(figure_name)
    plt.savefig(figure_name, format = "png", dpi=300)    
    
    return
Exemple #11
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"')
Exemple #12
0
def from_file_radius_gyr3(file_name, subpref):
    
    users_list = rd.read_in_subpref_users(subpref)
    
    total = float(rd.read_in_subpref_num_users()[subpref])
    
    if total > 0:
    
        nits = []
        its = []
        
        # a loop where we populate those two arrays from the file
        i = 0
        f = open(file_name, 'r')    
        # read the file
        for line in f:
            i = i + 1
            it, nit = line.split('\t')
            nit = float(nit)
            it = int(it)
            if users_list[it] == 1:
                nit = int(nit)
                nits.append(nit)
                its.append(it)
    
        mi = min(nits)
        mx = max(nits)
        print("Minimum radius of gyr ", mi)
        print("Maximum radius of gyr ", mx)
        
        total_nit = float(sum(nits))
        print("Total radius of gyr ", total_nit)
        
        pdf_nits = defaultdict(int)
        
        for j in range(0, len(nits)):
            pdf_nits[nits[j]] += 1
            
        ordered = OrderedDict(sorted(pdf_nits.items(), key=lambda t: t[0]))
        
        nits7s = []
        its7s = []
        
        test = 0
        #total = 500000.0
        
        for j in ordered.iterkeys():
            nits7s.append(ordered[j]/total)
            test += ordered[j]/total
            its7s.append(j)
            
        print test
            
    ############################################################################################################################
    # THIS is to plot number of users pdf
    ############################################################################################################################
    
        plt.figure(7)
    
        plt.plot(its7s, nits7s, 'o', linewidth=0.5, label= 'distribution of Rg')
        
        plt.xlabel('rg [km]')
        plt.ylabel('P(rg)')
        plt.legend()   
        
        # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
        plt.yscale('log')
        plt.xscale('log')
        figure_name = "/home/sscepano/D4D res/allstuff/rg/1/rg_" + str(subpref) + ".png"
              
        print(figure_name)
        plt.savefig(figure_name, format = "png", dpi=300)      
        
        plt.clf()
    
    return
Exemple #13
0
def from_file_radius_gyr(file_name): 
   
    usr_rg = nn.zeros(500001)
    # a loop where we populate those two arrays from the file
    i = 0
    f = open(file_name, 'r')    
    # read the file
    for line in f:
        i = i + 1
        u, rg = line.split('\t')
        rg = float(rg)
        u = int(u)
        usr_rg[u] = rg
       

    mi = min(usr_rg)
    mx = max(usr_rg)
    print("Minimum number of calls ", mi)
    print("Maximum number of calls ", mx)
    
#    total_u = float(sum(nc_distr))
#    print("Total users found ", total_u)
    
#   test_file_out = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/Obtained_num_calls_and_its_pct.tsv"
#   fto =  open(test_file_out,"w")
#    for j in range(0, max_num_calls):
#        nc_distr_pct[j] = (nc_distr[j] / total_u) * 100
#        fto.write(str(j) + '\t' + str(nc_distr_pct[j]) + '\n')

#    # I was just checking that the total percents sums up to 100 and they do but it looked funny as we have so small values
#    total = 0    
#    for i in range (max_num_calls):
#        total += percent_users[i]
#    print ("Check ", total)

############################################################################################################################
# THIS is to plot number of users pdf
############################################################################################################################

    fig1 = plt.figure(1)
    ax = fig1.add_subplot(111)
    n, bins, rectangles = ax.hist(usr_rg, 100, normed=True)

    #plt.plot(nc_distr_pct, 'ro', linewidth=0.5, label= 'pdf Num of calls')
    
    plt.xlabel('rg [km]')
    plt.ylabel('P(rg)')
    plt.legend()   
    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
    plt.yscale('log')
    plt.xscale('log')
    figure_name = "/home/sscepano/D4D res/allstuff/rg/pdf rg loglog.png"
    
#    #this is a regular plot file, then comment the previous loglog block
#    figure_name = "/home/sscepano/D4D res/allstuff/rg/pdf rg.png"
      
    print(figure_name)
    plt.savefig(figure_name, format = "png")        
    
################################################################################################################################
## THIS is to plot fq pdf
################################################################################################################################
#
#    plt.figure(2)
#    
#    fq = []
#    
#    for j in range(max_num_calls):
#        fq.append( float(j / 3360.0))
#
#    ffq = []
#    
#    for j in range(max_num_calls):
#        ffq.append(nc_distr_pct[j])
#        
#   
##    test_file_out2 = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/Calculated_fq_calls_and_its_pct2.tsv"
##    fto2 =  open(test_file_out2,"w")
##    for j in range(0, max_num_calls):
##        fto2.write(str(fq[j]) + '\t' + str(ffq[j]) + '\n')    
#
#
#    # Finally understood here -- when I give two arrays: x, y (at least append values IN ORDER like here) -- pyplot will plot y versus x
#    plt.plot(fq, ffq, 'g.', linewidth=0.3, label= 'pdf fq of calls')
#    
#    plt.xlabel('fq of calls')
#    plt.ylabel('% Users')
#    plt.legend()   
#    
#    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file   
#    plt.yscale('log')
#    plt.xscale('log')
#    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/SET3 distr of fq of calls loglog.png" 
#    
##    # this is a regular plot file, then comment the previous loglog block
##    figure_name = "/home/sscepano/D4D res/allstuff/SET3 frequent callers from python/1/SET3 distr of fq of calls.png"
#      
#    print(figure_name)
#    plt.savefig(figure_name, format = "png")   
    

    return   
Exemple #14
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()
Exemple #15
0
def from_files_usr_movements():

    file_name1 = "/home/sscepano/D4D res/allstuff/USER GRAPHS stats/user_number_of_edges_v1.tsv"
    file_name2 = "/home/sscepano/D4D res/allstuff/USER GRAPHS stats/user_number_of_nodes_v1.tsv"
    file_name3 = "/home/sscepano/D4D res/allstuff/USER GRAPHS stats/user_number_of_displacements_v1.tsv"

    nits = []
    its = []

    # a loop where we populate those two arrays from the file
    i = 0
    f = open(file_name3, "r")
    # read the file
    for line in f:
        i = i + 1
        it, nit = line.split("\t")
        nit = int(nit)
        it = int(it)
        nit = int(nit)
        nits.append(nit)
        its.append(it)

    mi = min(nits)
    mx = max(nits)
    print ("Minimum # edges ", mi)
    print ("Maximum # edges ", mx)

    total_nit = float(sum(nits))
    print ("Total # edges ", total_nit)

    pdf_nits = defaultdict(int)

    for j in range(0, len(nits)):
        pdf_nits[nits[j]] += 1

    ordered = OrderedDict(sorted(pdf_nits.items(), key=lambda t: t[0]))

    nits7s = []
    its7s = []

    test = 0

    for j in ordered.iterkeys():
        nits7s.append(ordered[j] / 500000.0)
        test += ordered[j] / 500000.0
        its7s.append(j)

    print test

    ############################################################################################################################
    # THIS is to plot number of users pdf
    ############################################################################################################################

    plt.figure(7)

    plt.plot(its7s, nits7s, "o", linewidth=0.5, label="distr. of # displacements ")

    plt.xlabel("# displacements")
    plt.ylabel("P(# displacements)")
    plt.legend()

    # this is if we want loglog lot, otheriwse comment and uncomment next line for regular plot file
    plt.yscale("log")
    plt.xscale("log")
    # figure_name1 = "/home/sscepano/D4D res/allstuff/USER GRAPHS stats/usr_num_edges.png"
    # figure_name2 = "/home/sscepano/D4D res/allstuff/USER GRAPHS stats/usr_num_nodes.png"
    figure_name3 = "/home/sscepano/D4D res/allstuff/USER GRAPHS stats/usr_num_displacements.png"

    print (figure_name3)
    plt.savefig(figure_name3, format="png", dpi=300)

    return
pred=conv_net(x,weights,biases,keep_prob)

cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

correct_pred=tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32))

init=tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    step=1
    while step*batch_size<training_iters:
        batch_x,batch_y=mnist.train.next_batch(batch_size)
        test=batch_x[0]
        fig=plt.figure()
        plt.imshow(test.reshape((28,28),order='C'),cmap='Greys',interpolation='nearest')
        print(weights['wc1'].eval()[0])
        plt.imshow(weights['wc1'].eval()[0][0].reshape(4,8),cmap='Greys',interpolation='nearest')
        sess.run(optimizer,feed_dict={x:batch_x,y:batch_y,keep_prob:dropout})
        if step%display_step==0:
            loss,acc=sess.run([cost,accuracy],feed_dict={x:batch_x,y:batch_y,keep_prob:1.})
            print('Iter'+str(step*batch_size)+',Minibatch Loss='+'{:.6f}'.format(loss)+'+,Training Accuracy='+'{:.5f}'.format(acc))
    step+=1
print('Optimization Finished!')
print('Testing Accuracy:',sess.run(accuracy,feed_dict={x:minist.test.images[:256],
                                                       y:minist.test.images[:256],
                                                       keep_prob:1.}))
# load the dataset
import pyplot as plt
data = read_csv('brain activity.txt', header=None)
# retrieve data as numpy array
values = data.values
# create a subplot for each time series
plt.figure()
for i in range(values.shape[1]):
	plt.subplot(values.shape[1], 1, i+1)
	plt.plot(values[:, i])
plt.show()