Esempio n. 1
0
def DrawMap(title, landwidth, vx, vy, lon_min, lon_max, lat_min, lat_max, npts, x, y, z, xi, yi, grid, name, folder, cities, missing, uncovered, lakes):
    print "Generating map for %s - %s (%d points) [%f,%f - %f,%f]" % (name, folder, npts, lat_max, lon_min, lat_min, lon_max)

    # Create the basemap
    m = Basemap(projection='merc', llcrnrlon=lon_min ,llcrnrlat=lat_min, urcrnrlon=lon_max ,urcrnrlat=lat_max, resolution='i')

    # Load and draw the shapefile
    japan_shp_info = m.readshapefile(administrativeShapefile,administrativeShapefile, color='b', linewidth = landwidth)
    
    # Compute the scale for the parallels and meridians lines
    scale = min((lon_max-lon_min), (lat_max-lat_min))/4

    # Draw parallels and meridians lines
    m.drawparallels(np.arange(y.min(),y.max(),scale),labels=[1,0,0,0],color='black',dashes=[1,0],labelstyle='+/-',linewidth=0.2) # draw parallels
    m.drawmeridians(np.arange(x.min(),x.max(),scale),labels=[0,0,0,1],color='black',dashes=[1,0],labelstyle='+/-',linewidth=0.2) # draw meridians

    # Compute Safecast color map
    cmap = cmap_discretize(cm.RdYlBu_r, 16, 0.)
    if renderCPM:
      normCPM = colors.Normalize(vmin=0,vmax=350)
    else:
      normCPM = colors.Normalize(vmin=0.0,vmax=1.0)

    # Draw Safecast data on the map
    lon,lat = m(x,y)
    m.scatter(lon,lat,s=2, c=z, cmap=cmap, linewidths=0.5, alpha=0.4, norm=normCPM, zorder = 5)

    # Draw contour color map
    xim, yim = m(*np.meshgrid(xi, yi))
    levels = range(0, 400, 350/16)
    #CS = m.contour(xim,yim, grid, levels, colors='k', linewidths=0.5)
    m.contourf(xim,yim, grid, levels, cmap=cmap, norm=normCPM)

    #plt.hexbin(lon,lat, C=z, cmap=cmap, gridsize=100, norm=normCPM, marginals=False)

    # Exclude uncovered areas
    if uncovered:
      for patch in missing.geoms:
        assert patch.geom_type in ['Polygon']
        assert patch.is_valid

        if patch.area > 0.0016: # more than (0.04 degree x 0.04 degree) ~ (1km x 1km) area
          # Fill and outline each patch
          x, y = patch.exterior.xy
          x, y = m(x, y)
          plt.fill(x, y, color='#FFFF00', aa=True, alpha=1.0, hatch="x") 

    # Clip the water bodies area (white hatch)
    for patch in lakes.geoms:
        assert patch.geom_type in ['Polygon']
        assert patch.is_valid

        # Fill and outline each patch
        x, y = patch.exterior.xy
        x, y = m(x, y)
        plt.fill(x, y, color="#FFFFFF", aa=True, alpha=1.0, hatch="o") 
        m.plot(x, y, color="#FFFFFF", aa=True, lw=1.0, alpha=0.0) # needed for basemap to scale/crop the area

    # Add city names
    for city in cities:
      x,y = m(city[0], city[1])
      m.plot(x, y, 'bo')
      cnametext = plt.text(x+50, y+50, city[2].decode('utf-8'), fontsize=5, zorder = 30)
      plt.setp(cnametext, path_effects=[PathEffects.withStroke(linewidth=2, foreground="w")], zorder = 30)

    # Add prefecture contour
    if len(vx) > 0:
      # Find main polygon
      vertices = zip(vx, vy)
      final = 0
      for i in reversed(range(1,len(vertices)-1,1)):
        x, y = vertices[i-1]
        nx, ny = vertices[len(vertices)-1]
        if (x==nx) and (y==ny):
          final = i
          break

      ax = plt.gca() # get current axes instance 
      #vxx, vyy = m(vx, vy) # project the points
      vxx, vyy = m(vx[final-1:], vy[final-1:]) # project the points
      poly_verts = zip(vxx,vyy) # zip the result
      
      # Reverse polygon vertices
      org = poly_verts
      poly_verts = []
      for a in reversed(org):
         poly_verts.append(a)

      # Mask out
      mask_outside_polygons([poly_verts], "white")

      # Draw contour
      from matplotlib.patches import Polygon
      from matplotlib.patches import Shadow
      poly = Polygon(poly_verts, edgecolor="white", fill=False, label=name, linewidth=4, zorder = 10) # facecolor="b"
      ax.add_patch(poly)
      poly = Polygon(poly_verts, edgecolor="black", fill=False, label=name, linewidth=2, zorder = 10) # facecolor="b"
      ax.add_patch(poly)

    #clbls = plt.clabel(CS, inline=1, fontsize=5, fmt='%1.0f CPM', use_clabeltext=True)
    #plt.setp(clbls, path_effects=[PathEffects.withStroke(linewidth=2, foreground="w")], zorder = 10)

    DefaultSize = plt.gcf().get_size_inches()

    MaxSize = max(DefaultSize[0], DefaultSize[1])
    SizeFactor = 16.5/max(DefaultSize[0], DefaultSize[1])
    #print "Page size [%f, %f]" % (DefaultSize[0] * SizeFactor, DefaultSize[1] * SizeFactor)
    plt.gcf().set_size_inches( (DefaultSize[0] * SizeFactor, DefaultSize[1] * SizeFactor) )

    plt.title(title)

    # Add distance circle from Daiichi power plant
    daiichilat = 37.425252
    daiichilon = 141.033247
    radii = [20, 30, 60, 100, 160, 250, 400]
    ax = plt.gca() # get current axes instance 
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    #for radius in radii:
    for radius in range(20, 400, 10):
      equi(m, daiichilon, daiichilat, radius, xlim, ylim, linewidth=1, zorder = 20)

    plt.colorbar() # Legend

    # Save the result
    if not os.path.exists("%s/%s" % (renderedMapsFolder, folder)):
      os.makedirs("%s/%s" % (renderedMapsFolder, folder))

    # Cleanup the output filename
    name.replace("'","_")
    name.replace(" ","_")

    # Save png file
    plt.savefig("%s/%s/safecast_%s_%s.png" % (renderedMapsFolder, folder, name, folder), dpi = (200))
    plt.clf() # clear the plot (free the memory for the other threads)
