Example #1
0
def initialize():
    global flooded_list
    global color_of_tile
    global movecount
    global for_restart
    global btncol
    flooded_list = list()
    color_of_tile = dict()
    movecount = 0
    for_restart = False

    screen.fill(0)  #color screen black

    #fills the grid with randomly colored tiles
    for i in range(14):
        for j in range(14):
            X = STEP_SIZE * i
            Y = STEP_SIZE * j
            tile = pygame.Surface(TILE_SIZE)
            color = colors[random.randint(0, 5)]
            tile.fill(rgb[color])
            color_of_tile[(X, Y)] = color
            screen.blit(tile, [X, Y])

    flooded_list.append((0, 0))

    # This is the function the students will write. -Jeremy
    flood(color_of_tile, flooded_list)

    tile = pygame.Surface(TILE_SIZE)
    tile.fill(rgb[color_of_tile[(0, 0)]])
    for i in range(len(flooded_list)):
        screen.blit(tile, flooded_list[i])
    pygame.display.update()

    # render controls
    # button initialization
    btncol = [dict(), dict(), dict(), dict(), dict(), dict()]

    # button initialization, color and position
    btncol[0] = {'color': rgb["pink"], 'position': (512, 21)}
    btncol[1] = {'color': rgb["violet"], 'position': (512, 95)}
    btncol[2] = {'color': rgb["yellow"], 'position': (512, 169)}
    btncol[3] = {'color': rgb["red"], 'position': (512, 243)}
    btncol[4] = {'color': rgb["olive"], 'position': (512, 317)}
    btncol[5] = {'color': rgb["blue"], 'position': (512, 391)}

    for i in range(len(btncol)):
        pygame.draw.circle(
            screen, btncol[i]['color'],
            (btncol[i]['position'][0] + 16, btncol[i]['position'][1] + 16), 16)
    pygame.display.update()
Example #2
0
def initialize(board_size, color_of_tile, flooded_list, screen_size):
    global btncol
    global screen

    screen.fill(0)  #color screen black

    #fills the grid with randomly colored tiles
    for i in range(board_size):
        for j in range(board_size):
            X = STEP_SIZE * i
            Y = STEP_SIZE * j
            tile = pygame.Surface(TILE_SIZE)
            tile.fill(rgb[color_of_tile[(X, Y)]])
            screen.blit(tile, [X, Y])

    # This is the function the students will write. -Jeremy
    flood(color_of_tile, flooded_list, screen_size)

    tile = pygame.Surface(TILE_SIZE)
    tile.fill(rgb[color_of_tile[(0, 0)]])
    for i in range(len(flooded_list)):
        screen.blit(tile, flooded_list[i])
    pygame.display.update()

    # render controls
    # button initialization
    btncol = [dict(), dict(), dict(), dict(), dict(), dict()]

    # button initialization, color and position
    btncol[0] = {'color': rgb["pink"], 'position': (screen_size[1] + 64, 21)}
    btncol[1] = {'color': rgb["violet"], 'position': (screen_size[1] + 64, 95)}
    btncol[2] = {
        'color': rgb["yellow"],
        'position': (screen_size[1] + 64, 169)
    }
    btncol[3] = {'color': rgb["red"], 'position': (screen_size[1] + 64, 243)}
    btncol[4] = {'color': rgb["olive"], 'position': (screen_size[1] + 64, 317)}
    btncol[5] = {'color': rgb["blue"], 'position': (screen_size[1] + 64, 391)}

    for i in range(len(btncol)):
        pygame.draw.circle(
            screen, btncol[i]['color'],
            (btncol[i]['position'][0] + 16, btncol[i]['position'][1] + 16), 16)
    pygame.display.update()
Example #3
0
def initialize(board_size, color_of_tile, flooded_list, screen_size):
    global btncol
    global screen
    
    screen.fill(0) #color screen black

    #fills the grid with randomly colored tiles
    for i in range(board_size):
        for j in range(board_size):
            X = STEP_SIZE*i
            Y = STEP_SIZE*j
            tile = pygame.Surface(TILE_SIZE)
            tile.fill(rgb[color_of_tile[(X,Y)]])
            screen.blit(tile, [X, Y])

    # This is the function the students will write. -Jeremy
    flood(color_of_tile, flooded_list, screen_size)

    tile = pygame.Surface(TILE_SIZE)
    tile.fill(rgb[color_of_tile[(0,0)]])
    for i in range(len(flooded_list)):
        screen.blit(tile, flooded_list[i])
    pygame.display.update()

    # render controls
    # button initialization
    btncol = [dict(), dict(), dict(), dict(), dict(), dict()]

    # button initialization, color and position
    btncol[0] = { 'color': rgb["pink"], 'position': (screen_size[1] + 64, 21) }
    btncol[1] = { 'color': rgb["violet"], 'position': (screen_size[1] + 64, 95) }
    btncol[2] = { 'color': rgb["yellow"], 'position': (screen_size[1] + 64, 169) }
    btncol[3] = { 'color': rgb["red"], 'position': (screen_size[1] + 64, 243) }
    btncol[4] = { 'color': rgb["olive"], 'position': (screen_size[1] + 64, 317) }
    btncol[5] = { 'color': rgb["blue"], 'position': (screen_size[1] + 64, 391) }

    for i in range(len(btncol)):
        pygame.draw.circle(screen, btncol[i]['color'],
                           (btncol[i]['position'][0]+16,
                            btncol[i]['position'][1]+16),
                           16)
    pygame.display.update()
Example #4
0
def step(screen_size,
         color_of_tile,
         flooded_list,
         color,
         show_graphics=False,
         gen_tests=False,
         times=[]):
    global tests
    global test
    global board_size
    global max_moves
    global screen

    if color != None and step.movecount < max_moves:
        step.movecount += 1

        if show_graphics:
            tile = pygame.Surface(TILE_SIZE)
            tile.fill(rgb[color])

        if gen_tests:
            test.append(copy.deepcopy(color_of_tile))
            test.append(color)

        for coord in flooded_list:
            color_of_tile[coord] = color

        # This is the function the students will write. -Jeremy
        t1 = time.time()
        flood(color_of_tile, flooded_list, screen_size)
        t2 = time.time()
        times.append(t2 - t1)

        if show_graphics:
            for i in range(len(flooded_list)):
                screen.blit(tile, flooded_list[i])

        # drought every seven years
        if drought_enabled and len(
                flooded_list) > 0 and step.movecount % 7 == 0:
            td1 = time.time()
            drought_tiles = create_drought(flooded_list, color_of_tile)
            #             td2 = time.clock()
            diff = time.time() - td1
            print "%0.8lf" % diff
            #             times.append(diff)

            if show_graphics:
                display.set_caption('Flood-it! Drought in progress!')
                for coord in drought_tiles:
                    tile.fill(rgb[color_of_tile[coord]])
                    screen.blit(tile, coord)
        else:
            if show_graphics:
                display.set_caption('Flood-it! ' + str(step.movecount) + '/' +
                                    str(max_moves))

        if show_graphics:
            pygame.display.update()

    if len(flooded_list) == (board_size * board_size):
        if show_graphics:
            game_over('win.png', screen_size)
            display.set_caption('Flood-it! Congratulations. You won!')
        if gen_tests:
            test.append(copy.deepcopy(color_of_tile))
            tests.append(test)
            test = []
        step.movecount = 0
        return True

    if step.movecount == max_moves and len(flooded_list) != (board_size *
                                                             board_size):
        if show_graphics:
            game_over('gameover.png', screen_size)
            display.set_caption('Flood-it! GAME OVER!')
        if gen_tests:
            test.append(copy.deepcopy(color_of_tile))
            tests.append(test)
            test = []
        step.movecount = 0
        return True

    return False
