Exemplo n.º 1
0
def test_bounds_within_meridian():
    host = GeoDict({
        'xmin': -180,
        'xmax': 150,
        'ymin': -90,
        'ymax': 90,
        'dx': 30,
        'dy': 45,
        'nx': 12,
        'ny': 5
    })
    sample = GeoDict({
        'xmin': 75,
        'xmax': -135,
        'ymin': -67.5,
        'ymax': 67.5,
        'dx': 30,
        'dy': 45,
        'nx': 6,
        'ny': 4
    })

    result = GeoDict({
        'xmin': 90,
        'xmax': -150,
        'ymin': -45,
        'ymax': 45,
        'dx': 30,
        'dy': 45,
        'nx': 5,
        'ny': 3
    })

    inside = host.getBoundsWithin(sample)
    assert inside == result
Exemplo n.º 2
0
def test_bounds_within_again():
    fxmin, fxmax = (-179.995833333333, 179.99583333189372)
    fymin, fymax = (-89.99583333333332, 89.9958333326134)
    fdx, fdy = (0.0083333333333, 0.0083333333333)
    fnx, fny = (43200, 21600)

    xmin, xmax = (97.233, 99.733)
    ymin, ymax = (84.854, 85.074)
    dx, dy = (0.025, 0.024444444444444317)
    nx, ny = (101, 10)

    host = GeoDict({
        'xmin': fxmin,
        'xmax': fxmax,
        'ymin': fymin,
        'ymax': fymax,
        'dx': fdx,
        'dy': fdy,
        'nx': fnx,
        'ny': fny
    })
    sample = GeoDict({
        'xmin': xmin,
        'xmax': xmax,
        'ymin': ymin,
        'ymax': ymax,
        'dx': dx,
        'dy': dy,
        'nx': nx,
        'ny': ny
    })
    inside = host.getBoundsWithin(sample)
Exemplo n.º 3
0
def test_bounds_within_again():
    fxmin, fxmax = (-179.995833333333, 179.99583333189372)
    fymin, fymax = (-89.99583333333332, 89.9958333326134)
    fdx, fdy = (0.0083333333333, 0.0083333333333)
    fnx, fny = (43200, 21600)

    xmin, xmax = (97.233, 99.733)
    ymin, ymax = (84.854, 85.074)
    dx, dy = (0.025, 0.024444444444444317)
    nx, ny = (101, 10)

    host = GeoDict({'xmin': fxmin,
                    'xmax': fxmax,
                    'ymin': fymin,
                    'ymax': fymax,
                    'dx': fdx,
                    'dy': fdy,
                    'nx': fnx,
                    'ny': fny})
    sample = GeoDict({'xmin': xmin,
                      'xmax': xmax,
                      'ymin': ymin,
                      'ymax': ymax,
                      'dx': dx,
                      'dy': dy,
                      'nx': nx,
                      'ny': ny})
    inside = host.getBoundsWithin(sample)
Exemplo n.º 4
0
def test_bounds_within_meridian():
    host = GeoDict({'xmin': -180,
                    'xmax': 150,
                    'ymin': -90,
                    'ymax': 90,
                    'dx': 30,
                    'dy': 45,
                    'nx': 12,
                    'ny': 5})
    sample = GeoDict({'xmin': 75,
                      'xmax': -135,
                      'ymin': -67.5,
                      'ymax': 67.5,
                      'dx': 30,
                      'dy': 45,
                      'nx': 6,
                      'ny': 4})

    result = GeoDict({'xmin': 90,
                      'xmax': -150,
                      'ymin': -45,
                      'ymax': 45,
                      'dx': 30,
                      'dy': 45,
                      'nx': 5,
                      'ny': 3})

    inside = host.getBoundsWithin(sample)
    assert inside == result
Exemplo n.º 5
0
def test_bounds_within_real():
    fxmin, fxmax = (-179.995833333333, 179.99583333189372)
    fymin, fymax = (-89.99583333333332, 89.9958333326134)
    fdx, fdy = (0.0083333333333, 0.0083333333333)
    fnx, fny = (43200, 21600)
    xmin, xmax = (177.75, -179.75)
    ymin, ymax = (50.41625, 51.98375)
    dx, dy = (0.025, 0.02488095238095242)
    nx, ny = (101, 64)
    host = GeoDict({
        'xmin': fxmin,
        'xmax': fxmax,
        'ymin': fymin,
        'ymax': fymax,
        'dx': fdx,
        'dy': fdy,
        'nx': fnx,
        'ny': fny
    })
    sample = GeoDict({
        'xmin': xmin,
        'xmax': xmax,
        'ymin': ymin,
        'ymax': ymax,
        'dx': dx,
        'dy': dy,
        'nx': nx,
        'ny': ny
    })
    result = GeoDict({
        'xmin': 60,
        'xmax': -120,
        'ymin': -30,
        'ymax': 30,
        'dx': 60,
        'dy': 30,
        'nx': 4,
        'ny': 3
    })
    inside = host.getBoundsWithin(sample)
    ixmin, ixmax = (177.75416666523603, -179.7541666666673)
    iymin, iymax = (50.4208333327717, 51.9791666660988)
    idx, idy = (0.0083333333333, 0.0083333333333)
    inx, iny = (300, 188)
    result = GeoDict({
        'xmin': ixmin,
        'xmax': ixmax,
        'ymin': iymin,
        'ymax': iymax,
        'dx': idx,
        'dy': idy,
        'nx': inx,
        'ny': iny
    })
    assert inside == result
Exemplo n.º 6
0
def test_cut():
    geodict = GeoDict({'xmin': 0.5, 'xmax': 4.5, 'ymin': 0.5,
                       'ymax': 4.5, 'dx': 1.0, 'dy': 1.0, 'ny': 5, 'nx': 5})
    data = np.arange(0, 25).reshape(5, 5)

    print('Testing data extraction...')
    grid = Grid2D(data, geodict)
    xmin, xmax, ymin, ymax = (2.5, 3.5, 2.5, 3.5)
    newgrid = grid.cut(xmin, xmax, ymin, ymax)
    output = np.array([[7, 8], [12, 13]])
    np.testing.assert_almost_equal(newgrid.getData(), output)
    print('Passed data extraction...')

    print('Testing data trimming with resampling...')
    # make a more complicated test using getboundswithin
    data = np.arange(0, 84).reshape(7, 12)
    geodict = GeoDict({'xmin': -180, 'xmax': 150,
                       'ymin': -90, 'ymax': 90,
                       'dx': 30, 'dy': 30,
                       'nx': 12, 'ny': 7})
    grid = Grid2D(data, geodict)
    sampledict = GeoDict.createDictFromBox(-75,
                                           45, -45, 75, geodict.dx, geodict.dy)
    cutdict = geodict.getBoundsWithin(sampledict)
    newgrid = grid.cut(cutdict.xmin, cutdict.xmax, cutdict.ymin, cutdict.ymax)
    output = np.array([[16, 17, 18, 19],
                       [28, 29, 30, 31],
                       [40, 41, 42, 43],
                       [52, 53, 54, 55]])
    np.testing.assert_almost_equal(newgrid.getData(), output)
    print('Passed data trimming with resampling...')

    print('Test cut with self-alignment...')
    geodict = GeoDict({'xmin': 0.5, 'xmax': 4.5,
                       'ymin': 0.5, 'ymax': 6.5,
                       'dx': 1.0, 'dy': 1.0,
                       'nx': 5, 'ny': 7})
    data = np.arange(0, 35).astype(np.float32).reshape(7, 5)
    grid = Grid2D(data, geodict)
    cutxmin = 1.7
    cutxmax = 3.7
    cutymin = 1.7
    cutymax = 5.7
    cutgrid = grid.cut(cutxmin, cutxmax, cutymin, cutymax, align=True)
    output = np.array([[7, 8],
                       [12, 13],
                       [17, 18],
                       [22, 23]])
    np.testing.assert_almost_equal(cutgrid.getData(), output)
    print('Passed cut with self-alignment.')
Exemplo n.º 7
0
def test_bounds_meridian2():
    host = {'ny': 797, 'dx': 0.0083333333,
            'ymin': -21.445972496439, 'dy': 0.0083333333,
            'xmin': 178.33735967776101, 'nx': 841,
            'xmax': -174.66264035023897, 'ymax': -14.812639189639}
    sample = {'ny': 773, 'dx': 0.008333333333333333,
              'ymin': -21.35, 'dy': 0.008333333333333333,
              'xmin': 178.43333333333334, 'nx': 817,
              'xmax': -174.76666666666665, 'ymax': -14.916666666666666}

    host_geodict = GeoDict(host)
    sample_geodict = GeoDict(sample)
    within = host_geodict.getBoundsWithin(sample_geodict)
    assert within.xmin == 178.437359677361
    assert within.xmax == -174.770973683139
