示例#1
0
def test_rupture_from_dict():

    # Grab an EdgeRupture
    origin = Origin({
        'id': 'test',
        'lat': 0,
        'lon': 0,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture
    origin = Origin({
        'id': 'test',
        'lon': -122.5,
        'lat': 37.3,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5
示例#2
0
    def getRuptureObject(self):
        """ Retrieve Rupture object from container.

        Returns:
            Rupture: Instance of (one of) a Point/Quad/EdgeRupture class.
        Raises:
            AttributeError: If rupture object has not been set in
                the container.
        """
        rupture_dict = self.getRuptureDict()
        rupture = rupture_from_dict(rupture_dict)
        return rupture
示例#3
0
    def getRuptureObject(self):
        """
        Retrieve Rupture object from container.

        Returns:
            Rupture: Instance of (one of) a Point/Quad/EdgeRupture class.
        Raises:
            AttributeError: If rupture object has not been set in
                the container.
        """
        rupture_dict = self.getRuptureDict()
        rupture = rupture_from_dict(rupture_dict)
        return rupture
示例#4
0
    def setRupture(self, rupture):
        """
        Store Rupture object in container.

        Args:
            rupture (dict or Rupture): Rupture object (Point,Quad, or Edge)
                or dictionary representation of same.
        Raises:
            TypeError: If input object or dictionary does not
                represent a Rupture object.
        """
        if 'rupture' in self.getDictionaries():
            self.dropDictionary([], 'rupture')
        if isinstance(rupture, dict):
            try:
                rupture_from_dict(rupture)
            except Exception:
                fmt = 'Input dict does not represent a rupture object.'
                raise TypeError(fmt)
            rupdict = rupture
        else:
            rupdict = rupture._geojson
        self.setRuptureDict(rupdict)
示例#5
0
def test_rupture_from_dict():
    # Grab an EdgeRupture
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture
    origin = Origin({'eventsourcecode': 'test',
                     'lon': -122.5, 'lat': 37.3,
                     'depth': 5.0, 'mag': 7.0})
    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5
示例#6
0
    def __repr__(self):
        """Return a string representation of the container.
        """
        out = 'Data type: %s\n' % self.getDataType()
        if self.getDataType() == 'grid':
            out = out + '    use "getIMTGrids" method to access '\
                'interpolated IMTs\n'
        else:
            out = out + '    use "getIMTArrays" method to access '\
                'interpolated IMTs\n'
        try:
            rupt = self.getRuptureDict()
            rupt_obj = rupture_from_dict(rupt)
            out = out + "Rupture: %s\n" % type(rupt_obj)
            out = out + "    locstring: %s\n" % rupt_obj._origin.locstring
            out = out + "    magnitude: %.1f\n" % rupt_obj._origin.mag
            out = out + "    time: %s\n" % \
                rupt_obj._origin.time.strftime(queue.TIMEFMT)
        except AttributeError:
            out = out + "Rupture: None\n"
        try:
            self.getConfig()
            out = out + "Config: use 'getConfig' method\n"
        except AttributeError:
            out = out + "Config: None\n"
        try:
            stations = self.getStationDict()['features']
            nsta = len(stations)
            sname = [s['properties']['channels'][0]['name'] for s in stations]
            n_mi = len([s for s in sname if s == 'mmi'])
            out = out + "Stations: use 'getStationDict' method\n"
            out = out + "    # instrumental stations: %i\n" % (nsta - n_mi)
            out = out + "    # macroseismic stations: %i\n" % n_mi
        except AttributeError:
            out = out + "Stations: None\n"
        try:
            self.getMetadata()
            out = out + "Metadata: use 'getMetadata' method\n"
        except LookupError:
            out = out + "Metadata: None\n"
        out = out + "Available IMTs (components):\n"
        imt_list = sorted(self.getIMTs())
        for i in range(len(imt_list)):
            components = self.getComponents(imt_list[i])
            comp_str = ", ".join(components)
            out = out + '    %s (%s)\n' % (imt_list[i], comp_str)

        return out
示例#7
0
    def setRupture(self,rupture):
        """ Store Rupture object in container.

        Args:
            rupture (dict or Rupture): Rupture object (Point,Quad, or Edge)
                or dictionary representation of same.
        Raises:
            TypeError: If input object or dictionary does not
                represent a Rupture object.
        """
        if 'rupture' in self.getStrings():
            self.dropString('rupture')
        if isinstance(rupture,dict):
            try:
                _ = rupture_from_dict(rupture)
            except Exception:
                fmt = 'Input dict does not represent a rupture object.'
                raise TypeError(fmt)
            json_str = json.dumps(rupture)
        else:
            json_str = json.dumps(rupture._geojson)
        self.setString('rupture',json_str)
示例#8
0
    def setRupture(self,rupture):
        """
        Store Rupture object in container.

        Args:
            rupture (dict or Rupture): Rupture object (Point,Quad, or Edge)
                or dictionary representation of same.
        Raises:
            TypeError: If input object or dictionary does not
                represent a Rupture object.
        """
        if 'rupture' in self.getStrings():
            self.dropString('rupture')
        if isinstance(rupture,dict):
            try:
                _ = rupture_from_dict(rupture)
            except Exception:
                fmt = 'Input dict does not represent a rupture object.'
                raise TypeError(fmt)
            json_str = json.dumps(rupture)
        else:
            json_str = json.dumps(rupture._geojson)
        self.setString('rupture',json_str)
示例#9
0
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)
示例#10
0
def test_rupture_from_dict():

    # Grab an EdgeRupture
    origin = Origin({'id': 'test', 'lat': 0, 'lon': 0, 'depth': 5.0,
                     'mag': 7.0, 'netid': 'us', 'network': '',
                     'locstring': '', 'time':
                     HistoricTime.utcfromtimestamp(time.time())})

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture from json
    file = os.path.join(homedir, 'rupture_data/point.json')
    rup = get_rupture(origin, file)
    assert rup.lats == 0
    assert rup.lons == 0

    # Point rupture
    origin = Origin({
        'id': 'test',
        'lon': -122.5, 'lat': 37.3,
        'depth': 5.0, 'mag': 7.0, 'netid': 'us',
        'network': '', 'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5

    assert rup_original.getLength() is None
    assert rup_original.getWidth() == constants.DEFAULT_WIDTH
    assert rup_original.getArea() is None
    assert rup_original.getStrike() == constants.DEFAULT_STRIKE
    assert rup_original.getDip() == constants.DEFAULT_DIP
    assert rup_original.getDepthToTop() == constants.DEFAULT_ZTOR
    assert rup_original.getQuadrilaterals() is None
    assert rup_original.depths == 5.0
    # No mech, no tectonic region
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.757296, 46.614723])
    else:
        print(rjb[0], rrup[0])
    # Various combinations of mech and tectonic region...
    rup_original._origin._tectonic_region = 'Active Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.757296, 46.614723])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [39.779893, 44.033556])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [40.937772, 45.254891])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [46.750567, 48.108934])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin._tectonic_region = 'Stable Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [43.676648, 48.008276])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.445057, 46.865434])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [43.233314, 47.563079])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [47.829729, 50.087485])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin._tectonic_region = 'Somewhere Else'
    rup_original._origin.mech = 'ALL'
    rjb, var = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    rrup, var = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                         np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.757296, 46.614723])
    else:
        print(rjb[0], rrup[0])

    # This is just zeroes now, so there's not much to check
    gc2 = rup_original.computeGC2(np.array([-122.0]), np.array([37.0]),
                                  np.array([0.0]))
    assert gc2['rx'][0] == 0