Example #5
0
def remap_bdry(zero, l_time, src_file, src_varname, src_grd, dst_grd,
               grid_name):

    print src_file
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    cw = int(len(dst_grd.vgrid.Cs_r))
    # create boundary file
    dst_file = src_varname + '_bdry' + '.nc'
    print '\nCreating boundary file', dst_file
    if os.path.exists(dst_file) is True:
        os.remove(dst_file)
    pyroms_toolbox.nc_create_roms_bdry_file(dst_file, dst_grd)

    nc = netCDF.Dataset(dst_file, 'a', format='NETCDF4')
    cdf = netCDF.Dataset(src_file)
    spval = -32767
    time = cdf.variables['time'][zero:l_time]
    time = time - time[0]
    if src_varname == 'ssh':
        src_var = np.zeros((len(time), Mp, Lp))
        ndim = 3
    else:
        ndim = 4

    if src_varname == 'ssh':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'zeta'
        dimensions_time = ('zeta_time')
        dst_varname_time = 'zeta_time'
        long_name = "free-surface time"
        unitstime = "days since 2006-01-01 00:00:00 GMT"
        calendar = "gregorian"
        long_name = 'free-surface'
        dst_varname_north = 'zeta_north'
        dimensions_north = ('zeta_time', 'xi_rho')
        long_name_north = 'free-surface north boundary condition'
        field_north = 'zeta_north, scalar, series'
        dst_varname_south = 'zeta_south'
        dimensions_south = ('zeta_time', 'xi_rho')
        long_name_south = 'free-surface south boundary condition'
        field_south = 'zeta_south, scalar, series'
        dst_varname_east = 'zeta_east'
        dimensions_east = ('zeta_time', 'eta_rho')
        long_name_east = 'free-surface east boundary condition'
        field_east = 'zeta_east, scalar, series'
        dst_varname_west = 'zeta_west'
        dimensions_west = ('zeta_time', 'eta_rho')
        long_name_west = 'free-surface west boundary condition'
        field_west = 'zeta_west, scalar, series'
        units = 'meter'
    elif src_varname == 'temperature' or src_varname == 'votemper':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'temperature'
        dimensions_time = ('temp_time')
        dst_varname_time = 'temp_time'
        long_name = "potential temperature time"
        unitstime = "days since 2004-01-01 00:00:00 GMT"
        calendar = "gregorian"
        dst_varname_north = 'temp_north'
        dimensions_north = ('temp_time', 's_rho', 'xi_rho')
        long_name_north = 'potential temperature north boundary condition'
        field_north = 'temp_north, scalar, series'
        dst_varname_south = 'temp_south'
        dimensions_south = ('temp_time', 's_rho', 'xi_rho')
        long_name_south = 'potential temperature south boundary condition'
        field_south = 'temp_south, scalar, series'
        dst_varname_east = 'temp_east'
        dimensions_east = ('temp_time', 's_rho', 'eta_rho')
        long_name_east = 'potential temperature east boundary condition'
        field_east = 'temp_east, scalar, series'
        dst_varname_west = 'temp_west'
        dimensions_west = ('temp_time', 's_rho', 'eta_rho')
        long_name_west = 'potential temperature west boundary condition'
        field_west = 'temp_west, scalar, series'
        units = 'Celsius'
    elif src_varname == 'salinity' or src_varname == 'vosaline':
        pos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'salinity'
        dimensions_time = ('salt_time')
        dst_varname_time = 'salt_time'
        long_name = "surface net heat flux time"
        unitstime = "days since 2004-01-01 00:00:00 GMT"
        calendar = "gregorian"
        dst_varname_north = 'salt_north'
        dimensions_north = ('salt_time', 's_rho', 'xi_rho')
        long_name_north = 'salinity north boundary condition'
        field_north = 'salt_north, scalar, series'
        dst_varname_south = 'salt_south'
        dimensions_south = ('salt_time', 's_rho', 'xi_rho')
        long_name_south = 'salinity south boundary condition'
        field_south = 'salt_south, scalar, series'
        dst_varname_east = 'salt_east'
        dimensions_east = ('salt_time', 's_rho', 'eta_rho')
        long_name_east = 'salinity east boundary condition'
        field_east = 'salt_east, scalar, series'
        dst_varname_west = 'salt_west'
        dimensions_west = ('salt_time', 's_rho', 'eta_rho')
        long_name_west = 'salinity west boundary condition'
        field_west = 'salt_west, scalar, series'
        units = 'PSU'
    else:
        raise ValueError, 'Undefined src_varname'

    if ndim == 4:
        # build intermediate zgrid
        zlevel = -z[::-1, 0, 0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    # create variable in boudary file
    print 'Creating dimension'
    nc.createDimension(dst_varname_time, l_time - zero)  ###
    print l_time - zero, len(time)

    print 'Creating variable', dst_varname_north
    nc.createVariable(dst_varname_north,
                      'f8',
                      dimensions_north,
                      fill_value=spval)
    nc.variables[dst_varname_north].long_name = long_name_north
    nc.variables[dst_varname_north].units = units
    nc.variables[dst_varname_north].field = field_north
    #nc.variables[dst_varname_north]._FillValue = spval

    print 'Creating variable', dst_varname_south
    nc.createVariable(dst_varname_south,
                      'f8',
                      dimensions_south,
                      fill_value=spval)
    nc.variables[dst_varname_south].long_name = long_name_south
    nc.variables[dst_varname_south].units = units
    nc.variables[dst_varname_south].field = field_south
    #nc.variables[dst_varname_south]._FillValue = spval

    print 'Creating variable', dst_varname_east
    nc.createVariable(dst_varname_east,
                      'f8',
                      dimensions_east,
                      fill_value=spval)
    nc.variables[dst_varname_east].long_name = long_name_east
    nc.variables[dst_varname_east].units = units
    nc.variables[dst_varname_east].field = field_east
    #nc.variables[dst_varname_east]._FillValue = spval

    print 'Creating variable', dst_varname_west
    nc.createVariable(dst_varname_west,
                      'f8',
                      dimensions_west,
                      fill_value=spval)
    nc.variables[dst_varname_west].long_name = long_name_west
    nc.variables[dst_varname_west].units = units
    nc.variables[dst_varname_west].field = field_west
    #nc.variables[dst_varname_west]._FillValue = spval

    print 'Creating variable', dst_varname_time
    nc.createVariable(dst_varname_time, 'f4', dimensions_time)
    nc.variables[dst_varname_time].long_name = long_name
    nc.variables[dst_varname_time].units = unitstime
    nc.variables[dst_varname_time].calendar = calendar

    if ndim == 4:
        dst_var_north = np.zeros((l_time - zero, cw, 1, Lp))
        dst_var_south = np.zeros((l_time - zero, cw, 1, Lp))
        dst_var_east = np.zeros((l_time - zero, cw, Mp, 1))
        dst_var_west = np.zeros((l_time - zero, cw, Mp, 1))
        for i in range(len(time)):
            if src_varname == 'votemper':
                src_varz = flood(
                    cdf.variables[src_varname][zero + i, :, :, :] - 273.15,
                    src_grd,
                    spval=spval)
            else:
                src_varz = flood(cdf.variables[src_varname][i, :, :, :],
                                 src_grd,
                                 spval=spval)
            dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)
            dst_var_north_cont = pyroms.remapping.z2roms(dst_varz[::-1, Mp -
                                                                  1:Mp, :],
                                                         dst_grdz,
                                                         dst_grd,
                                                         Cpos=Cpos,
                                                         spval=spval,
                                                         flood=True,
                                                         irange=(0, Lp),
                                                         jrange=(Mp - 1, Mp))
            dst_var_south_cont = pyroms.remapping.z2roms(dst_varz[::-1,
                                                                  0:1, :],
                                                         dst_grdz,
                                                         dst_grd,
                                                         Cpos=Cpos,
                                                         spval=spval,
                                                         flood=True,
                                                         irange=(0, Lp),
                                                         jrange=(0, 1))
            dst_var_east_cont = pyroms.remapping.z2roms(dst_varz[::-1, :,
                                                                 Lp - 1:Lp],
                                                        dst_grdz,
                                                        dst_grd,
                                                        Cpos=Cpos,
                                                        spval=spval,
                                                        flood=True,
                                                        irange=(Lp - 1, Lp),
                                                        jrange=(0, Mp))
            dst_var_west_cont = pyroms.remapping.z2roms(dst_varz[::-1, :, 0:1],
                                                        dst_grdz,
                                                        dst_grd,
                                                        Cpos=Cpos,
                                                        spval=spval,
                                                        flood=True,
                                                        irange=(0, 1),
                                                        jrange=(0, Mp))
            dst_var_north[i, :, :, :] = dst_var_north_cont
            dst_var_south[i, :, :, :] = dst_var_south_cont
            dst_var_east[i, :, :, :] = dst_var_east_cont
            dst_var_west[i, :, :, :] = dst_var_west_cont
            print i
    else:
        dst_var_north = np.zeros((l_time - zero, Lp))
        dst_var_south = np.zeros((l_time - zero, Lp))
        dst_var_east = np.zeros((l_time - zero, Mp))
        dst_var_west = np.zeros((l_time - zero, Mp))
        for i in range(len(time)):
            #src_varz = src_var[i,:,:]
            src_varz = np.zeros((len(src_var[0, :, 0]), len(src_var[0, 0, :])))
            dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)
            dst_var_north[i, :] = np.zeros((len(dst_varz[-1, :])))
            dst_var_south[i, :] = np.zeros((len(dst_varz[0, :])))
            dst_var_east[i, :] = np.zeros((len(dst_varz[:, -1])))
            dst_var_west[i, :] = np.zeros((len(dst_varz[:, 0])))
            print dst_var_south[i, :]

    # write data in destination file
    print 'write data in destination file'
    #time_2=np.concatenate((time,time+365,time+365+365,time+365+365+365,time+365+365+365+365),axis=0)		####
    time_2 = time  ####
    nc.variables[dst_varname_time][:] = time_2
    print time

    #dst_var_north_2=np.concatenate((dst_var_north,dst_var_north,dst_var_north,dst_var_north,dst_var_north),axis=0) ####
    #dst_var_south_2=np.concatenate((dst_var_south,dst_var_south,dst_var_south,dst_var_south,dst_var_south),axis=0) ####
    #dst_var_east_2=np.concatenate((dst_var_east,dst_var_east,dst_var_east,dst_var_east,dst_var_east),axis=0)	 ####
    #dst_var_west_2=np.concatenate((dst_var_west,dst_var_west,dst_var_west,dst_var_west,dst_var_west),axis=0)	 ####
    #nc.variables[dst_varname_north][:] = np.squeeze(dst_var_north_2)	 ####
    #nc.variables[dst_varname_south][:] = np.squeeze(dst_var_south_2)	 ####
    #nc.variables[dst_varname_east][:] = np.squeeze(dst_var_east_2)	 ####
    #nc.variables[dst_varname_west][:] = np.squeeze(dst_var_west_2)	 ####
    nc.variables[dst_varname_north][:] = dst_var_north
    nc.variables[dst_varname_south][:] = dst_var_south
    nc.variables[dst_varname_east][:] = dst_var_east
    nc.variables[dst_varname_west][:] = dst_var_west

    # close file
    nc.close()
    cdf.close()

    if src_varname == 'ssh':
        return dst_varz
