示例#1
0
def main():
    size = 4096
    bbox = [(0,0),(0,size),(size,size),(size,0)]

    centers, neighbors, vertices, regions = getVoronoi(size, bbox)

    vert_neighbors = [[] for i in vertices]
    vert_regions = [[] for i in vertices]
    for r, p in enumerate(regions):
        for i, v in enumerate(p[:-1]):
            vert_regions[v].append(r)
            if p[i-1] not in vert_neighbors[v]:
                vert_neighbors[v].append(p[i-1])
            if p[i+1] not in vert_neighbors[v]:
                vert_neighbors[v].append(p[i+1])

    cell_type = getBasicShape(size, neighbors, vertices, regions, 32268)

    dist_to_coast = getDistsToCoast(vertices, vert_regions, 
            vert_neighbors, cell_type)


    patches = [Polygon(vertices[p], True, ec='k') for p in regions]

    patchCol = PatchCollection(patches, cmap=plt.get_cmap('terrain'))

    patchCol.set_clim(0, 1)
    patchCol.set_antialiased(False)

    fig, ax = plt.subplots()

    ax.add_collection(patchCol)

    ax.set_aspect('equal')
    ax.set_xlim(0, size)
    ax.set_ylim(0, size)
    plt.tight_layout()
    plt.axis('off')

    for i in range(100):
        seed = datetime.now().microsecond

        colors = getTerrain(size, vertices, regions, cell_type, dist_to_coast, seed)
        
        patchCol.set_array(np.array(colors))

        plt.savefig('terrains/%06d.png' % seed, format='png', dpi=1200)
示例#2
0
def cvshade(clon,clat,valsin,proj='cyl',lon0=215,res='c',blat=30,fz=(11.6,5.8),add=None,cbticksize=12,cbticks=None,nocb=None,vlo=None,vhi=None,lat0=None,wid=12000000,ht=8000000,**kwargs):
	from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic
	from mcmath import edges
	from matplotlib.patches import Polygon
	from matplotlib.collections import PatchCollection
	from ferr import use

##	dgrid = use('/scratch/local2/u241180/data/mill/MPI_lon-lat-pressure-points_ocean-grid.nc',silent=1)
##	clon = dgrid.v['grid_center_lon'][:]
##	clat = dgrid.v['grid_center_lat'][:]
##	clon_crnr = dgrid.v['grid_corner_lon'][:]
##	clat_crnr = dgrid.v['grid_corner_lat'][:]

	if clon.shape[0] == 4 and clat.shape[0] == 4:
		clat = np.transpose(clat,(1,2,0))
		clon = np.transpose(clon,(1,2,0))

	clonc = clon.reshape((-1,4))
	clatc = clat.reshape((-1,4))

	clonc1 = np.where(clonc < 35, clonc + 360, clonc)
	clonc2 = np.empty_like(clonc1)
	clatc2 = clatc.copy()
	lhs_x = np.empty((0,4),dtype=np.float32)
	lhs_y = np.empty((0,4),dtype=np.float32)
	lhs_val = np.empty(0,dtype=np.float32)
	val_flat = valsin.copy()
	if isinstance(valsin,np.ma.MaskedArray):
		val_flat[val_flat.mask] = np.nan
	val_flat = val_flat.flatten()

	for ii in xrange(clonc1.shape[0]):
		clonc2[ii] = clonc1[ii]
		if ((clonc1[ii] > 350).any() & (clonc1[ii] < 50).any()):
			clonc2[ii] = np.where(clonc1[ii] < 50, 395., clonc1[ii])
			lhs_x = np.append(lhs_x,np.where(clonc1[ii] > 50,35.,clonc1[ii]).reshape(1,-1),axis=0)
			lhs_y = np.append(lhs_y,clatc2[ii].reshape(1,-1),axis=0)
			lhs_val = np.append(lhs_val,val_flat[ii])

	val2 = np.append(val_flat,lhs_val)
	if isinstance(valsin,np.ma.MaskedArray):
		val2 = np.ma.masked_invalid(val2)
	clonc2 = np.append(clonc2,lhs_x,axis=0)
	clatc2 = np.append(clatc2,lhs_y,axis=0)

	if proj == 'cyl':
		m1 = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
					 llcrnrlon=35,urcrnrlon=395,resolution='c')
	elif proj == 'moll':
		m1 = Basemap(projection='moll',lon_0=lon0)
	elif proj == 'npl':
		m1 = Basemap(projection='nplaea',boundinglat=blat,lon_0=lon0,resolution='l')
	elif proj == 'spl':
		m1 = Basemap(projection='splaea',boundinglat=blat,lon_0=lon0,resolution='l')
	elif proj == 'laea':
		if (lat0 is None):
			raise MCPlotError("central latitude not specified")
		m1 = Basemap(width=wid,height=ht,resolution='l',projection='laea',\
            lat_ts=lat0,lat_0=lat0,lon_0=lon0)
	else:
		raise MCPlotError("no proj %s found!" % proj)

	if add is None:
		fig = plt.figure(figsize=fz)
		ax = fig.add_axes((0.05,0.05,0.8,0.9),autoscale_on=False)
	else:
		fig = plt.gcf()
		ax = plt.gca()

	patches = np.empty(clonc2.shape[0],dtype=object)

	for ii in xrange(clonc2.shape[0]):
		xx1 = clonc2[ii]
		yy1 = clatc2[ii]
		xx,yy = m1(xx1,yy1)
		indx = np.array(zip(xx,yy))
		patches[ii] = Polygon(indx, True)

	p1 = PatchCollection(patches, edgecolors='none', linewidths=0,**kwargs)

	p1.set_array(val2)
	if ((vlo is not None) & (vhi is not None)):
		p1.set_clim(vmin=vlo,vmax=vhi)
	p1.set_antialiased(False)
	m1.drawmapboundary()