Exemplo n.º 8
0
def test_bounds_within_real():
    fxmin, fxmax = (-179.995833333333, 179.99583333189372)
    fymin, fymax = (-89.99583333333332, 89.9958333326134)
    fdx, fdy = (0.0083333333333, 0.0083333333333)
    fnx, fny = (43200, 21600)
    xmin, xmax = (177.75, -179.75)
    ymin, ymax = (50.41625, 51.98375)
    dx, dy = (0.025, 0.02488095238095242)
    nx, ny = (101, 64)
    host = GeoDict({'xmin': fxmin,
                    'xmax': fxmax,
                    'ymin': fymin,
                    'ymax': fymax,
                    'dx': fdx,
                    'dy': fdy,
                    'nx': fnx,
                    'ny': fny})
    sample = GeoDict({'xmin': xmin,
                      'xmax': xmax,
                      'ymin': ymin,
                      'ymax': ymax,
                      'dx': dx,
                      'dy': dy,
                      'nx': nx,
                      'ny': ny})
    result = GeoDict({'xmin': 60,
                      'xmax': -120,
                      'ymin': -30,
                      'ymax': 30,
                      'dx': 60,
                      'dy': 30,
                      'nx': 4,
                      'ny': 3})
    inside = host.getBoundsWithin(sample)
    ixmin, ixmax = (177.75416666523603, -179.7541666666673)
    iymin, iymax = (50.4208333327717, 51.9791666660988)
    idx, idy = (0.0083333333333, 0.0083333333333)
    inx, iny = (300, 188)
    result = GeoDict({'xmin': ixmin,
                      'xmax': ixmax,
                      'ymin': iymin,
                      'ymax': iymax,
                      'dx': idx,
                      'dy': idy,
                      'nx': inx,
                      'ny': iny})
    assert inside == result