Example #6
0
def step(screen_size, color_of_tile, flooded_list, color, show_graphics=False, gen_tests=False, times=[]):
    global tests
    global test
    global board_size
    global max_moves
    global screen
    
    if color != None and step.movecount < max_moves:
        step.movecount += 1
        
        if show_graphics:
            tile = pygame.Surface(TILE_SIZE)
            tile.fill(rgb[color])
        
        if gen_tests: test.append(copy.deepcopy(color_of_tile)); test.append(color)
        
        for coord in flooded_list:
            color_of_tile[coord] = color

        # This is the function the students will write. -Jeremy
        t1 = time.time()
        flood(color_of_tile, flooded_list, screen_size)
        t2 = time.time()
        times.append(t2-t1)

        if show_graphics:
            for i in range(len(flooded_list)):
                screen.blit(tile, flooded_list[i])

        # drought every seven years
        if drought_enabled and len(flooded_list) > 0 and step.movecount % 7 == 0:
            td1 = time.time()
            drought_tiles = create_drought(flooded_list, color_of_tile)
#             td2 = time.clock()
            diff = time.time() - td1
            print "%0.8lf" % diff
#             times.append(diff)
            
            if show_graphics:
                display.set_caption('Flood-it! Drought in progress!')
                for coord in drought_tiles:
                    tile.fill(rgb[color_of_tile[coord]])
                    screen.blit(tile, coord)
        else:
            if show_graphics:
                display.set_caption('Flood-it! '+str(step.movecount)+'/' + str(max_moves))

        if show_graphics:
            pygame.display.update()

    if len(flooded_list) == (board_size * board_size):
        if show_graphics:
            game_over('win.png', screen_size)
            display.set_caption('Flood-it! Congratulations. You won!')
        if gen_tests: test.append(copy.deepcopy(color_of_tile)); tests.append(test); test = []
        step.movecount = 0
        return True

    if step.movecount == max_moves and len(flooded_list) != (board_size * board_size):
        if show_graphics:
            game_over('gameover.png', screen_size)
            display.set_caption('Flood-it! GAME OVER!')
        if gen_tests: test.append(copy.deepcopy(color_of_tile)); tests.append(test); test = []
        step.movecount = 0
        return True
    
    return False
def crystal_detection(dir,filename,videofilename):
    global horizontal_center
    vidcap=cv2.VideoCapture(videofilename)
    slug_number=int(filename[4:-4])
    msec,length,innerLength,speed,horizontal_center=info[slug_number][:-4]
    horizontal_center=int(horizontal_center)
    leftmargin,leftinner,rightinner,rightmargin=map(scale,info[slug_number][-4:])
    mm=3000.0/speed
    im=[]
    for i in xrange(2*N+1):
        m=msec+(i-N)*mm
        vidcap.set(cv.CV_CAP_PROP_POS_MSEC, m) 
        success,image=vidcap.read()
        if i==N:
            im_o=image[:,:]
            im_o_bw=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
        im.append(cv2.cvtColor(image,cv2.COLOR_RGB2GRAY))
        cv2.imwrite(os.path.join(dir,'crystal_%d_raw_%d.jpg'%(slug_number,i)), im[i])
    tmp=im[N][:,:]
    left,right=find_margin(im[N],leftinner,rightinner)
    for i in xrange(h):
        for j in xrange(left,right+1):
            colors=[im[x].item(i,j) for x in xrange(2*N+1) if x!=N]
            if sum([abs(x-im[N].item(i,j))<=5 for x in colors])>N*0.6:
                tmp.itemset(i,j,255)
                continue
            colors=[]
            for x in xrange(2*N+1):
                if x==N: continue
                j1=j-(x-N)*0.03*w
                if 0>j1 or j1>=w: continue
                colors.append(im[x].item(i,j1))
            if sum([abs(x-im[N].item(i,j))<=5 for x in colors])>len(colors)*0.3:
                tmp.itemset(i,j,255)
                continue
            tmp.itemset(i,j,0)
    tmp=tmp[:,left:right+1]
    width=right+1-left
    blocks=flood(tmp,h,width)
    cv2.imwrite(os.path.join(dir,'crystal_%d_middle.jpg'%slug_number), tmp)
    for area,min_rec,components,convexhull in blocks:
        c=0.0;b=[255.0]
        components=set(components)
        for i,j in components:
            c+=im_o_bw.item(i,j+left)
            for x in xrange(5):
                u=i+random.randint(-5,5)
                v=j+random.randint(-5,5)
                if (u,v) in components: 
                    continue
                if not ((0<=u<h) and (0<=v<w)): continue
                b.append(im_o_bw.item(u,v))
        b.sort()
        b=b[len(b)/2]    
        c/=len(components)
        if c>b+20: continue
        color=[random.randint(150,256) for x in xrange(3)]
        [[u1,v1]]=convexhull[-1]
        for [[u2,v2]] in convexhull:
            le=int(math.sqrt((u1-u2)**2+(v1-v2)**2)*1.2)+2
            for ratio in xrange(le):
                r=ratio*1.0/(le-1)
                i=int(u1*r+(1-r)*u2+0.0001)
                j=int(v1*r+(1-r)*v2+0.0001)
                for x in xrange(3):
                    im_o.itemset(i,j+left,x,color[x])
            u1,v1=u2,v2
        (u1,v1),(u2,v2),t=min_rec
        with open(os.path.join(dir,'result.txt'),'a') as f:
            f.write('\t'.join([str(slug_number)]+
                              map(float_to_str,(u1,v1+left,u2,v2)))+'\n')
        #print '\t'.join([str(slug_number)]+map(float_to_str,(u1,v1+left,u2,v2))),c,b
    cv2.imwrite(os.path.join(dir,'crystal_%d_final.jpg'%slug_number), im_o)
    cv2.imwrite(os.path.join(dir,'final_%d.jpg'%slug_number), im_o)
    print slug_number