##	ax = gca()
	ax.add_collection(p1)
	m1.drawcoastlines()
	
	if not bool(nocb):
		if add is None:
			ax2 = fig.add_axes((0.89,0.1,0.02,0.8),autoscale_on=False)
			if cbticks is None:
				plt.colorbar(p1,cax=ax2,ax=ax,extend='both')
			else:
				plt.colorbar(p1,cax=ax2,ax=ax,extend='both',ticks=cbticks)
		else:
			bbox1 = ax.get_position()
			endx = bbox1.get_points()[1,0]
			endy = bbox1.get_points()[1,1]
			begy = bbox1.get_points()[0,1]
			begx = bbox1.get_points()[0,0]
			yext = 0.9*(endy - begy)
			xleft = endx - begx
			xspacer = 0.005
			yspacer = 0.02
			xext = 0.03*xleft
##			if xext > (0.08*yext):
##				xext = 0.08*yext
			ax2 = fig.add_axes((endx+xspacer,begy+yspacer,xext,yext),autoscale_on=False)
			if cbticks is None:
				plt.colorbar(p1,cax=ax2,ax=ax,extend='both')
			else:
				plt.colorbar(p1,cax=ax2,ax=ax,extend='both',ticks=cbticks)
		if cbticksize is not None:
			ytl = ax2.get_yticklabels()
			plt.setp(ytl,'size',cbticksize)

	return m1,p1
