def _clipBounds(self): """ Clip input vector data to bounds of map. """ # returns a list of GeoJSON-like mapping objects comp = self.container.getComponents('MMI')[0] imtdict = self.container.getIMTGrids('MMI', comp) geodict = imtdict['mean'].getGeoDict() xmin, xmax, ymin, ymax = (geodict.xmin, geodict.xmax, geodict.ymin, geodict.ymax) bbox = (xmin, ymin, xmax, ymax) bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin), (xmin, ymax)]) self.vectors = {} for key, value in self.layerdict.items(): vshapes = [] f = fiona.open(value, 'r') shapes = f.items(bbox=bbox) for shapeidx, shape in shapes: tshape = sShape(shape['geometry']) try: intshape = tshape.intersection(bboxpoly) # except TopologicalError as te: except Exception as te: self.logger.warn('Failure to grab %s segment: "%s"' % (key, str(te))) continue vshapes.append(intshape) self.logger.debug('Filename is %s' % value) f.close() self.vectors[key] = vshapes
def _clip_bounds(bbox, filename): """Clip input fiona-compatible vector file to input bounding box. :param bbox: Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds. :param filename: Input name of file containing vector data in a format compatible with fiona. :returns: Shapely Geometry object (Polygon or MultiPolygon). """ f = fiona.open(filename, 'r') shapes = list(f.items(bbox=bbox)) xmin, ymin, xmax, ymax = bbox newshapes = [] bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin), (xmin, ymax)]) for tshape in shapes: myshape = sShape(tshape[1]['geometry']) intshape = myshape.intersection(bboxpoly) newshapes.append(intshape) newshapes.append(myshape) gc = GeometryCollection(newshapes) f.close() return gc
def get_country_bounds(ccode, buffer_km=BUFFER_DISTANCE_KM): """Get list of country bounds (one for each sub-polygon in country polygon.) Args: ccode (str): Three letter ISO 3166 country code. buffer_km (int): Buffer distance around country boundary. Returns: list: List of 4-element tuples (xmin, xmax, ymin, ymax) """ xmin = xmax = ymin = ymax = None ccode = ccode.upper() datapath = os.path.join('data', COUNTRIES_SHP) shpfile = pkg_resources.resource_filename('libcomcat', datapath) bounds = [] with fiona.open(shpfile, 'r') as shapes: for shape in shapes: if shape['properties']['ADM0_A3'] == ccode: country = sShape(shape['geometry']) if isinstance(country, MultiPolygon): for polygon in country: xmin, ymin, xmax, ymax = _buffer( polygon.bounds, buffer_km) bounds.append((xmin, xmax, ymin, ymax)) else: xmin, ymin, xmax, ymax = _buffer(country.bounds, buffer_km) bounds.append((xmin, xmax, ymin, ymax)) break return bounds
def _selectRoads(self, roads_folder, bbox): """Select road shapes from roads directory. Args: roads_folder (str): Path to folder containing global roads data. bbox (tuple): Tuple of map bounds (xmin,ymin,xmax,ymax). Returns: list: list of Shapely geometries. """ vshapes = [] xmin, ymin, xmax, ymax = bbox bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin), (xmin, ymax)]) for root, dirs, files in os.walk(roads_folder): for fname in files: if fname.endswith('.shp'): filename = os.path.join(root, fname) with fiona.open(filename, 'r') as f: shapes = f.items(bbox=bbox) for shapeidx, shape in shapes: tshape = sShape(shape['geometry']) intshape = tshape.intersection(bboxpoly) vshapes.append(intshape) return vshapes
def _get_country_shape(ccode): datapath = os.path.join('data', COUNTRIES_SHP) shpfile = pkg_resources.resource_filename('libcomcat', datapath) country = None with fiona.open(shpfile, 'r') as shapes: for shape in shapes: if shape['properties']['ADM0_A3'] == ccode: country = sShape(shape['geometry']) return country
def _get_country_shape(ccode): datapath = os.path.join("data", COUNTRIES_SHP) shpfile = pkg_resources.resource_filename("libcomcat", datapath) country = None with fiona.open(shpfile, "r") as shapes: for shape in shapes: if shape["properties"]["ADM0_A3"] == ccode: country = sShape(shape["geometry"]) return country
def _clipBounds(self): #returns a list of GeoJSON-like mapping objects xmin,xmax,ymin,ymax = self.shakemap.getBounds() bbox = (xmin,ymin,xmax,ymax) bboxpoly = sPolygon([(xmin,ymax),(xmax,ymax),(xmax,ymin),(xmin,ymin),(xmin,ymax)]) self.vectors = {} for key,value in self.layerdict.items(): vshapes = [] f = fiona.open(value,'r') shapes = f.items(bbox=bbox) for shapeidx,shape in shapes: tshape = sShape(shape['geometry']) intshape = tshape.intersection(bboxpoly) vshapes.append(intshape) print('Filename is %s' % value) f.close() self.vectors[key] = vshapes
def _clip_bounds(bbox, filename): """Clip input fiona-compatible vector file to input bounding box. :param bbox: Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds. :param filename: Input name of file containing vector data in a format compatible with fiona. :returns: Shapely Geometry object (Polygon or MultiPolygon). """ #returns a clipped shapely object xmin, ymin, xmax, ymax = bbox bboxpoly = sPolygon([(xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin), (xmin, ymax)]) vshapes = [] f = fiona.open(filename, 'r') shapes = f.items(bbox=bbox) for shapeidx, shape in shapes: tshape = sShape(shape['geometry']) intshape = tshape.intersection(bboxpoly) vshapes.append(intshape) f.close() return vshapes
def draw_map(adict, override_scenario=False): """If adict['imtype'] is MMI, draw a map of intensity draped over topography, otherwise Draw IMT contour lines over hill-shaded topography. Args: adict (dictionary): A dictionary containing the following keys: 'imtype' (str): The intensity measure type 'topogrid' (Grid2d): A topography grid 'allcities' (Cities): A list of global cities, 'states_provinces' (Cartopy Feature): States/province boundaries. 'countries' (Cartopy Feature): Country boundaries. 'oceans' (Cartopy Feature): Oceans. 'lakes' (Cartopy Feature): Lakes. 'roads' (Shapely Feature): Roads. 'faults' (Shapely Feature): Fault traces 'datadir' (str): The path into which to deposit products 'operator' (str): The producer of this shakemap 'filter_size' (int): The size of the filter used before contouring 'info' (dictionary): The shakemap info structure 'component' (str): The intensity measure component being plotted 'imtdict' (dictionary): Dict containing the IMT grids 'rupdict' (dictionary): Dict containing the rupture data 'stationdict' (dictionary): Dict of station data 'config' (dictionary): The configuration data for this shakemap 'tdict' (dictionary): The text strings to be printed on the map in the user's choice of language. 'license_text' (str): License text to display at bottom of map 'license_logo' (str): Path to license logo image to display next to license text override_scenario (bool): Turn off scenario watermark. Returns: Tuple of (Matplotlib figure, Matplotlib figure): Objects containing the map generated by this function, and the intensity legend, respectively. If the imtype of this map is not 'MMI', the second element of the tuple will be None. """ imtype = adict['imtype'] imtdict = adict['imtdict'] # mmidict imtdata = np.nan_to_num(imtdict['mean'], nan=0.0) # mmidata gd = GeoDict(imtdict['mean_metadata']) imtgrid = Grid2D(imtdata, gd) # mmigrid gd = imtgrid.getGeoDict() # Retrieve the epicenter - this will get used on the map rupture = rupture_from_dict(adict['ruptdict']) origin = rupture.getOrigin() center_lat = origin.lat center_lon = origin.lon # load the cities data, limit to cities within shakemap bounds cities = adict['allcities'].limitByBounds((gd.xmin, gd.xmax, gd.ymin, gd.ymax)) # get the map boundaries and figure size bounds, figsize, aspect = _get_map_info(gd) # Note: dimensions are: [left, bottom, width, height] dim_left = 0.1 dim_bottom = 0.19 dim_width = 0.8 dim_height = dim_width/aspect if dim_height > 0.8: dim_height = 0.8 dim_width = 0.8 * aspect dim_left = (1.0 - dim_width) / 2 # Create the MercatorMap object, which holds a separate but identical # axes object used to determine collisions between city labels. mmap = MercatorMap( bounds, figsize, cities, padding=0.5, dimensions=[dim_left, dim_bottom, dim_width, dim_height]) fig = mmap.figure ax = mmap.axes # this needs to be done here so that city label collision # detection will work fig.canvas.draw() # get the geographic projection object geoproj = mmap.geoproj # get the mercator projection object proj = mmap.proj # get the proj4 string - used by Grid2D project() method projstr = proj.proj4_init # get the projected IMT and topo grids pimtgrid, ptopogrid = _get_projected_grids(imtgrid, adict['topogrid'], projstr) # get the projected geodict proj_gd = pimtgrid.getGeoDict() pimtdata = pimtgrid.getData() ptopo_data = ptopogrid.getData() mmimap = ColorPalette.fromPreset('mmi') if imtype == 'MMI': draped_hsv = _get_draped(pimtdata, ptopo_data, mmimap) else: # get the draped topo data topo_colormap = ColorPalette.fromPreset('shaketopo') draped_hsv = _get_shaded(ptopo_data, topo_colormap) # convert units if imtype == 'PGV': pimtdata = np.exp(pimtdata) else: pimtdata = np.exp(pimtdata) * 100 plt.sca(ax) ax.set_xlim(proj_gd.xmin, proj_gd.xmax) ax.set_ylim(proj_gd.ymin, proj_gd.ymax) img_extent = (proj_gd.xmin, proj_gd.xmax, proj_gd.ymin, proj_gd.ymax) plt.imshow(draped_hsv, origin='upper', extent=img_extent, zorder=IMG_ZORDER, interpolation='none') config = adict['config'] gmice = get_object_from_config('gmice', 'modeling', config) gmice_imts = gmice.DEFINED_FOR_INTENSITY_MEASURE_TYPES gmice_pers = gmice.DEFINED_FOR_SA_PERIODS oqimt = imt.from_string(imtype) if imtype != 'MMI' and (not isinstance(oqimt, tuple(gmice_imts)) or (isinstance(oqimt, imt.SA) and oqimt.period not in gmice_pers)): my_gmice = None else: my_gmice = gmice if imtype != 'MMI': # call the contour module in plotting to get the vertices of the # contour lines contour_objects = contour(imtdict, imtype, adict['filter_size'], my_gmice) # get a color palette for the levels we have # levels = [c['properties']['value'] for c in contour_objects] # cartopy shapely feature has some weird behaviors, so I had to go # rogue and draw contour lines/labels myself. # To choose which contours to label, we will keep track of the lengths # of contours, grouped by isovalue contour_lens = defaultdict(lambda: []) def arclen(path): """ Compute the arclength of *path*, which should be a list of pairs of numbers. """ x0, y0 = [np.array(c) for c in zip(*path)] x1, y1 = [np.roll(c, -1) for c in (x0, y0)] # offset by 1 # don't include first-last vertices as an edge: x0, y0, x1, y1 = [c[:-1] for c in (x0, y0, x1, y1)] return np.sum(np.sqrt((x0 - x1)**2 + (y0 - y1)**2)) # draw dashed contours first, the ones over land will be overridden by # solid contours for contour_object in contour_objects: props = contour_object['properties'] multi_lines = sShape(contour_object['geometry']) pmulti_lines = proj.project_geometry(multi_lines, src_crs=geoproj) for multi_line in pmulti_lines: pmulti_line = mapping(multi_line)['coordinates'] x, y = zip(*pmulti_line) contour_lens[props['value']].append(arclen(pmulti_line)) # color = imt_cmap.getDataColor(props['value']) ax.plot(x, y, color=props['color'], linestyle='dashed', zorder=DASHED_CONTOUR_ZORDER) white_box = dict( boxstyle="round", ec=(0, 0, 0), fc=(1., 1, 1), color='k' ) # draw solid contours next - the ones over water will be covered by # ocean polygon for contour_object in contour_objects: props = contour_object['properties'] multi_lines = sShape(contour_object['geometry']) pmulti_lines = proj.project_geometry(multi_lines, src_crs=geoproj) # only label long contours (relative to others with the same # isovalue) min_len = np.array(contour_lens[props['value']]).mean() for multi_line in pmulti_lines: pmulti_line = mapping(multi_line)['coordinates'] x, y = zip(*pmulti_line) # color = imt_cmap.getDataColor(props['value']) ax.plot(x, y, color=props['color'], linestyle='solid', zorder=CONTOUR_ZORDER) if arclen(pmulti_line) >= min_len: # try to label each segment with black text in a white box xc = x[int(len(x)/3)] yc = y[int(len(y)/3)] if _label_close_to_edge( xc, yc, proj_gd.xmin, proj_gd.xmax, proj_gd.ymin, proj_gd.ymax): continue # TODO: figure out if box is going to go outside the map, # if so choose a different point on the line. # For small values, use scientific notation with 1 sig fig # to avoid multiple contours labelled 0.0: value = props['value'] fmt = '%.1g' if abs(value) < 0.1 else '%.1f' ax.text(xc, yc, fmt % value, size=8, ha="center", va="center", bbox=white_box, zorder=AXES_ZORDER-1) # make the border thicker lw = 2.0 ax.outline_patch.set_zorder(BORDER_ZORDER) ax.outline_patch.set_linewidth(lw) ax.outline_patch.set_joinstyle('round') ax.outline_patch.set_capstyle('round') # Coastlines will get drawn when we draw the ocean edges # ax.coastlines(resolution="10m", zorder=COAST_ZORDER, linewidth=3) if adict['states_provinces']: ax.add_feature(adict['states_provinces'], edgecolor='0.5', zorder=COAST_ZORDER) if adict['countries']: ax.add_feature(adict['countries'], edgecolor='black', zorder=BORDER_ZORDER) if adict['oceans']: ax.add_feature(adict['oceans'], edgecolor='black', zorder=OCEAN_ZORDER) if adict['lakes']: ax.add_feature(adict['lakes'], edgecolor='black', zorder=OCEAN_ZORDER) if adict['faults'] is not None: ax.add_feature(adict['faults'], edgecolor='firebrick', zorder=ROAD_ZORDER) if adict['roads'] is not None: ax.add_feature(adict['roads'], edgecolor='dimgray', zorder=ROAD_ZORDER) # draw graticules, ticks, tick labels _draw_graticules(ax, *bounds) # is this event a scenario? info = adict['info'] etype = info['input']['event_information']['event_type'] is_scenario = etype == 'SCENARIO' if is_scenario and not override_scenario: plt.text( center_lon, center_lat, adict['tdict']['title_parts']['scenario'], fontsize=72, zorder=SCENARIO_ZORDER, transform=geoproj, alpha=WATERMARK_ALPHA, color=WATERMARK_COLOR, horizontalalignment='center', verticalalignment='center', rotation=45, path_effects=[ path_effects.Stroke(linewidth=1, foreground='black')] ) # Draw the map scale in the unoccupied lower corner. corner = 'll' draw_scale(ax, corner, pady=0.05, padx=0.05, zorder=SCALE_ZORDER) # draw cities mmap.drawCities(shadow=True, zorder=CITIES_ZORDER, draw_dots=True) # Draw the epicenter as a black star plt.sca(ax) plt.plot(center_lon, center_lat, 'k*', markersize=16, zorder=EPICENTER_ZORDER, transform=geoproj) # draw the rupture polygon(s) in black, if not point rupture point_source = True if not isinstance(rupture, PointRupture): point_source = False json_dict = rupture._geojson for feature in json_dict['features']: for coords in feature['geometry']['coordinates']: for pcoords in coords: poly2d = sLineString([xy[0:2] for xy in pcoords]) ppoly = proj.project_geometry(poly2d) mppoly = mapping(ppoly)['coordinates'] for spoly in mppoly: x, y = zip(*spoly) ax.plot(x, y, 'k', lw=1, zorder=FAULT_ZORDER) # draw the station data on the map stations = adict['stationdict'] _draw_stations(ax, stations, imtype, mmimap, geoproj) _draw_title(imtype, adict) process_time = info['processing']['shakemap_versions']['process_time'] map_version = int(info['processing']['shakemap_versions']['map_version']) if imtype == 'MMI': _draw_mmi_legend(fig, mmimap, gmice, process_time, map_version, point_source, adict['tdict']) # make a separate MMI legend fig2 = plt.figure(figsize=figsize) _draw_mmi_legend(fig2, mmimap, gmice, process_time, map_version, point_source, adict['tdict']) else: _draw_imt_legend(fig, mmimap, imtype, gmice, process_time, map_version, point_source, adict['tdict']) plt.draw() fig2 = None _draw_license(fig, adict) return (fig, fig2)
def drawHazusMap(self, shakegrid, filename, model_config): gd = shakegrid.getGeoDict() # Retrieve the epicenter - this will get used on the map (??) center_lat = shakegrid.getEventDict()['lat'] center_lon = shakegrid.getEventDict()['lon'] # define the map # first cope with stupid 180 meridian height = (gd.ymax - gd.ymin) * 111.191 if gd.xmin < gd.xmax: width = (gd.xmax - gd.xmin) * \ np.cos(np.radians(center_lat)) * 111.191 xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax) else: xmin, xmax, ymin, ymax = (gd.xmin, gd.xmax, gd.ymin, gd.ymax) xmax += 360 width = ((gd.xmax + 360) - gd.xmin) * \ np.cos(np.radians(center_lat)) * 111.191 aspect = width / height # if the aspect is not 1, then trim bounds in # x or y direction as appropriate if width > height: dw = (width - height) / 2.0 # this is width in km xmin = xmin + dw / (np.cos(np.radians(center_lat)) * 111.191) xmax = xmax - dw / (np.cos(np.radians(center_lat)) * 111.191) width = (xmax - xmin) * np.cos(np.radians(center_lat)) * 111.191 if height > width: dh = (height - width) / 2.0 # this is width in km ymin = ymin + dh / 111.191 ymax = ymax - dh / 111.191 height = (ymax - ymin) * 111.191 aspect = width / height figheight = FIGWIDTH / aspect bounds = (xmin, xmax, ymin, ymax) figsize = (FIGWIDTH, figheight) # load the counties here so we can grab the county names to # draw on the map counties_file = model_config['counties'] counties_shapes = fiona.open(counties_file, 'r') counties = counties_shapes.items(bbox=(xmin, ymin, xmax, ymax)) county_shapes = [] county_columns = { 'name': [], 'lat': [], 'lon': [], 'pop': [], } for cid, county in counties: # county is a dictionary county_shape = sShape(county['geometry']) state_fips = county['properties']['STATEFP10'] county_fips = county['properties']['COUNTYFP10'] fips = int(state_fips + county_fips) df = self._dataframe weight = 1 if (df['CountyFips'] == fips).any(): loss_row = df[df['CountyFips'] == fips].iloc[0] weight = loss_row['EconLoss'] center_point = county_shape.centroid county_name = county['properties']['NAMELSAD10'].replace( 'County', '').strip() # feature = ShapelyFeature([county_shape], ccrs.PlateCarree(), # zorder=COUNTY_ZORDER) county_shapes.append(county_shape) county_columns['name'].append(county_name) county_columns['pop'].append(county_shape.area * weight) county_columns['lat'].append(center_point.y) county_columns['lon'].append(center_point.x) # ax.add_feature(feature, facecolor=GREY, # edgecolor='grey', linewidth=0.5) # tx, ty = mmap.proj.transform_point( # center_point.x, center_point.y, ccrs.PlateCarree()) # plt.text(tx, ty, county_name, # zorder=NAME_ZORDER, # horizontalalignment='center', # verticalalignment='center') # Create the MercatorMap object, which holds a separate but identical # axes object used to determine collisions between city labels. # here we're pretending that county names are city names. county_df = pd.DataFrame(county_columns) cities = Cities(county_df) mmap = MercatorMap(bounds, figsize, cities, padding=0.5) fig = mmap.figure ax = mmap.axes geoproj = mmap.geoproj proj = mmap.proj # this is a workaround to an occasional problem where some vector layers # are not rendered. See # https://github.com/SciTools/cartopy/issues/1155#issuecomment-432941088 proj._threshold /= 6 # this needs to be done here so that city label collision # detection will work fig.canvas.draw() # draw county names mmap.drawCities(zorder=NAME_ZORDER) # now draw the counties in grey for county_shape in county_shapes: feature = ShapelyFeature([county_shape], ccrs.PlateCarree(), zorder=COUNTY_ZORDER) ax.add_feature(feature, facecolor=GREY, edgecolor='grey', linewidth=0.5, zorder=COUNTY_ZORDER) # now draw the county boundaries only so that we can see # them on top of the colored tracts. for county_shape in county_shapes: feature = ShapelyFeature([county_shape], ccrs.PlateCarree(), zorder=COUNTY_ZORDER) ax.add_feature(feature, facecolor=(0, 0, 0, 0), edgecolor='grey', linewidth=0.5, zorder=NAME_ZORDER) # define bounding box we'll use to clip vector data bbox = (xmin, ymin, xmax, ymax) # load and clip ocean vectors to match map boundaries oceanfile = model_config['ocean_vectors'] oceanshapes = _clip_bounds(bbox, oceanfile) ax.add_feature(ShapelyFeature(oceanshapes, crs=geoproj), facecolor=WATERCOLOR, zorder=OCEAN_ZORDER) # draw states with black border - TODO: Look into states_file = model_config['states'] transparent = '#00000000' states = _clip_bounds(bbox, states_file) ax.add_feature(ShapelyFeature(states, crs=geoproj), facecolor=transparent, edgecolor='k', zorder=STATE_ZORDER) # draw census tracts, colored by loss level tracts_file = model_config['tracts'] tract_shapes = fiona.open(tracts_file, 'r') tracts = tract_shapes.items(bbox=(xmin, ymin, xmax, ymax)) ntracts = 0 for tid, tract in tracts: # tract is a dictionary ntracts += 1 tract_shape = sShape(tract['geometry']) state_fips = str(int(tract['properties']['STATEFP10'])) county_fips = state_fips + tract['properties']['COUNTYFP10'] fips_column = self._dataframe['CountyFips'] if not fips_column.isin([county_fips]).any(): continue tract_fips = int(county_fips + tract['properties']['TRACTCE10']) econloss = 0.0 if tract_fips in self._tract_loss: econloss = self._tract_loss[tract_fips] # print('Tract %i: Economic loss: %.3f' % (tract_fips, econloss)) else: x = 1 if econloss < 1e3: color = GREEN elif econloss >= 1e3 and econloss < 1e5: color = YELLOW elif econloss >= 1e5 and econloss < 1e6: color = ORANGE else: color = RED feature = ShapelyFeature([tract_shape], ccrs.PlateCarree(), zorder=TRACT_ZORDER) ax.add_feature(feature, facecolor=color) # # Draw the epicenter as a black star # plt.plot(center_lon, center_lat, 'k*', markersize=16, # zorder=EPICENTER_ZORDER, transform=geoproj) # save our map out to a file logging.info('Saving to %s' % filename) t0 = time.time() plt.savefig(filename, dpi=300) t1 = time.time() logging.info('Done saving map - %.2f seconds' % (t1 - t0))