示例#11
0
def test_rupture_from_dict():

    # Grab an EdgeRupture
    origin = Origin({
        'id': 'test',
        'lat': 0,
        'lon': 0,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture from json
    file = os.path.join(homedir, 'rupture_data/point.json')
    rup = get_rupture(origin, file)
    assert rup.lats == 0
    assert rup.lons == 0

    # Point rupture
    origin = Origin({
        'id': 'test',
        'lon': -122.5,
        'lat': 37.3,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5

    assert rup_original.getLength() is None
    assert rup_original.getWidth() == constants.DEFAULT_WIDTH
    assert rup_original.getArea() is None
    assert rup_original.getStrike() == constants.DEFAULT_STRIKE
    assert rup_original.getDip() == constants.DEFAULT_DIP
    assert rup_original.getDepthToTop() == constants.DEFAULT_ZTOR
    assert rup_original.getQuadrilaterals() is None
    assert rup_original.depths == 5.0
    # No mech, no tectonic region
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [41.11182253, 42.73956168])
    # Various combinations of mech and tectonic region...
    rup_original._origin._tectonic_region = 'Active Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [41.11182253, 42.73956168])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [39.17479645, 41.20916362])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [39.85641875, 41.89222387])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [43.21392667, 44.04215406])
    rup_original._origin._tectonic_region = 'Stable Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [42.68382206, 43.71213495])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [42.29766584, 43.51422441])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [42.57075149, 43.7987126])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [44.19126409, 45.02525107])
    rup_original._origin._tectonic_region = 'Somewhere Else'
    rup_original._origin.mech = 'ALL'
    rjb, var = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    rrup, var = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                         np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [41.11182253, 42.73956168])

    # This is just zeroes now, so there's not much to check
    gc2 = rup_original.computeGC2(np.array([-122.0]), np.array([37.0]),
                                  np.array([0.0]))
    assert gc2['rx'][0] == 0