Exemplo n.º 9
0
def modelMap(grids, shakefile=None, suptitle=None, inventory_shapefile=None,
             plotorder=None, maskthreshes=None, colormaps=None, boundaries=None,
             zthresh=0, scaletype='continuous', lims=None, logscale=False,
             ALPHA=0.7, maproads=True, mapcities=True, isScenario=False,
             roadfolder=None, topofile=None, cityfile=None, oceanfile=None,
             roadcolor='#6E6E6E', watercolor='#B8EEFF', countrycolor='#177F10',
             outputdir=None, savepdf=True, savepng=True, showplots=False,
             roadref='unknown', cityref='unknown', oceanref='unknown',
             printparam=False, ds=True, dstype='mean', upsample=False):
    """
    This function creates maps of mapio grid layers (e.g. liquefaction or
    landslide models with their input layers)
    All grids must use the same bounds
    TO DO change so that all input layers do not have to have the same bounds,
    test plotting multiple probability layers, and add option so that if PDF and
    PNG aren't output, opens plot on screen using plt.show()

    :param grids: Dictionary of N layers and metadata formatted like:
        maplayers['layer name']={
        'grid': mapio grid2D object,
        'label': 'label for colorbar and top line of subtitle',
        'type': 'output or input to model',
        'description': 'detailed description of layer for subtitle'}.
      Layer names must be unique.
    :type name: Dictionary or Ordered dictionary - import collections;
      grids = collections.OrderedDict()
    :param shakefile: optional ShakeMap file (url or full file path) to extract information for labels and folder names
    :type shakefile: Shakemap Event Dictionary
    :param suptitle: This will be displayed at the top of the plots and in the
      figure names
    :type suptitle: string
    :param plotorder: List of keys describing the order to plot the grids, if
      None and grids is an ordered dictionary, it will use the order of the
      dictionary, otherwise it will choose order which may be somewhat random
      but it will always put a probability grid first
    :type plotorder: list
    :param maskthreshes: N x 1 array or list of lower thresholds for masking
      corresponding to order in plotorder or order of OrderedDict if plotorder
      is None. If grids is not an ordered dict and plotorder is not specified,
      this will not work right. If None (default), nothing will be masked
    :param colormaps: List of strings of matplotlib colormaps (e.g. cm.autumn_r)
      corresponding to plotorder or order of dictionary if plotorder is None.
      The list can contain both strings and None e.g. colormaps = ['cm.autumn',
      None, None, 'cm.jet'] and None's will default to default colormap
    :param boundaries: None to show entire study area, 'zoom' to zoom in on the
      area of action (only works if there is a probability layer) using zthresh
      as a threshold, or a dictionary defining lats and lons in the form of
      boundaries.xmin = minlon, boundaries.xmax = maxlon, boundaries.ymin =
      min lat, boundaries.ymax = max lat
    :param zthresh: threshold for computing zooming bounds, only used if
      boundaries = 'zoom'
    :type zthresh: float
    :param scaletype: Type of scale for plotting, 'continuous' or 'binned' -
      will be reflected in colorbar
    :type scaletype: string
    :param lims: None or Nx1 list of tuples or numpy arrays corresponding to
      plotorder defining the limits for saturating the colorbar (vmin, vmax) if
      scaletype is continuous or the bins to use (clev) if scaletype if binned.
      The list can contain tuples, arrays, and Nones, e.g. lims = [(0., 10.),
      None, (0.1, 1.5), np.linspace(0., 1.5, 15)]. When None is specified, the
      program will estimate the limits, when an array is specified but the scale
      type is continuous, vmin will be set to min(array) and vmax will be set
      to max(array)
    :param lims: None or Nx1 list of Trues and Falses corresponding to
      plotorder defining whether to use a linear or log scale (log10) for
      plotting the layer. This will be reflected in the labels
    :param ALPHA: Transparency for mapping, if there is a hillshade that will
      plot below each layer, it is recommended to set this to at least 0.7
    :type ALPHA: float
    :param maproads: Whether to show roads or not, default True, but requires
      that roadfile is specified and valid to work
    :type maproads: boolean
    :param mapcities: Whether to show cities or not, default True, but requires
      that cityfile is specified and valid to work
    :type mapcities: boolean
    :param isScenario: Whether this is a scenario (True) or a real event (False)
      (default False)
    :type isScenario: boolean
    :param roadfolder: Full file path to folder containing road shapefiles
    :type roadfolder: string
    :param topofile: Full file path to topography grid (GDAL compatible) - this
      is only needed to make a hillshade if a premade hillshade is not specified
    :type topofile: string
    :param cityfile: Full file path to Pager file containing city & population
      information
    :type cityfile: string
    :param roadcolor: Color to use for roads, if plotted, default #6E6E6E
    :type roadcolor: Hex color or other matplotlib compatible way of defining
      color
    :param watercolor: Color to use for oceans, lakes, and rivers, default
      #B8EEFF
    :type watercolor: Hex color or other matplotlib compatible way of defining
      color
    :param countrycolor: Color for country borders, default #177F10
    :type countrycolor: Hex color or other matplotlib compatible way of defining
      color
    :param outputdir: File path for outputting figures, if edict is defined, a
      subfolder based on the event id will be created in this folder. If None,
      will use current directory
    :param savepdf: True to save pdf figure, False to not
    :param savepng: True to save png figure, False to not
    :param ds: True to allow downsampling for display (necessary when arrays
      are quite large, False to not allow)
    :param dstype: What function to use in downsampling, options are 'min',
      'max', 'median', or 'mean'
    :param upsample: True to upsample the layer to the DEM resolution for better
      looking hillshades

    :returns:
        * PDF and/or PNG of map
        * Downsampled and trimmed version of input grids. If no
        modification was needed for plotting, this will be identical to grids but
        without the metadata

    """

    if suptitle is None:
        suptitle = ' '

    plt.ioff()

    defaultcolormap = cm.jet

    if shakefile is not None:
        edict = ShakeGrid.load(shakefile, adjust='res').getEventDict()
        temp = ShakeGrid.load(shakefile, adjust='res').getShakeDict()
        edict['eventid'] = temp['shakemap_id']
        edict['version'] = temp['shakemap_version']
    else:
        edict = None

    # Get output file location
    if outputdir is None:
        print('No output location given, using current directory for outputs\n')
        outputdir = os.getcwd()
    if edict is not None:
        outfolder = os.path.join(outputdir, edict['event_id'])
    else:
        outfolder = outputdir
    if not os.path.isdir(outfolder):
        os.makedirs(outfolder)

    # Get plotting order, if not specified
    if plotorder is None:
        plotorder = list(grids.keys())

    # Get boundaries to use for all plots
    cut = True
    if boundaries is None:
        cut = False
        keytemp = list(grids.keys())
        boundaries = grids[keytemp[0]]['grid'].getGeoDict()
    elif boundaries == 'zoom':
        # Find probability layer (will just take the maximum bounds if there is
        # more than one)
        keytemp = list(grids.keys())
        key1 = [key for key in keytemp if 'model' in key.lower()]
        if len(key1) == 0:
            print('Could not find model layer to use for zoom, using default boundaries')
            keytemp = list(grids.keys())
            boundaries = grids[keytemp[0]]['grid'].getGeoDict()
        else:
            lonmax = -1.e10
            lonmin = 1.e10
            latmax = -1.e10
            latmin = 1.e10
            for key in key1:
                # get lat lons of areas affected and add, if no areas affected,
                # switch to shakemap boundaries
                temp = grids[key]['grid']
                xmin, xmax, ymin, ymax = temp.getBounds()
                lons = np.linspace(xmin, xmax, temp.getGeoDict().nx)
                lats = np.linspace(ymax, ymin, temp.getGeoDict().ny)  # backwards so it plots right
                row, col = np.where(temp.getData() > float(zthresh))
                lonmin = lons[col].min()
                lonmax = lons[col].max()
                latmin = lats[row].min()
                latmax = lats[row].max()
                # llons, llats = np.meshgrid(lons, lats)  # make meshgrid
                # llons1 = llons[temp.getData() > float(zthresh)]
                # llats1 = llats[temp.getData() > float(zthresh)]
                # if llons1.min() < lonmin:
                #     lonmin = llons1.min()
                # if llons1.max() > lonmax:
                #     lonmax = llons1.max()
                # if llats1.min() < latmin:
                #     latmin = llats1.min()
                # if llats1.max() > latmax:
                #     latmax = llats1.max()
            boundaries1 = {'dx': 100, 'dy': 100., 'nx': 100., 'ny': 100}  # dummy fillers, only really care about bounds
            if xmin < lonmin-0.15*(lonmax-lonmin):
                boundaries1['xmin'] = lonmin-0.1*(lonmax-lonmin)
            else:
                boundaries1['xmin'] = xmin
            if xmax > lonmax+0.15*(lonmax-lonmin):
                boundaries1['xmax'] = lonmax+0.1*(lonmax-lonmin)
            else:
                boundaries1['xmax'] = xmax
            if ymin < latmin-0.15*(latmax-latmin):
                boundaries1['ymin'] = latmin-0.1*(latmax-latmin)
            else:
                boundaries1['ymin'] = ymin
            if ymax > latmax+0.15*(latmax-latmin):
                boundaries1['ymax'] = latmax+0.1*(latmax-latmin)
            else:
                boundaries1['ymax'] = ymax
            boundaries = GeoDict(boundaries1, adjust='res')
    else:
        # SEE IF BOUNDARIES ARE SAME AS BOUNDARIES OF LAYERS
        keytemp = list(grids.keys())
        tempgdict = grids[keytemp[0]]['grid'].getGeoDict()
        if np.abs(tempgdict.xmin-boundaries['xmin']) < 0.05 and \
           np.abs(tempgdict.ymin-boundaries['ymin']) < 0.05 and \
           np.abs(tempgdict.xmax-boundaries['xmax']) < 0.05 and \
           np.abs(tempgdict.ymax - boundaries['ymax']) < 0.05:
            print('Input boundaries are almost the same as specified boundaries, no cutting needed')
            boundaries = tempgdict
            cut = False
        else:
            try:
                if boundaries['xmin'] > boundaries['xmax'] or \
                   boundaries['ymin'] > boundaries['ymax']:
                    print('Input boundaries are not usable, using default boundaries')
                    keytemp = list(grids.keys())
                    boundaries = grids[keytemp[0]]['grid'].getGeoDict()
                    cut = False
                else:
                    # Build dummy GeoDict
                    boundaries = GeoDict({'xmin': boundaries['xmin'],
                                          'xmax': boundaries['xmax'],
                                          'ymin': boundaries['ymin'],
                                          'ymax': boundaries['ymax'],
                                          'dx': 100.,
                                          'dy': 100.,
                                          'ny': 100.,
                                          'nx': 100.},
                                         adjust='res')
            except:
                print('Input boundaries are not usable, using default boundaries')
                keytemp = list(grids.keys())
                boundaries = grids[keytemp[0]]['grid'].getGeoDict()
                cut = False

    # Pull out bounds for various uses
    bxmin, bxmax, bymin, bymax = boundaries.xmin, boundaries.xmax, boundaries.ymin, boundaries.ymax

    # Determine if need a single panel or multi-panel plot and if multi-panel,
    # how many and how it will be arranged
    fig = plt.figure()
    numpanels = len(grids)
    if numpanels == 1:
        rowpan = 1
        colpan = 1
        # create the figure and axes instances.
        fig.set_figwidth(5)
    elif numpanels == 2 or numpanels == 4:
        rowpan = np.ceil(numpanels/2.)
        colpan = 2
        fig.set_figwidth(13)
    else:
        rowpan = np.ceil(numpanels/3.)
        colpan = 3
        fig.set_figwidth(15)
    if rowpan == 1:
        fig.set_figheight(rowpan*6.0)
    else:
        fig.set_figheight(rowpan*5.3)

    # Need to update naming to reflect the shakemap version once can get
    # getHeaderData to work, add edict['version'] back into title, maybe
    # shakemap id also?
    fontsizemain = 14.
    fontsizesub = 12.
    fontsizesmallest = 10.
    if rowpan == 1.:
        fontsizemain = 12.
        fontsizesub = 10.
        fontsizesmallest = 8.
    if edict is not None:
        if isScenario:
            title = edict['event_description']
        else:
            timestr = edict['event_timestamp'].strftime('%b %d %Y')
            title = 'M%.1f %s v%i - %s' % (edict['magnitude'], timestr, edict['version'], edict['event_description'])
        plt.suptitle(title+'\n'+suptitle, fontsize=fontsizemain)
    else:
        plt.suptitle(suptitle, fontsize=fontsizemain)

    clear_color = [0, 0, 0, 0.0]

    # Cut all of them and release extra memory

    xbuff = (bxmax-bxmin)/10.
    ybuff = (bymax-bymin)/10.
    cutxmin = bxmin-xbuff
    cutymin = bymin-ybuff
    cutxmax = bxmax+xbuff
    cutymax = bymax+ybuff
    if cut is True:
        newgrids = collections.OrderedDict()
        for k, layer in enumerate(plotorder):
            templayer = grids[layer]['grid']
            try:
                newgrids[layer] = {'grid': templayer.cut(cutxmin, cutxmax, cutymin, cutymax, align=True)}
            except Exception as e:
                print(('Cutting failed, %s, continuing with full layers' % e))
                newgrids = grids
                continue
        del templayer
        gc.collect()
    else:
        newgrids = grids
    tempgdict = newgrids[list(grids.keys())[0]]['grid'].getGeoDict()

    # Upsample layers to same as topofile if desired for better looking hillshades
    if upsample is True and topofile is not None:
        try:
            topodict = GDALGrid.getFileGeoDict(topofile)
            if topodict.dx >= tempgdict.dx or topodict.dy >= tempgdict.dy:
                print('Upsampling not possible, resolution of results already smaller than DEM')
                pass
            else:
                tempgdict1 = GeoDict({'xmin': tempgdict.xmin-xbuff,
                                      'ymin': tempgdict.ymin-ybuff,
                                      'xmax': tempgdict.xmax+xbuff,
                                      'ymax': tempgdict.ymax+ybuff,
                                      'dx': topodict.dx,
                                      'dy': topodict.dy,
                                      'nx': topodict.nx,
                                      'ny': topodict.ny},
                                     adjust='res')
                tempgdict2 = tempgdict1.getBoundsWithin(tempgdict)
                for k, layer in enumerate(plotorder):
                    newgrids[layer]['grid'] = newgrids[layer]['grid'].subdivide(tempgdict2)
        except:
            print('Upsampling failed, continuing')

    # Downsample all of them for plotting, if needed, and replace them in
    # grids (to save memory)
    tempgrid = newgrids[list(grids.keys())[0]]['grid']
    xsize = tempgrid.getGeoDict().nx
    ysize = tempgrid.getGeoDict().ny
    inchesx, inchesy = fig.get_size_inches()
    divx = int(np.round(xsize/(500.*inchesx)))
    divy = int(np.round(ysize/(500.*inchesy)))
    xmin, xmax, ymin, ymax = tempgrid.getBounds()
    gdict = tempgrid.getGeoDict()  # Will be replaced if downsampled
    del tempgrid
    gc.collect()

    if divx <= 1:
        divx = 1
    if divy <= 1:
        divy = 1
    if (divx > 1. or divy > 1.) and ds:
        if dstype == 'max':
            func = np.nanmax
        elif dstype == 'min':
            func = np.nanmin
        elif dstype == 'med':
            func = np.nanmedian
        else:
            func = np.nanmean
        for k, layer in enumerate(plotorder):
            layergrid = newgrids[layer]['grid']
            dat = block_reduce(layergrid.getData().copy(),
                               block_size=(divy, divx),
                               cval=float('nan'),
                               func=func)
            if k == 0:
                lons = block_reduce(np.linspace(xmin, xmax, layergrid.getGeoDict().nx),
                                    block_size=(divx,),
                                    func=np.mean,
                                    cval=float('nan'))
                if math.isnan(lons[-1]):
                    lons[-1] = lons[-2] + (lons[1]-lons[0])
                lats = block_reduce(np.linspace(ymax, ymin, layergrid.getGeoDict().ny),
                                    block_size=(divy,),
                                    func=np.mean,
                                    cval=float('nan'))
                if math.isnan(lats[-1]):
                    lats[-1] = lats[-2] + (lats[1]-lats[0])
                gdict = GeoDict({'xmin': lons.min(),
                                 'xmax': lons.max(),
                                 'ymin': lats.min(),
                                 'ymax': lats.max(),
                                 'dx': np.abs(lons[1]-lons[0]),
                                 'dy': np.abs(lats[1]-lats[0]),
                                 'nx': len(lons),
                                 'ny': len(lats)},
                                adjust='res')
            newgrids[layer]['grid'] = Grid2D(dat, gdict)
        del layergrid, dat
    else:
        lons = np.linspace(xmin, xmax, xsize)
        lats = np.linspace(ymax, ymin, ysize)  # backwards so it plots right side up

    #make meshgrid
    llons1, llats1 = np.meshgrid(lons, lats)

    # See if there is an oceanfile for masking
    bbox = PolygonSH(((cutxmin, cutymin), (cutxmin, cutymax), (cutxmax, cutymax), (cutxmax, cutymin)))
    if oceanfile is not None:
        try:
            f = fiona.open(oceanfile)
            oc = next(f)
            f.close
            shapes = shape(oc['geometry'])
            # make boundaries into a shape
            ocean = shapes.intersection(bbox)
        except:
            print('Not able to read specified ocean file, will use default ocean masking')
            oceanfile = None
    if inventory_shapefile is not None:
        try:
            f = fiona.open(inventory_shapefile)
            invshp = list(f.items(bbox=(bxmin, bymin, bxmax, bymax)))
            f.close()
            inventory = [shape(inv[1]['geometry']) for inv in invshp]
        except:
            print('unable to read inventory shapefile specified, will not plot inventory')
            inventory_shapefile = None

    # # Find cities that will be plotted
    if mapcities is True and cityfile is not None:
        try:
            mycity = BasemapCities.loadFromGeoNames(cityfile=cityfile)
            bcities = mycity.limitByBounds((bxmin, bxmax, bymin, bymax))
            #bcities = bcities.limitByPopulation(40000)
            bcities = bcities.limitByGrid(nx=4, ny=4, cities_per_grid=2)
        except:
            print('Could not read in cityfile, not plotting cities')
            mapcities = False
            cityfile = None

    # Load in topofile
    if topofile is not None:
        try:
            topomap = GDALGrid.load(topofile, resample=True, method='linear', samplegeodict=gdict)
        except:
            topomap = GMTGrid.load(topofile, resample=True, method='linear', samplegeodict=gdict)
        topodata = topomap.getData().copy()
        # mask oceans if don't have ocean shapefile
        if oceanfile is None:
            topodata = maskoceans(llons1, llats1, topodata, resolution='h', grid=1.25, inlands=True)
    else:
        print('no hillshade is possible\n')
        topomap = None
        topodata = None

    # Load in roads, if needed
    if maproads is True and roadfolder is not None:
        try:
            roadslist = []
            for folder in os.listdir(roadfolder):
                road1 = os.path.join(roadfolder, folder)
                shpfiles = glob.glob(os.path.join(road1, '*.shp'))
                if len(shpfiles):
                    shpfile = shpfiles[0]
                    f = fiona.open(shpfile)
                    shapes = list(f.items(bbox=(bxmin, bymin, bxmax, bymax)))
                    for shapeid, shapedict in shapes:
                        roadslist.append(shapedict)
                    f.close()
        except:
            print('Not able to plot roads')
            roadslist = None

    val = 1
    for k, layer in enumerate(plotorder):
        layergrid = newgrids[layer]['grid']
        if 'label' in list(grids[layer].keys()):
            label1 = grids[layer]['label']
        else:
            label1 = layer
        try:
            sref = grids[layer]['description']['name']
        except:
            sref = None
        ax = fig.add_subplot(rowpan, colpan, val)
        val += 1
        clat = bymin + (bymax-bymin)/2.0
        clon = bxmin + (bxmax-bxmin)/2.0
        # setup of basemap ('lcc' = lambert conformal conic).
        # use major and minor sphere radii from WGS84 ellipsoid.
        m = Basemap(llcrnrlon=bxmin, llcrnrlat=bymin, urcrnrlon=bxmax, urcrnrlat=bymax,
                    rsphere=(6378137.00, 6356752.3142),
                    resolution='l', area_thresh=1000., projection='lcc',
                    lat_1=clat, lon_0=clon, ax=ax)

        x1, y1 = m(llons1, llats1)  # get projection coordinates
        axsize = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
        if k == 0:
            wid, ht = axsize.width, axsize.height
        if colormaps is not None and \
           len(colormaps) == len(newgrids) and \
           colormaps[k] is not None:
            palette = colormaps[k]
        else:  # Find preferred default color map for each type of layer
            if 'prob' in layer.lower() or 'pga' in layer.lower() or \
               'pgv' in layer.lower() or 'cohesion' in layer.lower() or \
               'friction' in layer.lower() or 'fs' in layer.lower():
                palette = cm.jet
            elif 'slope' in layer.lower():
                palette = cm.gnuplot2
            elif 'precip' in layer.lower():
                palette = cm2.s3pcpn
            else:
                palette = defaultcolormap

        if topodata is not None:
            if k == 0:
                ptopo = m.transform_scalar(
                    np.flipud(topodata), lons+0.5*gdict.dx,
                    lats[::-1]-0.5*gdict.dy, np.round(300.*wid),
                    np.round(300.*ht), returnxy=False, checkbounds=False,
                    order=1, masked=False)
                #use lightsource class to make our shaded topography
                ls = LightSource(azdeg=135, altdeg=45)
                ls1 = LightSource(azdeg=120, altdeg=45)
                ls2 = LightSource(azdeg=225, altdeg=45)
                intensity1 = ls1.hillshade(ptopo, fraction=0.25, vert_exag=1.)
                intensity2 = ls2.hillshade(ptopo, fraction=0.25, vert_exag=1.)
                intensity = intensity1*0.5 + intensity2*0.5
                #hillshm_im = m.transform_scalar(np.flipud(hillshm), lons, lats[::-1], np.round(300.*wid), np.round(300.*ht), returnxy=False, checkbounds=False, order=0, masked=False)
            #m.imshow(hillshm_im, cmap='Greys', vmin=0., vmax=3., zorder=1, interpolation='none')  # vmax = 3 to soften colors to light gray
            #m.pcolormesh(x1, y1, hillshm, cmap='Greys', linewidth=0., rasterized=True, vmin=0., vmax=3., edgecolors='none', zorder=1);
            # plt.draw()

        # Get the data
        dat = layergrid.getData().copy()

        # mask out anything below any specified thresholds
        # Might need to move this up to before downsampling...might give illusion of no hazard in places where there is some that just got averaged out
        if maskthreshes is not None and len(maskthreshes) == len(newgrids):
            if maskthreshes[k] is not None:
                dat[dat <= maskthreshes[k]] = float('NaN')
                dat = np.ma.array(dat, mask=np.isnan(dat))

        if logscale is not False and len(logscale) == len(newgrids):
            if logscale[k] is True:
                dat = np.log10(dat)
                label1 = r'$log_{10}$(' + label1 + ')'

        if scaletype.lower() == 'binned':
            # Find order of range to know how to scale
            order = np.round(np.log(np.nanmax(dat) - np.nanmin(dat)))
            if order < 1.:
                scal = 10**-order
            else:
                scal = 1.
            if lims is None or len(lims) != len(newgrids):
                clev = (np.linspace(np.floor(scal*np.nanmin(dat)), np.ceil(scal*np.nanmax(dat)), 10))/scal
            else:
                if lims[k] is None:
                    clev = (np.linspace(np.floor(scal*np.nanmin(dat)), np.ceil(scal*np.nanmax(dat)), 10))/scal
                else:
                    clev = lims[k]
            # Adjust to colorbar levels
            dat[dat < clev[0]] = clev[0]
            for j, level in enumerate(clev[:-1]):
                dat[(dat >= clev[j]) & (dat < clev[j+1])] = clev[j]
            # So colorbar saturates at top
            dat[dat > clev[-1]] = clev[-1]
            #panelhandle = m.contourf(x1, y1, datm, clev, cmap=palette, linewidth=0., alpha=ALPHA, rasterized=True)
            vmin = clev[0]
            vmax = clev[-1]
        else:
            if lims is not None and len(lims) == len(newgrids):
                if lims[k] is None:
                    vmin = np.nanmin(dat)
                    vmax = np.nanmax(dat)
                else:
                    vmin = lims[k][0]
                    vmax = lims[k][-1]
            else:
                vmin = np.nanmin(dat)
                vmax = np.nanmax(dat)

        # Mask out cells overlying oceans or block with a shapefile if available
        if oceanfile is None:
            dat = maskoceans(llons1, llats1, dat, resolution='h', grid=1.25, inlands=True)
        else:
            #patches = []
            if type(ocean) is PolygonSH:
                ocean = [ocean]
            for oc in ocean:
                patch = getProjectedPatch(oc, m, edgecolor="#006280", facecolor=watercolor, lw=0.5, zorder=4.)
                #x, y = m(oc.exterior.xy[0], oc.exterior.xy[1])
                #xy = zip(x, y)
                #patch = Polygon(xy, facecolor=watercolor, edgecolor="#006280", lw=0.5, zorder=4.)
                ##patches.append(Polygon(xy, facecolor=watercolor, edgecolor=watercolor, zorder=500.))
                ax.add_patch(patch)
            ##ax.add_collection(PatchCollection(patches))

        if inventory_shapefile is not None:
            for in1 in inventory:
                if 'point' in str(type(in1)):
                    x, y = in1.xy
                    x = x[0]
                    y = y[0]
                    m.scatter(x, y, c='m', s=50, latlon=True, marker='^',
                              zorder=100001)
                else:
                    x, y = m(in1.exterior.xy[0], in1.exterior.xy[1])
                    xy = list(zip(x, y))
                    patch = Polygon(xy, facecolor='none', edgecolor='k', lw=0.5, zorder=10.)
                    #patches.append(Polygon(xy, facecolor=watercolor, edgecolor=watercolor, zorder=500.))
                    ax.add_patch(patch)
        palette.set_bad(clear_color, alpha=0.0)
        # Plot it up
        dat_im = m.transform_scalar(
            np.flipud(dat), lons+0.5*gdict.dx, lats[::-1]-0.5*gdict.dy,
            np.round(300.*wid), np.round(300.*ht), returnxy=False,
            checkbounds=False, order=0, masked=True)
        if topodata is not None:  # Drape over hillshade
            #turn data into an RGBA image
            cmap = palette
            #adjust data so scaled between vmin and vmax and between 0 and 1
            dat1 = dat_im.copy()
            dat1[dat1 < vmin] = vmin
            dat1[dat1 > vmax] = vmax
            dat1 = (dat1 - vmin)/(vmax-vmin)
            rgba_img = cmap(dat1)
            maskvals = np.dstack((dat1.mask, dat1.mask, dat1.mask))
            rgb = np.squeeze(rgba_img[:, :, 0:3])
            rgb[maskvals] = 1.
            draped_hsv = ls.blend_hsv(rgb, np.expand_dims(intensity, 2))
            m.imshow(draped_hsv, zorder=3., interpolation='none')
            # This is just a dummy layer that will be deleted to make the
            # colorbar look right
            panelhandle = m.imshow(dat_im, cmap=palette, zorder=0.,
                                   vmin=vmin, vmax=vmax)
        else:
            panelhandle = m.imshow(dat_im, cmap=palette, zorder=3.,
                                   vmin=vmin, vmax=vmax, interpolation='none')
        #panelhandle = m.pcolormesh(x1, y1, dat, linewidth=0., cmap=palette, vmin=vmin, vmax=vmax, alpha=ALPHA, rasterized=True, zorder=2.);
        #panelhandle.set_edgecolors('face')
        # add colorbar
        cbfmt = '%1.1f'
        if vmax is not None and vmin is not None:
            if (vmax - vmin) < 1.:
                cbfmt = '%1.2f'
            elif vmax > 5.:  # (vmax - vmin) > len(clev):
                cbfmt = '%1.0f'

        #norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)
        if scaletype.lower() == 'binned':
            cbar = fig.colorbar(panelhandle, spacing='proportional',
                                ticks=clev, boundaries=clev, fraction=0.036,
                                pad=0.04, format=cbfmt, extend='both')
            #cbar1 = ColorbarBase(cbar.ax, cmap=palette, norm=norm, spacing='proportional', ticks=clev, boundaries=clev, fraction=0.036, pad=0.04, format=cbfmt, extend='both', extendfrac='auto')

        else:
            cbar = fig.colorbar(panelhandle, fraction=0.036, pad=0.04,
                                extend='both', format=cbfmt)
            #cbar1 = ColorbarBase(cbar.ax, cmap=palette, norm=norm, fraction=0.036, pad=0.04, extend='both', extendfrac='auto', format=cbfmt)

        if topodata is not None:
            panelhandle.remove()

        cbar.set_label(label1, fontsize=10)
        cbar.ax.tick_params(labelsize=8)

        parallels = m.drawparallels(getMapLines(bymin, bymax, 3),
                                    labels=[1, 0, 0, 0], linewidth=0.5,
                                    labelstyle='+/-', fontsize=9, xoffset=-0.8,
                                    color='gray', zorder=100.)
        m.drawmeridians(getMapLines(bxmin, bxmax, 3), labels=[0, 0, 0, 1],
                        linewidth=0.5, labelstyle='+/-', fontsize=9,
                        color='gray', zorder=100.)
        for par in parallels:
            try:
                parallels[par][1][0].set_rotation(90)
            except:
                pass

        #draw roads on the map, if they were provided to us
        if maproads is True and roadslist is not None:
            try:
                for road in roadslist:
                    try:
                        xy = list(road['geometry']['coordinates'])
                        roadx, roady = list(zip(*xy))
                        mapx, mapy = m(roadx, roady)
                        m.plot(mapx, mapy, roadcolor, lw=0.5, zorder=9)
                    except:
                        continue
            except Exception as e:
                print(('Failed to plot roads, %s' % e))

        #add city names to map
        if mapcities is True and cityfile is not None:
            try:
                fontname = 'Arial'
                fontsize = 8
                if k == 0:  # Only need to choose cities first time and then apply to rest
                    fcities = bcities.limitByMapCollision(
                        m, fontname=fontname, fontsize=fontsize)
                    ctlats, ctlons, names = fcities.getCities()
                    cxis, cyis = m(ctlons, ctlats)
                for ctlat, ctlon, cxi, cyi, name in zip(ctlats, ctlons, cxis, cyis, names):
                    m.scatter(ctlon, ctlat, c='k', latlon=True, marker='.',
                              zorder=100000)
                    ax.text(cxi, cyi, name, fontname=fontname,
                            fontsize=fontsize, zorder=100000)
            except Exception as e:
                print('Failed to plot cities, %s' % e)

        #draw star at epicenter
        plt.sca(ax)
        if edict is not None:
            elat, elon = edict['lat'], edict['lon']
            ex, ey = m(elon, elat)
            plt.plot(ex, ey, '*', markeredgecolor='k', mfc='None', mew=1.0,
                     ms=15, zorder=10000.)

        m.drawmapboundary(fill_color=watercolor)

        m.fillcontinents(color=clear_color, lake_color=watercolor)
        m.drawrivers(color=watercolor)
        ##m.drawcoastlines()

        #draw country boundaries
        m.drawcountries(color=countrycolor, linewidth=1.0)

        #add map scale
        m.drawmapscale((bxmax+bxmin)/2., (bymin+(bymax-bymin)/9.), clon, clat, np.round((((bxmax-bxmin)*111)/5)/10.)*10, barstyle='fancy', zorder=10)

        # Add border
        autoAxis = ax.axis()
        rec = Rectangle((autoAxis[0]-0.7, autoAxis[2]-0.2), (autoAxis[1]-autoAxis[0])+1, (autoAxis[3]-autoAxis[2])+0.4, fill=False, lw=1, zorder=1e8)
        rec = ax.add_patch(rec)
        rec.set_clip_on(False)

        plt.draw()

        if sref is not None:
            label2 = '%s\nsource: %s' % (label1, sref)  # '%s\n' % label1 + r'{\fontsize{10pt}{3em}\selectfont{}%s}' % sref  #
        else:
            label2 = label1
        plt.title(label2, axes=ax, fontsize=fontsizesub)

        #draw scenario watermark, if scenario
        if isScenario:
            plt.sca(ax)
            cx, cy = m(clon, clat)
            plt.text(cx, cy, 'SCENARIO', rotation=45, alpha=0.10, size=72, ha='center', va='center', color='red')

        #if ds: # Could add this to print "downsampled" on map
        #    plt.text()

        if k == 1 and rowpan == 1:
            # adjust single level plot
            axsize = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
            ht2 = axsize.height
            fig.set_figheight(ht2*1.6)
        else:
            plt.tight_layout()

        # Make room for suptitle - tight layout doesn't account for it
        plt.subplots_adjust(top=0.92)

    if printparam is True:
        try:
            fig = plt.gcf()
            dictionary = grids['model']['description']['parameters']
            paramstring = 'Model parameters: '
            halfway = np.ceil(len(dictionary)/2.)
            for i, key in enumerate(dictionary):
                if i == halfway and colpan == 1:
                    paramstring += '\n'
                paramstring += ('%s = %s; ' % (key, dictionary[key]))
            print(paramstring)
            fig.text(0.01, 0.015, paramstring, fontsize=fontsizesmallest)
            plt.draw()
        except:
            print('Could not display model parameters')

    if edict is not None:
        eventid = edict['eventid']
    else:
        eventid = ''

    time1 = datetime.datetime.utcnow().strftime('%d%b%Y_%H%M')
    outfile = os.path.join(outfolder, '%s_%s_%s.pdf' % (eventid, suptitle, time1))
    pngfile = os.path.join(outfolder, '%s_%s_%s.png' % (eventid, suptitle, time1))

    if savepdf is True:
        print('Saving map output to %s' % outfile)
        plt.savefig(outfile, dpi=300)
    if savepng is True:
        print('Saving map output to %s' % pngfile)
        plt.savefig(pngfile)
    if showplots is True:
        plt.show()
    else:
        plt.close(fig)

    return newgrids