Example #8
0
def remap_uv(zero, l_time, src_file, src_grd, dst_grd, grid_name):
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    cw = int(len(dst_grd.vgrid.Cs_r))
    dxy = 5
    cdepth = 0
    kk = 0
    nctime.long_name = 'time'
    nctime.units = 'hours since 2006-01-01 00:00:00'
    cdf = Dataset(src_file)

    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    dst_file = src_file.rsplit('/')[-1]
    dst_fileu = 'u' + dst_grd.name + '.nc'
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_file(dst_fileu, dst_grd, nctime)
    dst_filev = 'v' + dst_grd.name + '.nc'
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_file(dst_filev, dst_grd, nctime)

    # open destination file
    ncu = Dataset(dst_fileu, 'a', format='NETCDF3_64BIT')
    ncv = Dataset(dst_filev, 'a', format='NETCDF3_64BIT')

    time = cdf.variables['time'][zero:l_time]
    time = time - time[0]
    print time

    #get missing value
    spval = -32767  #src_varu._FillValue

    # get weights file
    wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (grid_name)

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1, 0, 0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                     dst_zcoord)

    # create variable in destination file
    #print 'Creating variable u'
    ncu.createVariable('u',
                       'f8', ('ocean_time', 's_rho', 'eta_u', 'xi_u'),
                       fill_value=spval)
    ncu.variables['u'].long_name = '3D u-momentum component'
    ncu.variables['u'].units = 'meter second-1'
    ncu.variables['u'].field = 'u-velocity, scalar, series'
    #ncu.variables['u_north']._FillValue = spval
    # create variable in destination file
    #print 'Creating variable ubar'
    ncu.createVariable('ubar',
                       'f8', ('ocean_time', 'eta_u', 'xi_u'),
                       fill_value=spval)
    ncu.variables['ubar'].long_name = '2D u-momentum component'
    ncu.variables['ubar'].units = 'meter second-1'
    ncu.variables['ubar'].field = 'ubar-velocity,, scalar, series'
    #ncu.variables['ubar_north']._FillValue = spval

    #print 'Creating variable v'
    ncv.createVariable('v',
                       'f8', ('ocean_time', 's_rho', 'eta_v', 'xi_v'),
                       fill_value=spval)
    ncv.variables['v'].long_name = '3D v-momentum component'
    ncv.variables['v'].units = 'meter second-1'
    ncv.variables['v'].field = 'v-velocity, scalar, series'
    #ncv.variables['v_north']._FillValue = spval
    #print 'Creating variable vbar'
    ncv.createVariable('vbar',
                       'f8', ('ocean_time', 'eta_v', 'xi_v'),
                       fill_value=spval)
    ncv.variables['vbar'].long_name = '2D v-momentum component'
    ncv.variables['vbar'].units = 'meter second-1'
    ncv.variables['vbar'].field = 'vbar-velocity,, scalar, series'
    #ncv.variables['vbar_north']._FillValue = spval

    # remaping
    #print 'remapping and rotating u and v from', src_grd.name, 'to', dst_grd.name
    #print 'time =', time

    src_angle = pyroms.remapping.remap(
        src_grd.angle,
        'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (grid_name),
        spval=spval)
    dst_angle = dst_grd.hgrid.angle_rho
    angle = dst_angle - src_angle
    angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))
    eitheta = np.exp(-1j * angle[:, :, :])

    dst_u = np.zeros((l_time - zero, cw, Mp, Lp - 1))
    dst_v = np.zeros((l_time - zero, cw, Mp - 1, Lp))
    dst_ubar = np.zeros((l_time - zero, Mp, Lp - 1))
    dst_vbar = np.zeros((l_time - zero, Mp - 1, Lp))
    for m in range(len(time)):
        src_uz = flood(cdf.variables['vomecrty'][zero + m, :, :, :],
                       src_grd,
                       spval=spval)
        src_vz = flood(cdf.variables['vozocrtx'][zero + m, :, :, :],
                       src_grd,
                       spval=spval)
        dst_uz = pyroms.remapping.remap(src_uz, wts_file, spval=spval)
        dst_vz = pyroms.remapping.remap(src_vz, wts_file, spval=spval)
        dst_u_cont = pyroms.remapping.z2roms(dst_uz[::-1, :, :],
                                             dst_grdz,
                                             dst_grd,
                                             Cpos='rho',
                                             spval=spval,
                                             flood=True)
        dst_v_cont = pyroms.remapping.z2roms(dst_vz[::-1, :, :],
                                             dst_grdz,
                                             dst_grd,
                                             Cpos='rho',
                                             spval=spval,
                                             flood=True)
        U = dst_u_cont + dst_v_cont * 1j
        U = U * eitheta
        dst_u_cont = np.real(U)
        dst_v_cont = np.imag(U)
        dst_u_cont = 0.5 * (dst_u_cont[:, :, :-1] + dst_u_cont[:, :, 1:])
        dst_v_cont = 0.5 * (dst_v_cont[:, :-1, :] + dst_v_cont[:, 1:, :])
        idxu = np.where(dst_grd.hgrid.mask_u == 0)
        idxv = np.where(dst_grd.hgrid.mask_v == 0)
        for n in range(dst_grd.vgrid.N):
            dst_u_cont[n, idxu[0], idxu[1]] = spval
            dst_v_cont[n, idxv[0], idxv[1]] = spval
        z_u = 0.5 * (dst_grd.vgrid.z_w[0, :, :, :-1] +
                     dst_grd.vgrid.z_w[0, :, :, 1:])
        z_v = 0.5 * (dst_grd.vgrid.z_w[0, :, :-1, :] +
                     dst_grd.vgrid.z_w[0, :, 1:, :])
        dst_ubar_cont = np.zeros((dst_u_cont.shape[1], dst_u_cont.shape[2]))
        dst_vbar_cont = np.zeros((dst_v_cont.shape[1], dst_v_cont.shape[2]))
        for i in range(dst_ubar_cont.shape[1]):
            for j in range(dst_ubar_cont.shape[0]):
                dst_ubar_cont[j, i] = (dst_u_cont[:, j, i] * np.diff(
                    z_u[:, j, i])).sum() / -z_u[0, j, i]
        for i in range(dst_vbar_cont.shape[1]):
            for j in range(dst_vbar_cont.shape[0]):
                dst_vbar_cont[j, i] = (dst_v_cont[:, j, i] * np.diff(
                    z_v[:, j, i])).sum() / -z_v[0, j, i]
        for i in range(dst_ubar_cont.shape[1]):
            for j in range(dst_ubar_cont.shape[0]):
                dst_ubar_cont[j, i] = (dst_u_cont[:, j, i] * np.diff(
                    z_u[:, j, i])).sum() / -z_u[0, j, i]
        for i in range(dst_vbar_cont.shape[1]):
            for j in range(dst_vbar_cont.shape[0]):
                dst_vbar_cont[j, i] = (dst_v_cont[:, j, i] * np.diff(
                    z_v[:, j, i])).sum() / -z_v[0, j, i]
        dst_ubar_cont[idxu[0], idxu[1]] = spval
        dst_vbar_cont[idxv[0], idxv[1]] = spval

        dst_ubar[m, :, :] = dst_ubar_cont
        dst_vbar[m, :, :] = dst_vbar_cont
        dst_u[m, :, :, :] = dst_u_cont
        dst_v[m, :, :, :] = dst_v_cont

    # write data in destination file
    #print 'write data in destination file'
    ncu.variables['ocean_time'][:] = time / 24.
    ncu.variables['u'][:] = dst_u
    ncu.variables['ubar'][:] = dst_ubar

    ncv.variables['ocean_time'][:] = time / 24.
    ncv.variables['v'][:] = dst_v
    ncv.variables['vbar'][:] = dst_vbar

    print time
    print np.shape(dst_u)
    print np.shape(dst_v)
    # close destination file
    ncu.close()
    ncv.close()
    def segment(self, flood_lines=None, use_normalize=False):
        print('segment ' + self.fn)
        self.name = self.fn[:-4]
        a = os.system('mkdir -p ' + self.name)
        self.rgb = [
            [
                self.dat[i],  # format data into list of rgb tuples
                self.dat[self.npx + i],
                self.dat[2 * self.npx + i]
            ] for i in range(0, self.npx)
        ]

        c = {}  # count rgb values
        for x in self.rgb:
            x = str(x)
            c[x] = c[x] + 1 if x in c else 1

        ffn = self.fn + '_rgb_count.png'
        if not os.path.exists(ffn):
            plt.figure()
            plt.bar(c.keys(), np.log(list(c.values())) / np.log(10.))
            plt.title("Log of count of color values")
            print('+w ' + ffn)
            plt.savefig(ffn)
            plt.close()

        counts = [[c[k], k] for k in c]
        counts.sort()
        self.max_color = counts[-1][1]  # assume most-prevalent col is bg

        if sys.getrecursionlimit() < self.npx:  # increase recursion limit
            sys.setrecursionlimit(self.npx)

        # labels for segmentation
        self.labels = [0 for i in range(self.npx)]  # 0 == unlabelled!
        self.next_label = 1

        r_i = flood_lines if flood_lines else range(self.rows)
        for i in r_i:
            for j in range(self.cols):
                flood(self, i, j)
        self.gather_points()  # list (i,j) points by segment

        fn = None
        is_truth = (self.name == 'truth')  # is this truth data?
        truth = None
        if is_truth:
            truth = [x for x in open('truth_chars.txt').read()]

        for pi in range(len(self.points)):  # plot image rep. of each truth

            point = self.points[pi]

            if pi > 0:  # 0 is bg / unlabelled
                try:
                    ns = truth[pi - 1] if is_truth else str(pi)
                    fn = self.name + os.path.sep + ns + '.png'
                    if not os.path.exists(fn):
                        plt.figure()
                        plt.scatter([x[1] for x in point],
                                    [-x[0] for x in point])
                        plt.title(ns)
                        print('+w ' + fn)
                        if use_normalize:
                            plt.xlim([-.5, self.cols - .5])
                            plt.ylim([-(self.rows - .5), .5])
                        plt.xlabel('col ix')
                        plt.ylabel('-row ix')
                        plt.savefig(fn)
                        plt.close()

                    fn = self.name + os.path.sep + ns + '.centroid'
                    if not os.path.exists(fn):
                        print('  +w ' + fn)
                        xL, yL = to_list(point)
                        cX, cY = centroid(xL, yL)
                        open(fn, 'wb').write(
                            (str(cX) + ' ' + str(cY)).encode())

                    # nb run cleanup.py before changing truth inputs
                    fn = self.name + os.path.sep + ns + '.p'
                    if not os.path.exists(fn):
                        print('  +w ' + fn)
                        pickle.dump(point, open(fn, 'wb'))
                except:
                    pass  # don't plot / save the background