Esempio n. 2
0
def DrawTile(precision, lon_min, lon_width, lat_min, lat_height, gx, gy, gzoom, gsize_lon, gsize_lat, x, y, z, xi, yi, grid, missing, uncovered, coastline, waterbodies, name):
    fig = Figure()
    canvas = FigureCanvas(fig)

    # Precompute gsize x gsize tiles in one shot
    lon_max = lon_min + gsize_lon * lon_width
    lat_max = lat_min + gsize_lat * lat_height

    # Create the basemap and load the shapefile
    m = Basemap(projection='merc', llcrnrlon=lon_min ,llcrnrlat=lat_min, urcrnrlon=lon_max ,urcrnrlat=lat_max, resolution='i')

    # Cleanup all axes, title, ... from the canvas
    dpi = 64
    m.ax = fig.add_axes([0, 0, 1, 1], axis_bgcolor=(1.0,1.0,1.0,0.0), frameon=False)
    m.ax.get_frame().set_linewidth(0.0)
    fig.set_size_inches((256*gsize_lon)/dpi, (256*gsize_lat)/dpi) # we need 256x256 pixel images
    fig.set_facecolor((1.0,1.0,1.0,0.0))
    fig.figurePatch.set_alpha(0.0)
    fig.gca().axesPatch.set_alpha(0.0)
    
    #japan_shp_info = m.readshapefile("%s/%s" % (rendererFolder, shapefile),"%s/%s" % (rendererFolder, shapefile), color='b', linewidth = 0.5)

    # Compute Safecast color map
    cmap = cmap_discretize(cm.RdYlBu_r, 16, 0.)
    normCPM = colors.Normalize(vmin=0,vmax=350)

    # Exclude uncovered areas
    if uncovered:
      for patch in missing.geoms:
        assert patch.geom_type in ['Polygon']
        assert patch.is_valid

        if patch.area > 0.0016: # more than (0.04 degree x 0.04 degree) ~ (1km x 1km) area
          # Fill and outline each patch
          x, y = patch.exterior.xy
          x, y = m(x, y)
          m.ax.fill(x, y, color='#FFFF00', aa=True, alpha=1.0, hatch="x") 
          m.plot(x, y, color=googleWaterColorHtml, aa=True, lw=1.0, alpha=0.0) # needed for basemap to scale/crop the area

    # Draw countour interpolation map
    if not uncovered:
      xim, yim = m(*np.meshgrid(xi, yi))
      levels = range(0, 400, 350/16)
      m.contourf(xim,yim, grid, levels, cmap=cmap, norm=normCPM, vmin=0, vmax=350)

    # Draw Safecast data on the map
    if not uncovered:
      lon,lat = m(x,y)
      m.scatter(lon,lat,s=2, c=z, cmap=cmap, norm=normCPM, linewidths=0.2, alpha=1.0)

    # Clip outside coastlines area and water bodies
    if len(coastline) > 0 and len(waterbodies) > 0:
      polygonsToClip = []
      for patch in coastline.geoms:
        if not patch.is_empty and patch.is_valid:
          vx, vy = patch.exterior.xy
          vx.reverse()
          vy.reverse()
          mvx, mvy = m(vx,vy)
          polygonsToClip.append(zip(mvx, mvy))

      for patch in waterbodies.geoms:
        if not patch.is_empty and patch.is_valid:
          vx, vy = patch.exterior.xy
          mvx, mvy = m(vx,vy)
          polygonsToClip.append(zip(mvx, mvy))

      mask_outside_polygons(polygonsToClip, googleWaterColorHtml, ax = m.ax)

    # Save the result
    if not os.path.exists("%s/%s/%s" % (rendererFolder, tileFolder, gzoom)):
      os.makedirs("%s/%s/%s" % (rendererFolder, tileFolder, gzoom))

    #
    # Multiple tiles
    #
    if (gsize_lon > 1):
      tileNameTemp = "%s/%s/%s/%s" % (rendererFolder, tileFolder, gzoom, name)
      canvas.print_figure(tileNameTemp, dpi=dpi)

      # Start the tile cutting process
      image = Image.open(tileNameTemp)
      tile_width = 256
      tile_height = 256

      # Cut the tiles 
      currentx = 0
      currenty = 0
      googlex = gx
      googley = gy
      while currenty < image.size[1]:
        while currentx < image.size[0]:
          tile = image.crop((currentx,currenty,currentx + tile_width,currenty + tile_height))
          tilename = "safecast_griddata_%s_%s_%s.png" %(googlex, googley, gzoom)
          filename = "%s/%s/%s/%s" % (rendererFolder, tileFolder, gzoom, tilename)

          if not os.path.exists(filename):
            makeColorTransparent(tile, googleWaterColor).save(filename)

          currentx += tile_width
          googlex += 1

        currentx = 0 
        currenty += tile_height

        googley += 1
        googlex = gx
      os.remove(tileNameTemp)

    #
    # One tile
    #
    else:
      name = "safecast_griddata_%s_%s_%s.png" %(gx, gy, gzoom)
      tileName = "%s/%s/%s/%s" % (rendererFolder, tileFolder, gzoom, name)
      canvas.print_figure(tileName, dpi=dpi)
      makeColorTransparent(Image.open(tileName), googleWaterColor).save(tileName)

    # Clear the plot (free the memory for the other threads)
    plt.clf()