Exemplo n.º 10
0
def test_bounds_within():
    host = GeoDict({
        'xmin': -180,
        'xmax': 150,
        'ymin': -90,
        'ymax': 90,
        'dx': 30,
        'dy': 45,
        'nx': 12,
        'ny': 5
    })
    sample = GeoDict({
        'xmin': -75,
        'xmax': 45,
        'ymin': -67.5,
        'ymax': 67.5,
        'dx': 30,
        'dy': 45,
        'nx': 5,
        'ny': 4
    })

    result = GeoDict({
        'xmin': -60,
        'xmax': 30,
        'ymin': -45,
        'ymax': 45,
        'dx': 30,
        'dy': 45,
        'nx': 4,
        'ny': 3
    })

    inside = host.getBoundsWithin(sample)
    assert inside == result

    # test degenerate case where first pass at getting inside bounds fails (xmax)
    host = GeoDict({
        'ymax': 84.0,
        'dx': 0.008333333333333333,
        'ny': 16801,
        'xmax': 179.99166666666667,
        'xmin': -180.0,
        'nx': 43200,
        'dy': 0.008333333333333333,
        'ymin': -56.0
    })

    sample = GeoDict({
        'ymax': 18.933333333333334,
        'dx': 0.008333333333333333,
        'ny': 877,
        'xmax': -90.28333333333333,
        'xmin': -97.86666666666666,
        'nx': 911,
        'dy': 0.008333333333333333,
        'ymin': 11.633333333333333
    })
    inside = host.getBoundsWithin(sample)
    assert sample.contains(inside)

    #this tests some logic that I can't figure out
    #a way to make happen inside getBoundsWithin().
    newymin, ymin = (11.63333333333334, 11.633333333333333)
    fdy = 0.008333333333333333
    yminrow = 8684.0
    fymax = 84.0
    newymin -= fdy / 2  #bump it down
    while newymin <= ymin:
        yminrow = yminrow - 1
        newymin = fymax - yminrow * fdy
    assert newymin > ymin