示例#3
0
def cvshade(clon,
            clat,
            valsin,
            proj='cyl',
            lon0=215,
            res='c',
            blat=30,
            fz=(11.6, 5.8),
            add=None,
            cbticksize=12,
            cbticks=None,
            nocb=None,
            vlo=None,
            vhi=None,
            lat0=None,
            wid=12000000,
            ht=8000000,
            land1=None,
            land2='blank',
            landmask=None,
            landdark=None,
            hatchmask=None,
            hatchalpha=None,
            **kwargs):
    """An increasingly complicated function for generating decent graphs of shaded contour plots
	on the surface of the earth.  This version is really only designed to work with rectilinear
	grids.  Placement of colorbars in multi-panel figures has proven to be a big problem, and more
	parameters now exist to try to manage this better in multiple circumstances.
	Params: xin - longtitude array of data (1-d)
	        yin - latitude array of data (1-d)
		valsin - data to shade
		proj - projection to employ,
		       currently only the following are enabled: cyl, moll, npl, spl, laea, robin
		lon0 - central longitude meridian for plot
		res - same as in Basemap
		blat - bounding latitude for polar projections: npl,spl
		fz - tuple for figure size
		add - add the shade plot to current axes instead of making a new figure
		cbticksize, cbticks - self-explanatory, hopefully
		nocb - don't auto-add a colorbar

		land1 - does a continent fill for the map instead of plotting/shading a land mask like 'landmask':
		        None by default
		land2 - does a background fill for named color; background color by default
		        if None, no fill is done for the map boundary at all, nor for continents
		hatchmask - required for either of the two hatching methods; needs to be a MaskedArray,
		            and not just a mask (not just a boolean array)
			"""

    from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic
    from mcmath import edges
    from matplotlib.patches import Polygon
    from matplotlib.collections import PatchCollection
    from ferr import use

    if clon.shape[0] == 4 and clat.shape[0] == 4:
        clat = np.transpose(clat, (1, 2, 0))
        clon = np.transpose(clon, (1, 2, 0))

    clonc = clon.reshape((-1, 4))
    clatc = clat.reshape((-1, 4))

    lon = clonc.mean(axis=1)
    lat = clatc.mean(axis=1)

    clonc1 = np.where(clonc < 35, clonc + 360, clonc)
    clonc2 = np.empty_like(clonc1)
    clatc2 = clatc.copy()
    lhs_x = np.zeros((4000, 4), dtype=np.float32)
    lhs_y = np.zeros((4000, 4), dtype=np.float32)
    lhs_val = np.zeros(4000, dtype=np.float32)
    val_flat = valsin.copy()
    if isinstance(valsin, np.ma.MaskedArray):
        val_flat[val_flat.mask] = np.nan
    val_flat = val_flat.flatten()

    if hatchmask is not None:
        hatch_flat = hatchmask.copy()
        hatch_flat[hatch_flat.mask] = np.nan
        hatch_flat = hatch_flat.flatten()
        lhs_hatch = np.zeros(4000, dtype=np.float32)

    if landmask is not None:
        land_flat = landmask.copy()
        land_flat[land_flat.mask] = np.nan
        land_flat = land_flat.flatten()
        lhs_land = np.zeros(4000, dtype=np.float32)

    final_size = 0

    for ii in xrange(clonc1.shape[0]):
        clonc2[ii] = clonc1[ii]
        if ((clonc1[ii] > 350).any() & (clonc1[ii] < 50).any()):
            clonc2[ii] = np.where(clonc1[ii] < 50, 395., clonc1[ii])
            lhs_x[final_size] = np.where(clonc1[ii] > 50, 35.,
                                         clonc1[ii]).reshape(1, -1)
            lhs_y[final_size] = clatc2[ii].reshape(1, -1)
            lhs_val[final_size] = val_flat[ii]
            if hatchmask is not None:
                lhs_hatch[final_size] = hatch_flat[ii]
            if landmask is not None:
                lhs_land[final_size] = land_flat[ii]
            final_size = final_size + 1

    val2 = np.r_[val_flat, lhs_val[:final_size]]
    if isinstance(valsin, np.ma.MaskedArray):
        val2 = np.ma.masked_invalid(val2)
    clonc2 = np.r_['0,2,0', clonc2, lhs_x[:final_size]]
    clatc2 = np.r_['0,2,0', clatc2, lhs_y[:final_size]]

    if hatchmask is not None:
        hatch2 = np.r_[hatch_flat, lhs_hatch[:final_size]]
        hatch2 = np.ma.masked_invalid(hatch2)

    if landmask is not None:
        land2 = np.r_[land_flat, lhs_land[:final_size]]
        land2 = np.ma.masked_invalid(land2)

    if add is None:
        fig = plt.figure(figsize=fz)
        ax = fig.add_axes((0.05, 0.05, 0.8, 0.9), autoscale_on=False)
    else:
        fig = plt.gcf()
        ax = plt.gca()

    if proj == 'cyl':
        m1 = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
            llcrnrlon=35,urcrnrlon=395,resolution='c')
    elif proj == 'moll':
        m1 = Basemap(projection='moll', lon_0=215, resolution='c')
    elif proj == 'robin':
        m1 = Basemap(projection='robin', lon_0=215, resolution='c')
    elif proj == 'npl':
        m1 = Basemap(projection='nplaea',
                     boundinglat=blat,
                     lon_0=lon0,
                     resolution='l')
    elif proj == 'spl':
        m1 = Basemap(projection='splaea',
                     boundinglat=blat,
                     lon_0=lon0,
                     resolution='l')
    elif proj == 'laea':
        if (lat0 is None):
            raise MCPlotError("central latitude not specified")
        m1 = Basemap(width=wid,height=ht,resolution='l',projection='laea',\
         lat_ts=lat0,lat_0=lat0,lon_0=lon0)
    else:
        raise MCPlotError("no proj %s found!" % proj)

    patches = np.empty(clonc2.shape[0], dtype=object)

    for ii in xrange(clonc2.shape[0]):
        xx1 = clonc2[ii]
        yy1 = clatc2[ii]
        xx, yy = m1(xx1, yy1)
        indx = np.array(zip(xx, yy))
        patches[ii] = Polygon(indx, True)

    p1 = PatchCollection(patches, edgecolors='none', **kwargs)

    p1.set_array(val2)
    if ((vlo is not None) & (vhi is not None)):
        p1.set_clim(vmin=vlo, vmax=vhi)
    p1.set_antialiased(False)

    if land1 is not None:
        m1.fillcontinents(color=land1, lake_color=land1)
    if land2 == 'blank':
        m1.drawmapboundary()
    elif land2 is None:
        m1.drawmapboundary(linewidth=0, fill_color=land2)
    else:
        m1.drawmapboundary(fill_color=land2)

    ax.add_collection(p1)

    if land2 is not None:
        m1.drawcoastlines()

    if (hatchmask is not None):
        nls2 = mpl.colors.BoundaryNorm(linspace(0., 1., 11), 180)
        if hatchalpha is None:
            hatchalpha = 0.5
        p2 = PatchCollection(patches,
                             edgecolors='none',
                             facecolors='dimgrey',
                             linewidths=0,
                             zorder=2,
                             alpha=hatchalpha)
        p2.set_array(hatch2)
        ax.add_collection(p2)

    if (landmask is not None):
        if landdark is not None:
            nls2 = mpl.colors.BoundaryNorm(linspace(0., 1., 11), landdark)
        else:
            nls2 = mpl.colors.BoundaryNorm(linspace(0., 1., 11), 180)
        p3 = PatchCollection(patches,
                             edgecolors='none',
                             linewidths=0,
                             cmap=cm.Greys,
                             norm=nls2)
        p3.set_array(land2)
        ax.add_collection(p3)

    if not bool(nocb):
        if add is None:
            ax2 = fig.add_axes((0.89, 0.1, 0.02, 0.8), autoscale_on=False)
            if cbticks is None:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both')
            else:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both', ticks=cbticks)
        else:
            bbox1 = ax.get_position()
            endx = bbox1.get_points()[1, 0]
            endy = bbox1.get_points()[1, 1]
            begy = bbox1.get_points()[0, 1]
            begx = bbox1.get_points()[0, 0]
            yext = 0.9 * (endy - begy)
            xleft = endx - begx
            xspacer = 0.005
            yspacer = 0.02
            xext = 0.03 * xleft

            ax2 = fig.add_axes((endx + xspacer, begy + yspacer, xext, yext),
                               autoscale_on=False)
            if cbticks is None:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both')
            else:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both', ticks=cbticks)
        if cbticksize is not None:
            ytl = ax2.get_yticklabels()
            plt.setp(ytl, 'size', cbticksize)

    return m1, p1