Example #10
0
def remap(zero, l_time, src_file, src_varname, src_grd, dst_grd, grid_name):
    nctime.long_name = 'time'
    nctime.units = 'hours since 2006-01-01 00:00:00'
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    cw = int(len(dst_grd.vgrid.Cs_r))
    cdf = Dataset(src_file)
    if src_varname == 'ssh':
        src_var = np.zeros((1, Mp, Lp))
    else:
        src_var = cdf.variables[src_varname][0:1]
    ndim = np.ndim(src_var)
    spval = -32767
    dst_file = src_file.rsplit('/')[-1]
    dst_file = src_varname + dst_grd.name + '.nc'
    pyroms_toolbox.nc_create_roms_file(dst_file, dst_grd, nctime)
    nc = Dataset(dst_file, 'a', format='NETCDF3_64BIT')
    print ndim
    if ndim == 4:
        time = cdf.variables['time'][zero:l_time]
        src_var = src_var[0, :, :, :]
    elif ndim == 3:
        time = cdf.variables['time'][zero:l_time]
        src_var = np.zeros((len(time), Mp, Lp))
    time = time - time[0]
    if src_varname == 'ssh':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'zeta'
        dimensions = ('ocean_time', 'eta_rho', 'xi_rho')
        long_name = 'free-surface'
        units = 'meter'
        field = 'free-surface, scalar, series'
    elif src_varname == 'votemper':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'temp'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'potential temperature'
        units = 'Celsius'
        field = 'temperature, scalar, series'
    elif src_varname == 'vosaline':
        Bpos = 't'
        Cpos = 'rho'
        z = src_grd.z_t
        Mp, Lp = dst_grd.hgrid.mask_rho.shape
        wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' % (
            grid_name)
        dst_varname = 'salt'
        dimensions = ('ocean_time', 's_rho', 'eta_rho', 'xi_rho')
        long_name = 'salinity'
        units = 'PSU'
        field = 'salinity, scalar, series'

    if ndim == 4:
        zlevel = -z[::-1, 0, 0]
        nzlevel = len(zlevel)
        dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel,
                                               nzlevel)
        dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name + '_Z', dst_grd.hgrid,
                                         dst_zcoord)

    nc.createVariable(dst_varname, 'f8', dimensions, fill_value=spval)
    nc.variables[dst_varname].long_name = long_name
    nc.variables[dst_varname].units = units
    nc.variables[dst_varname].field = field
    dxy = 5
    cdepth = 0
    kk = 0

    if ndim == 4:
        dst_var = np.zeros((l_time - zero, cw, Mp, Lp))
        for i in range(len(time)):
            if src_varname == 'votemper':
                src_varz = flood(
                    cdf.variables[src_varname][zero + i, :, :, :] - 273.15,
                    src_grd,
                    spval=spval)
            else:
                src_varz = flood(cdf.variables[src_varname][zero + i, :, :, :],
                                 src_grd,
                                 spval=spval)
            dst_varz = pyroms.remapping.remap(src_varz, wts_file, spval=spval)
            dst_cont = pyroms.remapping.z2roms(dst_varz[::-1, :, :],
                                               dst_grdz,
                                               dst_grd,
                                               Cpos=Cpos,
                                               spval=spval,
                                               flood=True)
            dst_var[i, :, :, :] = dst_cont

    else:
        dst_var = np.zeros((l_time - zero, Mp, Lp))
#for i in range(len(time)):
#	xx=np.arange(-7,7,1);yy=np.arange(-7,7,1)
#	R=np.zeros((len(xx),len(yy)))
#	for j in range(len(xx)):
#		for k in range(len(yy)):
#			dst_var[i,j+17,k+31]=2*np.exp(-0.05*(xx[j]**2+yy[k]**2))

    nc.variables['ocean_time'][:] = time / 24.
    nc.variables[dst_varname][:] = dst_var
    nc.close()