Exemplo n.º 11
0
def test():
    #these values taken from the shakemap header of:
    #http://earthquake.usgs.gov/realtime/product/shakemap/ak12496371/ak/1453829475592/download/grid.xml

    print('Testing various dictionaries for consistency...')

    print('Testing consistent dictionary...')
    #this should pass, and will serve as the comparison from now on
    gdict = {
        'xmin': -160.340600,
        'xmax': -146.340600,
        'ymin': 54.104700,
        'ymax': 65.104700,
        'dx': 0.025000,
        'dy': 0.025000,
        'ny': 441,
        'nx': 561
    }
    gd = GeoDict(gdict)
    print('Consistent dictionary passed.')

    print('Testing dictionary with inconsistent resolution...')
    #this should pass
    gdict = {
        'xmin': -160.340600,
        'xmax': -146.340600,
        'ymin': 54.104700,
        'ymax': 65.104700,
        'dx': 0.026000,
        'dy': 0.026000,
        'ny': 441,
        'nx': 561
    }
    gd3 = GeoDict(gdict, adjust='res')
    assert gd3 == gd
    print('Dimensions modification passed.')

    print('Testing dictionary with inconsistent lower right corner...')
    #this should pass
    gdict = {
        'xmin': -160.340600,
        'xmax': -146.350600,
        'ymin': 54.103700,
        'ymax': 65.104700,
        'dx': 0.025000,
        'dy': 0.025000,
        'ny': 441,
        'nx': 561
    }
    gd4 = GeoDict(gdict, adjust='bounds')
    assert gd4 == gd
    print('Corner modification passed.')

    print(
        'Testing to make sure lat/lon and row/col calculations are correct...')
    #make sure the lat/lon row/col calculations are correct
    ndec = int(np.abs(np.log10(GeoDict.EPS)))
    lat, lon = gd.getLatLon(0, 0)
    dlat = np.abs(lat - gd.ymax)
    dlon = np.abs(lon - gd.xmin)
    assert dlat < GeoDict.EPS and dlon < GeoDict.EPS
    row, col = gd.getRowCol(lat, lon)
    assert row == 0 and col == 0

    lat, lon = gd.getLatLon(gd.ny - 1, gd.nx - 1)
    dlat = np.abs(lat - gd.ymin)
    dlon = np.abs(lon - gd.xmax)
    assert dlat < GeoDict.EPS and dlon < GeoDict.EPS
    row, col = gd.getRowCol(lat, lon)
    assert row == (gd.ny - 1) and col == (gd.nx - 1)
    print('lat/lon and row/col calculations are correct.')

    print('Testing a dictionary for a global grid...')
    #this is the file geodict for Landscan - should pass muster
    globaldict = {
        'nx': 43200,
        'ny': 20880,
        'dx': 0.00833333333333,
        'xmax': 179.99583333318935,
        'xmin': -179.99583333333334,
        'dy': 0.00833333333333,
        'ymax': 83.99583333326376,
        'ymin': -89.99583333333334
    }
    gd5 = GeoDict(globaldict)
    lat, lon = gd5.getLatLon(gd5.ny - 1, gd5.nx - 1)
    dlat = np.abs(lat - gd5.ymin)
    dlon = np.abs(lon - gd5.xmax)
    assert dlat < GeoDict.EPS and dlon < GeoDict.EPS
    print('Global grid is internally consistent.')

    #Test class methods for creating a GeoDict
    print('Testing whether GeoDict creator class methods work...')
    xmin = -121.05333277776235
    xmax = -116.03833388890432
    ymin = 32.138334444506171
    ymax = 36.286665555493826
    dx = 0.0083333333333333332
    dy = 0.0083333333333333332
    gd6 = GeoDict.createDictFromBox(xmin,
                                    xmax,
                                    ymin,
                                    ymax,
                                    dx,
                                    dy,
                                    inside=False)
    assert gd6.xmax > xmax
    assert gd6.ymin < ymin
    print('Created dictionary (outside) is correct.')
    gd7 = GeoDict.createDictFromBox(xmin,
                                    xmax,
                                    ymin,
                                    ymax,
                                    dx,
                                    dy,
                                    inside=True)
    assert gd7.xmax < xmax
    assert gd7.ymin > ymin
    print('Created dictionary (inside) is correct.')
    xspan = 2.5
    yspan = 2.5
    gd8 = GeoDict.createDictFromCenter(xmin, ymin, dx, dy, xspan, yspan)
    print('Created dictionary (from center point) is valid.')

    print('Testing a geodict with dx/dy values that are NOT the same...')
    xmin, xmax, ymin, ymax = (-121.06166611109568, -116.03000055557099,
                              32.130001111172838, 36.294998888827159)
    dx, dy = (0.009999722214505959, 0.009999444413578534)
    td = GeoDict.createDictFromBox(xmin, xmax, ymin, ymax, dx, dy)
    print(
        'Passed testing a geodict with dx/dy values that are NOT the same...')

    #test getBoundsWithin
    #use global grid, and then a shakemap grid that we can get
    print('Testing getBoundsWithin...')
    grussia = {
        'xmin': 155.506400,
        'xmax': 161.506400,
        'ymin': 52.243000,
        'ymax': 55.771000,
        'dx': 0.016667,
        'dy': 0.016642,
        'nx': 361,
        'ny': 213
    }
    gdrussia = GeoDict(grussia, adjust='res')
    sampledict = gd5.getBoundsWithin(gdrussia)
    xSmaller = sampledict.xmin > grussia['xmin'] and sampledict.xmax < grussia[
        'xmax']
    ySmaller = sampledict.ymin > grussia['ymin'] and sampledict.ymax < grussia[
        'ymax']
    assert xSmaller and ySmaller
    assert gd5.isAligned(sampledict)
    print('getBoundsWithin returned correct result.')

    print('Testing isAligned() method...')
    gd = GeoDict({
        'xmin': 0.5,
        'xmax': 3.5,
        'ymin': 0.5,
        'ymax': 3.5,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 4,
        'ny': 4
    })

    inside_aligned = GeoDict({
        'xmin': 1.5,
        'xmax': 2.5,
        'ymin': 1.5,
        'ymax': 2.5,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 2,
        'ny': 2
    })
    inside_not_aligned = GeoDict({
        'xmin': 2.0,
        'xmax': 3.0,
        'ymin': 2.0,
        'ymax': 3.0,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 2,
        'ny': 2
    })
    assert gd.isAligned(inside_aligned)
    assert not gd.isAligned(inside_not_aligned)
    print('Passed isAligned() method...')

    print('Testing getAligned method...')
    popdict = GeoDict({
        'dx': 0.00833333333333,
        'dy': 0.00833333333333,
        'nx': 43200,
        'ny': 20880,
        'xmax': 179.99583333318935,
        'xmin': -179.99583333333334,
        'ymax': 83.99583333326376,
        'ymin': -89.99583333333334
    })
    sampledict = GeoDict({
        'dx': 0.008333333333333333,
        'dy': 0.008336693548387094,
        'nx': 601,
        'ny': 497,
        'xmax': -116.046,
        'xmin': -121.046,
        'ymax': 36.2785,
        'ymin': 32.1435
    })
    aligndict = popdict.getAligned(sampledict)
    assert popdict.isAligned(aligndict)

    print('Testing geodict intersects method...')
    gd1 = GeoDict({
        'xmin': 0.5,
        'xmax': 3.5,
        'ymin': 0.5,
        'ymax': 3.5,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 4,
        'ny': 4
    })

    print('Testing geodict intersects method...')
    gd2 = GeoDict({
        'xmin': 2.5,
        'xmax': 5.5,
        'ymin': 2.5,
        'ymax': 5.5,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 4,
        'ny': 4
    })
    gd3 = GeoDict({
        'xmin': 4.5,
        'xmax': 7.5,
        'ymin': 4.5,
        'ymax': 7.5,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 4,
        'ny': 4
    })
    gd4 = GeoDict({
        'xmin': 1.5,
        'xmax': 2.5,
        'ymin': 1.5,
        'ymax': 2.5,
        'dx': 1.0,
        'dy': 1.0,
        'nx': 2,
        'ny': 2
    })
    assert gd1.intersects(gd2)
    assert not gd1.intersects(gd3)
    print('Passed intersects method...')

    print('Testing geodict intersects method with real geographic data...')
    gda = GeoDict({
        'ymax': 83.62083333333263,
        'nx': 43201,
        'ny': 20835,
        'dx': 0.00833333333333,
        'dy': 0.00833333333333,
        'xmin': -179.99583333333334,
        'ymin': -89.99583333326461,
        'xmax': -179.99583333347732
    })
    gdb = GeoDict({
        'ymax': 28.729166666619193,
        'nx': 300,
        'ny': 264,
        'dx': 0.00833333333333,
        'dy': 0.00833333333333,
        'xmin': 84.08749999989436,
        'ymin': 26.537499999953404,
        'xmax': 86.57916666656007
    })
    assert gda.intersects(gdb)
    print('Passed geodict intersects method with real geographic data.')

    print('Testing geodict doesNotContain method...')
    assert gd1.doesNotContain(gd3)
    assert not gd1.doesNotContain(gd4)

    print('Passed doesNotContain method...')

    print('Testing geodict contains method...')

    assert gd1.contains(gd4)
    assert not gd1.contains(gd3)
    print('Passed contains method...')
Exemplo n.º 12
0
def test_bounds_within():
    host = GeoDict({'xmin': -180,
                    'xmax': 150,
                    'ymin': -90,
                    'ymax': 90,
                    'dx': 30,
                    'dy': 45,
                    'nx': 12,
                    'ny': 5})
    sample = GeoDict({'xmin': -75,
                      'xmax': 45,
                      'ymin': -67.5,
                      'ymax': 67.5,
                      'dx': 30,
                      'dy': 45,
                      'nx': 5,
                      'ny': 4})

    result = GeoDict({'xmin': -60,
                      'xmax': 30,
                      'ymin': -45,
                      'ymax': 45,
                      'dx': 30,
                      'dy': 45,
                      'nx': 4,
                      'ny': 3})

    inside = host.getBoundsWithin(sample)
    assert inside == result

    # test degenerate case where first pass at getting inside bounds fails (xmax)
    host = GeoDict({'ymax': 84.0,
                    'dx': 0.008333333333333333,
                    'ny': 16801,
                    'xmax': 179.99166666666667,
                    'xmin': -180.0,
                    'nx': 43200,
                    'dy': 0.008333333333333333,
                    'ymin': -56.0})

    sample = GeoDict({'ymax': 18.933333333333334,
                      'dx': 0.008333333333333333,
                      'ny': 877,
                      'xmax': -90.28333333333333,
                      'xmin': -97.86666666666666,
                      'nx': 911,
                      'dy': 0.008333333333333333,
                      'ymin': 11.633333333333333})
    inside = host.getBoundsWithin(sample)
    assert sample.contains(inside)

    # this tests some logic that I can't figure out
    # a way to make happen inside getBoundsWithin().
    newymin, ymin = (11.63333333333334, 11.633333333333333)
    fdy = 0.008333333333333333
    yminrow = 8684.0
    fymax = 84.0
    newymin -= fdy/2  # bump it down
    while newymin <= ymin:
        yminrow = yminrow - 1
        newymin = fymax - yminrow*fdy
    assert newymin > ymin
Exemplo n.º 13
0
def test():
    # these values taken from the shakemap header of:
    # http://earthquake.usgs.gov/realtime/product/shakemap/ak12496371/ak/1453829475592/download/grid.xml

    print('Testing various dictionaries for consistency...')

    print('Testing consistent dictionary...')
    # this should pass, and will serve as the comparison from now on
    gdict = {'xmin': -160.340600, 'xmax': -146.340600,
             'ymin': 54.104700, 'ymax': 65.104700,
             'dx': 0.025000, 'dy': 0.025000,
             'ny': 441, 'nx': 561}
    gd = GeoDict(gdict)
    print('Consistent dictionary passed.')

    print('Testing dictionary with inconsistent resolution...')
    # this should pass
    gdict = {'xmin': -160.340600, 'xmax': -146.340600,
             'ymin': 54.104700, 'ymax': 65.104700,
             'dx': 0.026000, 'dy': 0.026000,
             'ny': 441, 'nx': 561}
    gd3 = GeoDict(gdict, adjust='res')
    assert gd3 == gd
    print('Dimensions modification passed.')

    print('Testing dictionary with inconsistent lower right corner...')
    # this should pass
    gdict = {'xmin': -160.340600, 'xmax': -146.350600,
             'ymin': 54.103700, 'ymax': 65.104700,
             'dx': 0.025000, 'dy': 0.025000,
             'ny': 441, 'nx': 561}
    gd4 = GeoDict(gdict, adjust='bounds')
    assert gd4 == gd
    print('Corner modification passed.')

    print('Testing to make sure lat/lon and row/col calculations are correct...')
    # make sure the lat/lon row/col calculations are correct
    ndec = int(np.abs(np.log10(GeoDict.EPS)))
    lat, lon = gd.getLatLon(0, 0)
    dlat = np.abs(lat-gd.ymax)
    dlon = np.abs(lon-gd.xmin)
    assert dlat < GeoDict.EPS and dlon < GeoDict.EPS
    row, col = gd.getRowCol(lat, lon)
    assert row == 0 and col == 0

    lat, lon = gd.getLatLon(gd.ny-1, gd.nx-1)
    dlat = np.abs(lat-gd.ymin)
    dlon = np.abs(lon-gd.xmax)
    assert dlat < GeoDict.EPS and dlon < GeoDict.EPS
    row, col = gd.getRowCol(lat, lon)
    assert row == (gd.ny-1) and col == (gd.nx-1)
    print('lat/lon and row/col calculations are correct.')

    print('Testing a dictionary for a global grid...')
    # this is the file geodict for Landscan - should pass muster
    globaldict = {'nx': 43200,
                  'ny': 20880,
                  'dx': 0.00833333333333,
                  'xmax': 179.99583333318935,
                  'xmin': -179.99583333333334,
                  'dy': 0.00833333333333,
                  'ymax': 83.99583333326376,
                  'ymin': -89.99583333333334}
    gd5 = GeoDict(globaldict)
    lat, lon = gd5.getLatLon(gd5.ny-1, gd5.nx-1)
    dlat = np.abs(lat-gd5.ymin)
    dlon = np.abs(lon-gd5.xmax)
    assert dlat < GeoDict.EPS and dlon < GeoDict.EPS
    print('Global grid is internally consistent.')

    # Test class methods for creating a GeoDict
    print('Testing whether GeoDict creator class methods work...')
    xmin = -121.05333277776235
    xmax = -116.03833388890432
    ymin = 32.138334444506171
    ymax = 36.286665555493826
    dx = 0.0083333333333333332
    dy = 0.0083333333333333332
    gd6 = GeoDict.createDictFromBox(
        xmin, xmax, ymin, ymax, dx, dy, inside=False)
    assert gd6.xmax > xmax
    assert gd6.ymin < ymin
    print('Created dictionary (outside) is correct.')
    gd7 = GeoDict.createDictFromBox(
        xmin, xmax, ymin, ymax, dx, dy, inside=True)
    assert gd7.xmax < xmax
    assert gd7.ymin > ymin
    print('Created dictionary (inside) is correct.')
    xspan = 2.5
    yspan = 2.5
    gd8 = GeoDict.createDictFromCenter(xmin, ymin, dx, dy, xspan, yspan)
    print('Created dictionary (from center point) is valid.')

    print('Testing a geodict with dx/dy values that are NOT the same...')
    xmin, xmax, ymin, ymax = (-121.06166611109568, -116.03000055557099,
                              32.130001111172838, 36.294998888827159)
    dx, dy = (0.009999722214505959, 0.009999444413578534)
    td = GeoDict.createDictFromBox(xmin, xmax, ymin, ymax, dx, dy)
    print('Passed testing a geodict with dx/dy values that are NOT the same...')

    # test getBoundsWithin
    # use global grid, and then a shakemap grid that we can get
    print('Testing getBoundsWithin...')
    grussia = {'xmin': 155.506400, 'xmax': 161.506400,
               'ymin': 52.243000, 'ymax': 55.771000,
               'dx': 0.016667, 'dy': 0.016642,
               'nx': 361, 'ny': 213}
    gdrussia = GeoDict(grussia, adjust='res')
    sampledict = gd5.getBoundsWithin(gdrussia)
    xSmaller = sampledict.xmin > grussia['xmin'] and sampledict.xmax < grussia['xmax']
    ySmaller = sampledict.ymin > grussia['ymin'] and sampledict.ymax < grussia['ymax']
    assert xSmaller and ySmaller
    assert gd5.isAligned(sampledict)
    print('getBoundsWithin returned correct result.')

    print('Testing isAligned() method...')
    gd = GeoDict({'xmin': 0.5, 'xmax': 3.5,
                  'ymin': 0.5, 'ymax': 3.5,
                  'dx': 1.0, 'dy': 1.0,
                  'nx': 4, 'ny': 4})

    inside_aligned = GeoDict({'xmin': 1.5, 'xmax': 2.5,
                              'ymin': 1.5, 'ymax': 2.5,
                              'dx': 1.0, 'dy': 1.0,
                              'nx': 2, 'ny': 2})
    inside_not_aligned = GeoDict({'xmin': 2.0, 'xmax': 3.0,
                                  'ymin': 2.0, 'ymax': 3.0,
                                  'dx': 1.0, 'dy': 1.0,
                                  'nx': 2, 'ny': 2})
    assert gd.isAligned(inside_aligned)
    assert not gd.isAligned(inside_not_aligned)
    print('Passed isAligned() method...')

    print('Testing getAligned method...')
    popdict = GeoDict({'dx': 0.00833333333333,
                       'dy': 0.00833333333333,
                       'nx': 43200,
                       'ny': 20880,
                       'xmax': 179.99583333318935,
                       'xmin': -179.99583333333334,
                       'ymax': 83.99583333326376,
                       'ymin': -89.99583333333334})
    sampledict = GeoDict({'dx': 0.008333333333333333,
                          'dy': 0.008336693548387094,
                          'nx': 601,
                          'ny': 497,
                          'xmax': -116.046,
                          'xmin': -121.046,
                          'ymax': 36.2785,
                          'ymin': 32.1435})
    aligndict = popdict.getAligned(sampledict)
    assert popdict.isAligned(aligndict)

    print('Testing geodict intersects method...')
    gd1 = GeoDict({'xmin': 0.5, 'xmax': 3.5,
                   'ymin': 0.5, 'ymax': 3.5,
                   'dx': 1.0, 'dy': 1.0,
                   'nx': 4, 'ny': 4})

    print('Testing geodict intersects method...')
    gd2 = GeoDict({'xmin': 2.5, 'xmax': 5.5,
                   'ymin': 2.5, 'ymax': 5.5,
                   'dx': 1.0, 'dy': 1.0,
                   'nx': 4, 'ny': 4})
    gd3 = GeoDict({'xmin': 4.5, 'xmax': 7.5,
                   'ymin': 4.5, 'ymax': 7.5,
                   'dx': 1.0, 'dy': 1.0,
                   'nx': 4, 'ny': 4})
    gd4 = GeoDict({'xmin': 1.5, 'xmax': 2.5,
                   'ymin': 1.5, 'ymax': 2.5,
                   'dx': 1.0, 'dy': 1.0,
                   'nx': 2, 'ny': 2})
    assert gd1.intersects(gd2)
    assert not gd1.intersects(gd3)
    print('Passed intersects method...')

    print('Testing geodict intersects method with real geographic data...')
    gda = GeoDict({'ymax': 83.62083333333263, 'nx': 43201,
                   'ny': 20835, 'dx': 0.00833333333333,
                   'dy': 0.00833333333333, 'xmin': -179.99583333333334,
                   'ymin': -89.99583333326461, 'xmax': -179.99583333347732})
    gdb = GeoDict({'ymax': 28.729166666619193, 'nx': 300,
                   'ny': 264, 'dx': 0.00833333333333,
                   'dy': 0.00833333333333, 'xmin': 84.08749999989436,
                   'ymin': 26.537499999953404, 'xmax': 86.57916666656007})
    assert gda.intersects(gdb)
    print('Passed geodict intersects method with real geographic data.')

    print('Testing geodict doesNotContain method...')
    assert gd1.doesNotContain(gd3)
    assert not gd1.doesNotContain(gd4)

    print('Passed doesNotContain method...')

    print('Testing geodict contains method...')

    assert gd1.contains(gd4)
    assert not gd1.contains(gd3)
    print('Passed contains method...')