示例#4
0
def cvshade(clon,
            clat,
            valsin,
            proj='cyl',
            lon0=215,
            res='c',
            blat=30,
            fz=(11.6, 5.8),
            add=None,
            cbticksize=12,
            cbticks=None,
            nocb=None,
            vlo=None,
            vhi=None,
            lat0=None,
            wid=12000000,
            ht=8000000,
            **kwargs):
    from mpl_toolkits.basemap import Basemap, shiftgrid, addcyclic
    from mcmath import edges
    from matplotlib.patches import Polygon
    from matplotlib.collections import PatchCollection
    from ferr import use

    ##	dgrid = use('/scratch/local2/u241180/data/mill/MPI_lon-lat-pressure-points_ocean-grid.nc',silent=1)
    ##	clon = dgrid.v['grid_center_lon'][:]
    ##	clat = dgrid.v['grid_center_lat'][:]
    ##	clon_crnr = dgrid.v['grid_corner_lon'][:]
    ##	clat_crnr = dgrid.v['grid_corner_lat'][:]

    if clon.shape[0] == 4 and clat.shape[0] == 4:
        clat = np.transpose(clat, (1, 2, 0))
        clon = np.transpose(clon, (1, 2, 0))

    clonc = clon.reshape((-1, 4))
    clatc = clat.reshape((-1, 4))

    clonc1 = np.where(clonc < 35, clonc + 360, clonc)
    clonc2 = np.empty_like(clonc1)
    clatc2 = clatc.copy()
    lhs_x = np.empty((0, 4), dtype=np.float32)
    lhs_y = np.empty((0, 4), dtype=np.float32)
    lhs_val = np.empty(0, dtype=np.float32)
    val_flat = valsin.copy()
    if isinstance(valsin, np.ma.MaskedArray):
        val_flat[val_flat.mask] = np.nan
    val_flat = val_flat.flatten()

    for ii in xrange(clonc1.shape[0]):
        clonc2[ii] = clonc1[ii]
        if ((clonc1[ii] > 350).any() & (clonc1[ii] < 50).any()):
            clonc2[ii] = np.where(clonc1[ii] < 50, 395., clonc1[ii])
            lhs_x = np.append(lhs_x,
                              np.where(clonc1[ii] > 50, 35.,
                                       clonc1[ii]).reshape(1, -1),
                              axis=0)
            lhs_y = np.append(lhs_y, clatc2[ii].reshape(1, -1), axis=0)
            lhs_val = np.append(lhs_val, val_flat[ii])

    val2 = np.append(val_flat, lhs_val)
    if isinstance(valsin, np.ma.MaskedArray):
        val2 = np.ma.masked_invalid(val2)
    clonc2 = np.append(clonc2, lhs_x, axis=0)
    clatc2 = np.append(clatc2, lhs_y, axis=0)

    if proj == 'cyl':
        m1 = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
            llcrnrlon=35,urcrnrlon=395,resolution='c')
    elif proj == 'moll':
        m1 = Basemap(projection='moll', lon_0=lon0)
    elif proj == 'npl':
        m1 = Basemap(projection='nplaea',
                     boundinglat=blat,
                     lon_0=lon0,
                     resolution='l')
    elif proj == 'spl':
        m1 = Basemap(projection='splaea',
                     boundinglat=blat,
                     lon_0=lon0,
                     resolution='l')
    elif proj == 'laea':
        if (lat0 is None):
            raise MCPlotError("central latitude not specified")
        m1 = Basemap(width=wid,height=ht,resolution='l',projection='laea',\
                  lat_ts=lat0,lat_0=lat0,lon_0=lon0)
    else:
        raise MCPlotError("no proj %s found!" % proj)

    if add is None:
        fig = plt.figure(figsize=fz)
        ax = fig.add_axes((0.05, 0.05, 0.8, 0.9), autoscale_on=False)
    else:
        fig = plt.gcf()
        ax = plt.gca()

    patches = np.empty(clonc2.shape[0], dtype=object)

    for ii in xrange(clonc2.shape[0]):
        xx1 = clonc2[ii]
        yy1 = clatc2[ii]
        xx, yy = m1(xx1, yy1)
        indx = np.array(zip(xx, yy))
        patches[ii] = Polygon(indx, True)

    p1 = PatchCollection(patches, edgecolors='none', linewidths=0, **kwargs)

    p1.set_array(val2)
    if ((vlo is not None) & (vhi is not None)):
        p1.set_clim(vmin=vlo, vmax=vhi)
    p1.set_antialiased(False)
    m1.drawmapboundary()
    ##	ax = gca()
    ax.add_collection(p1)
    m1.drawcoastlines()

    if not bool(nocb):
        if add is None:
            ax2 = fig.add_axes((0.89, 0.1, 0.02, 0.8), autoscale_on=False)
            if cbticks is None:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both')
            else:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both', ticks=cbticks)
        else:
            bbox1 = ax.get_position()
            endx = bbox1.get_points()[1, 0]
            endy = bbox1.get_points()[1, 1]
            begy = bbox1.get_points()[0, 1]
            begx = bbox1.get_points()[0, 0]
            yext = 0.9 * (endy - begy)
            xleft = endx - begx
            xspacer = 0.005
            yspacer = 0.02
            xext = 0.03 * xleft
            ##			if xext > (0.08*yext):
            ##				xext = 0.08*yext
            ax2 = fig.add_axes((endx + xspacer, begy + yspacer, xext, yext),
                               autoscale_on=False)
            if cbticks is None:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both')
            else:
                plt.colorbar(p1, cax=ax2, ax=ax, extend='both', ticks=cbticks)
        if cbticksize is not None:
            ytl = ax2.get_yticklabels()
            plt.setp(ytl, 'size', cbticksize)

    return m1, p1