Example #11
0
def remap_bdry_uv(zero,l_time, src_file, src_grd, dst_grd, grid_name):

    # get time
    # get dimensions
    Mp, Lp = dst_grd.hgrid.mask_rho.shape
    cw=int(len(dst_grd.vgrid.Cs_r))

    # create destination file
    dst_fileu = 'u_bdry' + '.nc'
    print '\nCreating destination file', dst_fileu
    if os.path.exists(dst_fileu) is True:
        os.remove(dst_fileu)
    pyroms_toolbox.nc_create_roms_bdry_file(dst_fileu, dst_grd)
    dst_filev = 'v_bdry'  '.nc'
    print 'Creating destination file', dst_filev
    if os.path.exists(dst_filev) is True:
        os.remove(dst_filev)
    pyroms_toolbox.nc_create_roms_bdry_file(dst_filev, dst_grd)
    cdf = Dataset(src_file)
    # open destination file
    ncu = Dataset(dst_fileu, 'a', format='NETCDF4')
    ncv = Dataset(dst_filev, 'a', format='NETCDF4')

    time = cdf.variables['time'][zero:l_time]
    time=time-time[0]
    print time
    src_varu = cdf.variables['vozocrtx'][0,:,:,:]
    src_varv = cdf.variables['vomecrty'][0,:,:,:]

    #get missing value
    spval = -32767 #src_varu._FillValue

    # get weights file
    wts_file = 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' %(grid_name)

    # build intermediate zgrid
    zlevel = -src_grd.z_t[::-1,0,0]
    nzlevel = len(zlevel)
    dst_zcoord = pyroms.vgrid.z_coordinate(dst_grd.vgrid.h, zlevel, nzlevel)
    dst_grdz = pyroms.grid.ROMS_Grid(dst_grd.name+'_Z', dst_grd.hgrid, dst_zcoord)

    # create variable in destination file

    ncu.createDimension('v3d_time', l_time-zero)			####
    ncu.createDimension('v2d_time', l_time-zero)			####

    ncu.createVariable('v3d_time', 'f8', ('v3d_time'))
    ncu.variables['v3d_time'].long_name = '3D momentum time'
    ncu.variables['v3d_time'].units = 'days since 2004-01-01 00:00:00 GMT'
    ncu.variables['v3d_time'].calendar = 'gregorian'
    #ncu.variables['v3d_time']._FillValue = spval

    ncu.createVariable('v2d_time', 'f8', ('v2d_time'))
    ncu.variables['v2d_time'].long_name = '2D momentum time'
    ncu.variables['v2d_time'].units = 'days since 2004-01-01 00:00:00 GMT'
    ncu.variables['v2d_time'].calendar = 'gregorian'
    #ncu.variables['v2d_time']._FillValue = spval

    print 'Creating variable u_north'
    ncu.createVariable('u_north', 'f8', ('v3d_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_north'].long_name = '3D u-momentum north boundary condition'
    ncu.variables['u_north'].units = 'meter second-1'
    ncu.variables['u_north'].field = 'u_north, scalar, series'
    #ncu.variables['u_north']._FillValue = spval

    print 'Creating variable u_south'
    ncu.createVariable('u_south', 'f8', ('v3d_time', 's_rho', 'xi_u'), fill_value=spval)
    ncu.variables['u_south'].long_name = '3D u-momentum south boundary condition'
    ncu.variables['u_south'].units = 'meter second-1'
    ncu.variables['u_south'].field = 'u_south, scalar, series'
    #ncu.variables['u_south']._FillValue = spval

    print 'Creating variable u_east'
    ncu.createVariable('u_east', 'f8', ('v3d_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_east'].long_name = '3D u-momentum east boundary condition'
    ncu.variables['u_east'].units = 'meter second-1'
    ncu.variables['u_east'].field = 'u_east, scalar, series'
    #ncu.variables['u_east']._FillValue = spval
    print 'Creating variable u_west'
    ncu.createVariable('u_west', 'f8', ('v3d_time', 's_rho', 'eta_u'), fill_value=spval)
    ncu.variables['u_west'].long_name = '3D u-momentum west boundary condition'
    ncu.variables['u_west'].units = 'meter second-1'
    ncu.variables['u_west'].field = 'u_east, scalar, series'
    #ncu.variables['u_west']._FillValue = spval

    # create variable in destination file
    print 'Creating variable ubar_north'
    ncu.createVariable('ubar_north', 'f8', ('v2d_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_north'].long_name = '2D u-momentum north boundary condition'
    ncu.variables['ubar_north'].units = 'meter second-1'
    ncu.variables['ubar_north'].field = 'ubar_north, scalar, series'
    #ncu.variables['ubar_north']._FillValue = spval

    print 'Creating variable ubar_south'
    ncu.createVariable('ubar_south', 'f8', ('v2d_time', 'xi_u'), fill_value=spval)
    ncu.variables['ubar_south'].long_name = '2D u-momentum south boundary condition'
    ncu.variables['ubar_south'].units = 'meter second-1'
    ncu.variables['ubar_south'].field = 'ubar_south, scalar, series'
    #ncu.variables['ubar_south']._FillValue = spval

    print 'Creating variable ubar_east'
    ncu.createVariable('ubar_east', 'f8', ('v2d_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_east'].long_name = '2D u-momentum east boundary condition'
    ncu.variables['ubar_east'].units = 'meter second-1'
    ncu.variables['ubar_east'].field = 'ubar_east, scalar, series'
    #ncu.variables['ubar_east']._FillValue = spval
    print 'Creating variable ubar_west'
    ncu.createVariable('ubar_west', 'f8', ('v2d_time', 'eta_u'), fill_value=spval)
    ncu.variables['ubar_west'].long_name = '2D u-momentum west boundary condition'
    ncu.variables['ubar_west'].units = 'meter second-1'
    ncu.variables['ubar_west'].field = 'ubar_east, scalar, series'
    #ncu.variables['ubar_west']._FillValue = spval

    ncv.createDimension('v3d_time', l_time-zero)			###
    ncv.createDimension('v2d_time', l_time-zero)			###

    ncv.createVariable('v3d_time', 'f8', ('v3d_time'))
    ncv.variables['v3d_time'].long_name = '3D momentum time'
    ncv.variables['v3d_time'].units = 'days since 2004-01-01 00:00:00 GMT'
    ncv.variables['v3d_time'].calendar = 'gregorian'
    #ncu.variables['v3d_time']._FillValue = spval

    ncv.createVariable('v2d_time', 'f8', ('v2d_time'))
    ncv.variables['v2d_time'].long_name = '2D momentum time'
    ncv.variables['v2d_time'].units = 'days since 2004-01-01 00:00:00 GMT'
    ncv.variables['v2d_time'].calendar = 'gregorian'
    #ncu.variables['v2d_time']._FillValue = spval


    print 'Creating variable v_north'
    ncv.createVariable('v_north', 'f8', ('v3d_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_north'].long_name = '3D v-momentum north boundary condition'
    ncv.variables['v_north'].units = 'meter second-1'
    ncv.variables['v_north'].field = 'v_north, scalar, series'
    #ncv.variables['v_north']._FillValue = spval

    print 'Creating variable v_south'
    ncv.createVariable('v_south', 'f8', ('v3d_time', 's_rho', 'xi_v'), fill_value=spval)
    ncv.variables['v_south'].long_name = '3D v-momentum south boundary condition'
    ncv.variables['v_south'].units = 'meter second-1'
    ncv.variables['v_south'].field = 'v_south, scalar, series'
    #ncv.variables['v_south']._FillValue = spval

    print 'Creating variable v_east'
    ncv.createVariable('v_east', 'f8', ('v3d_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_east'].long_name = '3D v-momentum east boundary condition'
    ncv.variables['v_east'].units = 'meter second-1'
    ncv.variables['v_east'].field = 'v_east, scalar, series'
    #ncv.variables['v_east']._FillValue = spval
    print 'Creating variable v_west'
    ncv.createVariable('v_west', 'f8', ('v3d_time', 's_rho', 'eta_v'), fill_value=spval)
    ncv.variables['v_west'].long_name = '3D v-momentum west boundary condition'
    ncv.variables['v_west'].units = 'meter second-1'
    ncv.variables['v_west'].field = 'v_east, scalar, series'
    #ncv.variables['v_west']._FillValue = spval

    print 'Creating variable vbar_north'
    ncv.createVariable('vbar_north', 'f8', ('v2d_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_north'].long_name = '2D v-momentum north boundary condition'
    ncv.variables['vbar_north'].units = 'meter second-1'
    ncv.variables['vbar_north'].field = 'vbar_north, scalar, series'
    #ncv.variables['vbar_north']._FillValue = spval

    print 'Creating variable vbar_south'
    ncv.createVariable('vbar_south', 'f8', ('v2d_time', 'xi_v'), fill_value=spval)
    ncv.variables['vbar_south'].long_name = '2D v-momentum south boundary condition'
    ncv.variables['vbar_south'].units = 'meter second-1'
    ncv.variables['vbar_south'].field = 'vbar_south, scalar, series'
    #ncv.variables['vbar_south']._FillValue = spval

    print 'Creating variable vbar_east'
    ncv.createVariable('vbar_east', 'f8', ('v2d_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_east'].long_name = '2D v-momentum east boundary condition'
    ncv.variables['vbar_east'].units = 'meter second-1'
    ncv.variables['vbar_east'].field = 'vbar_east, scalar, series'
    #ncv.variables['vbar_east']._FillValue = spval
    print 'Creating variable vbar_west'
    ncv.createVariable('vbar_west', 'f8', ('v2d_time', 'eta_v'), fill_value=spval)
    ncv.variables['vbar_west'].long_name = '2D v-momentum west boundary condition'
    ncv.variables['vbar_west'].units = 'meter second-1'
    ncv.variables['vbar_west'].field = 'vbar_east, scalar, series'
    #ncv.variables['vbar_west']._FillValue = spval





    dst_u_north=np.ma.zeros((l_time-zero, cw, Lp-1))
    dst_u_south=np.ma.zeros((l_time-zero, cw, Lp-1))
    dst_u_east=np.ma.zeros((l_time-zero, cw, Mp))
    dst_u_west=np.ma.zeros((l_time-zero, cw, Mp))

    dst_v_north=np.ma.zeros((l_time-zero, cw,  Lp))
    dst_v_south=np.ma.zeros((l_time-zero, cw,  Lp))
    dst_v_east=np.ma.zeros((l_time-zero, cw, Mp-1))
    dst_v_west=np.ma.zeros((l_time-zero, cw, Mp-1))

    dst_ubar_north=np.ma.zeros((l_time-zero, Lp-1))
    dst_ubar_south=np.ma.zeros((l_time-zero, Lp-1))
    dst_ubar_east=np.ma.zeros((l_time-zero, Mp))
    dst_ubar_west=np.ma.zeros((l_time-zero, Mp))


    dst_vbar_north=np.ma.zeros((l_time-zero, Lp))
    dst_vbar_south=np.ma.zeros((l_time-zero, Lp))
    dst_vbar_east=np.ma.zeros((l_time-zero, Mp-1))
    dst_vbar_west=np.ma.zeros((l_time-zero, Mp-1))

    for m in range(len(time)):
        src_uz = flood(cdf.variables['vozocrtx'][m,:,:,:], src_grd,  spval=spval)
        src_vz = flood(cdf.variables['vomecrty'][m,:,:,:], src_grd,  spval=spval)
        dst_uz = pyroms.remapping.remap(src_uz, wts_file, spval=spval)
        dst_vz = pyroms.remapping.remap(src_vz, wts_file, spval=spval)

	dst_u_north_cont = pyroms.remapping.z2roms(dst_uz[::-1, Mp-2:Mp, 0:Lp], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(0,Lp), jrange=(Mp-2,Mp))
	#print np.shape(dst_u_north)
	dst_u_south_cont = pyroms.remapping.z2roms(dst_uz[::-1, 0:2, 0:Lp], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(0,Lp), jrange=(0,2))
	dst_u_east_cont = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, Lp-2:Lp], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(Lp-2,Lp), jrange=(0,Mp))
	dst_u_west_cont = pyroms.remapping.z2roms(dst_uz[::-1, 0:Mp, 0:2], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(0,2), jrange=(0,Mp))

	dst_v_north_cont = pyroms.remapping.z2roms(dst_vz[::-1, Mp-2:Mp, 0:Lp], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(0,Lp), jrange=(Mp-2,Mp))
	dst_v_south_cont = pyroms.remapping.z2roms(dst_vz[::-1, 0:2, 0:Lp], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(0,Lp), jrange=(0,2))
	dst_v_east_cont = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, Lp-2:Lp], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(Lp-2,Lp), jrange=(0,Mp))
	dst_v_west_cont = pyroms.remapping.z2roms(dst_vz[::-1, 0:Mp, 0:2], dst_grdz, dst_grd, Cpos='rho', spval=spval, flood=True, irange=(0,2), jrange=(0,Mp))
	#print dst_u_south_cont.min(), dst_u_south_cont.max()

	src_angle = pyroms.remapping.remap(src_grd.angle, 'remap_weights_PUSSY_to_%s_bilinear_t_to_rho.nc' %(grid_name), spval=spval) 
	dst_angle = dst_grd.hgrid.angle_rho
	angle = dst_angle - src_angle
	angle = np.tile(angle, (dst_grd.vgrid.N, 1, 1))

	U_north = dst_u_north_cont + dst_v_north_cont*1j
	eitheta_north = np.exp(-1j*angle[:,Mp-2:Mp, 0:Lp])
	U_north = U_north * eitheta_north
	dst_u_north_cont = np.real(U_north)
	dst_v_north_cont = np.imag(U_north)

	U_south = dst_u_south_cont + dst_v_south_cont*1j
	eitheta_south = np.exp(-1j*angle[:,0:2, 0:Lp])
	U_south = U_south * eitheta_south
	dst_u_south_cont = np.real(U_south)
	dst_v_south_cont = np.imag(U_south)

	U_east = dst_u_east_cont + dst_v_east_cont*1j
	eitheta_east = np.exp(-1j*angle[:,0:Mp, Lp-2:Lp])
	U_east = U_east * eitheta_east
	dst_u_east_cont = np.real(U_east)
	dst_v_east_cont = np.imag(U_east)

	U_west = dst_u_west_cont + dst_v_west_cont*1j
	eitheta_west = np.exp(-1j*angle[:,0:Mp, 0:2])
	U_west = U_west * eitheta_west
	dst_u_west_cont = np.real(U_west)
	dst_v_west_cont = np.imag(U_west)

	dst_u_north_cont = 0.5 * np.squeeze(dst_u_north_cont[:,-1,:-1] + dst_u_north_cont[:,-1,1:])
	dst_v_north_cont = 0.5 * np.squeeze(dst_v_north_cont[:,:-1,:] + dst_v_north_cont[:,1:,:])
	dst_u_south_cont = 0.5 * np.squeeze(dst_u_south_cont[:,0,:-1] + dst_u_south_cont[:,0,1:])
	dst_v_south_cont = 0.5 * np.squeeze(dst_v_south_cont[:,:-1,:] + dst_v_south_cont[:,1:,:])
	dst_u_east_cont = 0.5 * np.squeeze(dst_u_east_cont[:,:,:-1] + dst_u_east_cont[:,:,1:])
	dst_v_east_cont = 0.5 * np.squeeze(dst_v_east_cont[:,:-1,-1] + dst_v_east_cont[:,1:,-1])
	dst_u_west_cont = 0.5 * np.squeeze(dst_u_west_cont[:,:,:-1] + dst_u_west_cont[:,:,1:])
	dst_v_west_cont = 0.5 * np.squeeze(dst_v_west_cont[:,:-1,0] + dst_v_west_cont[:,1:,0])
	#print dst_u_south_cont.min(), dst_u_south_cont.max()

	idxu_north = np.where(dst_grd.hgrid.mask_u[-1,:] == 0)
	idxv_north = np.where(dst_grd.hgrid.mask_v[-1,:] == 0)
	idxu_south = np.where(dst_grd.hgrid.mask_u[0,:] == 0)
	idxv_south = np.where(dst_grd.hgrid.mask_v[0,:] == 0)
	idxu_east = np.where(dst_grd.hgrid.mask_u[:,-1] == 0)
	idxv_east = np.where(dst_grd.hgrid.mask_v[:,-1] == 0)
	idxu_west = np.where(dst_grd.hgrid.mask_u[:,0] == 0)
	idxv_west = np.where(dst_grd.hgrid.mask_v[:,0] == 0)
	for n in range(dst_grd.vgrid.N): 
		dst_u_north_cont[n, idxu_north[0]] = spval
        	dst_v_north_cont[n, idxv_north[0]] = spval
        	dst_u_south_cont[n, idxu_south[0]] = spval
        	dst_v_south_cont[n, idxv_south[0]] = spval
        	dst_u_east_cont[n, idxu_east[0]] = spval
        	dst_v_east_cont[n, idxv_east[0]] = spval
        	dst_u_west_cont[n, idxu_west[0]] = spval
        	dst_v_west_cont[n, idxv_west[0]] = spval

	z_u_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:-1] + dst_grd.vgrid.z_w[0,:,-1,1:])
	z_v_north = 0.5 * (dst_grd.vgrid.z_w[0,:,-1,:] + dst_grd.vgrid.z_w[0,:,-2,:])
	z_u_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:-1] + dst_grd.vgrid.z_w[0,:,0,1:])
	z_v_south = 0.5 * (dst_grd.vgrid.z_w[0,:,0,:] + dst_grd.vgrid.z_w[0,:,1,:])
	z_u_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:,-1] + dst_grd.vgrid.z_w[0,:,:,-2])
	z_v_east = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,-1] + dst_grd.vgrid.z_w[0,:,1:,-1])
	z_u_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:,0] + dst_grd.vgrid.z_w[0,:,:,1])
	z_v_west = 0.5 * (dst_grd.vgrid.z_w[0,:,:-1,0] + dst_grd.vgrid.z_w[0,:,1:,0])


	dst_ubar_north_cont = np.ma.zeros(dst_u_north_cont.shape[1])
	dst_ubar_south_cont = np.ma.zeros(dst_u_south_cont.shape[1])
	dst_ubar_east_cont = np.ma.zeros(dst_u_east_cont.shape[1])
	dst_ubar_west_cont = np.ma.zeros(dst_u_west_cont.shape[1])
	dst_vbar_north_cont = np.ma.zeros(dst_v_north_cont.shape[1])
	dst_vbar_south_cont = np.ma.zeros(dst_v_south_cont.shape[1])
	dst_vbar_east_cont = np.ma.zeros(dst_v_east_cont.shape[1])
	dst_vbar_west_cont = np.ma.zeros(dst_v_west_cont.shape[1])


	for i in range(dst_u_north_cont.shape[1]):
        	dst_ubar_north_cont[i] = (dst_u_north_cont[:,i] * np.diff(z_u_north[:,i])).sum() / -z_u_north[0,i]
	for i in range(dst_v_north_cont.shape[1]):
        	dst_vbar_north_cont[i] = (dst_v_north_cont[:,i] * np.diff(z_v_north[:,i])).sum() / -z_v_north[0,i]
	for i in range(dst_u_south_cont.shape[1]):
        	dst_ubar_south_cont[i] = (dst_u_south_cont[:,i] * np.diff(z_u_south[:,i])).sum() / -z_u_south[0,i]
	for i in range(dst_v_south_cont.shape[1]):
        	dst_vbar_south_cont[i] = (dst_v_south_cont[:,i] * np.diff(z_v_south[:,i])).sum() / -z_v_south[0,i]
	for j in range(dst_u_east_cont.shape[1]):
        	dst_ubar_east_cont[j] = (dst_u_east_cont[:,j] * np.diff(z_u_east[:,j])).sum() / -z_u_east[0,j]
        	dst_ubar_west_cont[j] = (dst_u_west_cont[:,j] * np.diff(z_u_west[:,j])).sum() / -z_u_west[0,j]
	for j in range(dst_v_east_cont.shape[1]):
        	dst_vbar_east_cont[j] = (dst_v_east_cont[:,j] * np.diff(z_v_east[:,j])).sum() / -z_v_east[0,j]
        	dst_vbar_west_cont[j] = (dst_v_west_cont[:,j] * np.diff(z_v_west[:,j])).sum() / -z_v_west[0,j]

	#print dst_ubar_south_cont.min()

	dst_ubar_north[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_u[-1,:] == 0, dst_ubar_north_cont)   
	dst_ubar_south[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_u[0,:] == 0, dst_ubar_south_cont)   
	dst_ubar_east[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_u[:,-1] == 0, dst_ubar_east_cont)   
	dst_ubar_west[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_u[:,0] == 0, dst_ubar_west_cont)   
	dst_vbar_north[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_v[-1,:] == 0, dst_vbar_north_cont)   
	dst_vbar_south[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_v[0,:] == 0, dst_vbar_south_cont)   
	dst_vbar_east[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_v[:,-1] == 0, dst_vbar_east_cont)   
	dst_vbar_west[m,:] = np.ma.masked_where(dst_grd.hgrid.mask_v[:,0] == 0, dst_vbar_west_cont)  


	#dst_ubar_north[m,:]=dst_ubar_north_cont
	#dst_ubar_south[m,:]=dst_ubar_south_cont
	#dst_ubar_east[m,:]=dst_ubar_east_cont
	#dst_ubar_west[m,:]=dst_ubar_west_cont

	#dst_vbar_north[m,:]=dst_vbar_north_cont
	#dst_vbar_south[m,:]=dst_vbar_south_cont
	#dst_vbar_east[m,:]=dst_vbar_east_cont
	#dst_vbar_west[m,:]=dst_vbar_west_cont

        #print m
	dst_u_north[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_u[-1,:],(cw,1)) == 0, dst_u_north_cont)
	dst_u_south[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_u[0,:],(cw,1)) == 0,dst_u_south_cont)
	dst_u_east[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_u[:,-1],(cw,1)) == 0,dst_u_east_cont)
	dst_u_west[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_u[:,0],(cw,1)) == 0,dst_u_west_cont)

	dst_v_north[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_v[-1,:],(cw,1)) == 0,dst_v_north_cont)
	dst_v_south[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_v[0,:],(cw,1)) == 0,dst_v_south_cont)
	dst_v_east[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_v[:,-1],(cw,1)) == 0,dst_v_east_cont)
	dst_v_west[m,:,:]=np.ma.masked_where(np.tile(dst_grd.hgrid.mask_v[:,0],(cw,1)) == 0,dst_v_west_cont)
	print m, dst_u_south[m].min(), dst_u_south[m].max(), dst_ubar_south[m,:].min(), dst_ubar_south[m,:].max()#, dst_ubar_south[-1], sum(dst_u_south[:,-1])
	#print np.shape(dst_u_south_cont)
	#if not int(dst_ubar_south[m,:].min()) == spval:
	#	break


    # write data in destination file
    print 'write data in destination file'
    ncu.variables['v2d_time'][:] = time####np.concatenate((time,time+365,time+365+365,time+365+365+365,time+365+365+365+365),axis=0)*60*60*24####
    ncu.variables['v3d_time'][:] = time####np.concatenate((time,time+365,time+365+365,time+365+365+365,time+365+365+365+365),axis=0)*60*60*24####
    ncu.variables['u_north'][:] = dst_u_north####np.concatenate((dst_u_north,dst_u_north,dst_u_north,dst_u_north,dst_u_north),axis=0) ####dst_u_north####
    ncu.variables['u_south'][:] = dst_u_south####np.concatenate((dst_u_south,dst_u_south,dst_u_south,dst_u_south,dst_u_south),axis=0)####dst_u_south####
    ncu.variables['u_east'][:] = dst_u_east####np.concatenate((dst_u_east,dst_u_east,dst_u_east,dst_u_east,dst_u_east),axis=0)####dst_u_east####
    ncu.variables['u_west'][:] = dst_u_west####np.concatenate((dst_u_west,dst_u_west,dst_u_west,dst_u_west,dst_u_west),axis=0)####dst_u_west####
    ncu.variables['ubar_north'][:] = dst_ubar_north####np.concatenate((dst_ubar_north,dst_ubar_north,dst_ubar_north,dst_ubar_north,dst_ubar_north),axis=0)####dst_ubar_north####
    ncu.variables['ubar_south'][:] = dst_ubar_south####np.concatenate((dst_ubar_south,dst_ubar_south,dst_ubar_south,dst_ubar_south,dst_ubar_south),axis=0)####dst_ubar_south####
    ncu.variables['ubar_east'][:] = dst_ubar_east####np.concatenate((dst_ubar_east,dst_ubar_east,dst_ubar_east,dst_ubar_east,dst_ubar_east),axis=0)####dst_ubar_east####
    ncu.variables['ubar_west'][:] = dst_ubar_west####np.concatenate((dst_ubar_west,dst_ubar_west,dst_ubar_west,dst_ubar_west,dst_ubar_west),axis=0)####dst_ubar_west####

    ncv.variables['v2d_time'][:] = time###np.concatenate((time,time+365,time+365+365,time+365+365+365,time+365+365+365+365),axis=0)*60*60*24####
    ncv.variables['v3d_time'][:] = time###np.concatenate((time,time+365,time+365+365,time+365+365+365,time+365+365+365+365),axis=0)*60*60*24####
    ncv.variables['v_north'][:] = dst_v_north####np.concatenate((dst_v_north,dst_v_north,dst_v_north,dst_v_north,dst_v_north),axis=0)####dst_v_north####
    ncv.variables['v_south'][:] = dst_v_south####np.concatenate((dst_v_south,dst_v_south,dst_v_south,dst_v_south,dst_v_south),axis=0)####dst_v_south####
    ncv.variables['v_east'][:] = dst_v_east####np.concatenate((dst_v_east,dst_v_east,dst_v_east,dst_v_east,dst_v_east),axis=0)####dst_v_east####
    ncv.variables['v_west'][:] = dst_v_west####np.concatenate((dst_v_west,dst_v_west,dst_v_west,dst_v_west,dst_v_west),axis=0)####dst_v_west####
    ncv.variables['vbar_north'][:] = dst_vbar_north####np.concatenate((dst_vbar_north,dst_vbar_north,dst_vbar_north,dst_vbar_north,dst_vbar_north),axis=0)####dst_vbar_north####
    ncv.variables['vbar_south'][:] = dst_vbar_south####np.concatenate((dst_vbar_south,dst_vbar_south,dst_vbar_south,dst_vbar_south,dst_vbar_south),axis=0)####dst_vbar_south####
    ncv.variables['vbar_east'][:] = dst_vbar_east####np.concatenate((dst_vbar_east,dst_vbar_east,dst_vbar_east,dst_vbar_east,dst_vbar_east),axis=0)####dst_vbar_east####
    ncv.variables['vbar_west'][:] = dst_vbar_west####np.concatenate((dst_vbar_west,dst_vbar_west,dst_vbar_west,dst_vbar_west,dst_vbar_west),axis=0)####dst_vbar_west####

    # close file
    ncu.close()
    ncv.close()
    cdf.close()
Example #12
0
                is_done = True
            elif e.key == K_r:
                initialize()
            elif e.key in keycolors:
                color = keycolors[e.key]

        if color != None and movecount < 25:
            if not for_restart:
                movecount += 1
                tile = pygame.Surface(TILE_SIZE)
                tile.fill(rgb[color])
                for coord in flooded_list:
                    color_of_tile[coord] = color

                # This is the function the students will write. -Jeremy
                flood(color_of_tile, flooded_list)

                for i in range(len(flooded_list)):
                    screen.blit(tile, flooded_list[i])

                # drought (new feature, disabled for now) -Jeremy
                if False and len(flooded_list) > 1 and random.randint(1,
                                                                      5) == 1:
                    display.set_caption('Flood-it! Drought in progress!')
                    movecount -= 1
                    num_remove = len(flooded_list) / 10
                    drought_tiles = create_drought(flooded_list, color_of_tile)
                    for coord in drought_tiles:
                        tile.fill(rgb[color_of_tile[coord]])
                        screen.blit(tile, coord)
                else: