Exemple #1
0
def main(mw, models, im_list, vs30, rrups, tect_type, output_dir):
    site = classdef.Site()
    site.vs30 = vs30

    fault = classdef.Fault()
    fault.Mw = mw
    fault.tect_type = tect_type

    # Default parameters
    fault.rake = 180
    fault.width = 0.1
    fault.dip = 45
    fault.ztor = 0
    fault.hdepth = 0

    median_im = np.zeros(len(rrups))
    std_dev = np.zeros(len(rrups))

    for im in im_list:
        fig_im, ax_im = plt.subplots()
        for model in models:
            model = classdef.GMM[model]
            for i, rrup in enumerate(rrups):
                site.Rrup = rrup
                site.Rjb = rrup
                result = empirical_factory.compute_gmm(
                    fault, site, model, im.name, im.period
                )
                median_im[i] = result[0]
                std_dev[i] = result[1][0]

            # Individual Model Plot
            fig, ax = plt.subplots()
            ax.loglog(rrups, median_im, color="black", label=model.name)
            ax.loglog(
                rrups, median_im * np.exp(-std_dev), color="black", linestyle="dashed"
            )
            ax.loglog(
                rrups, median_im * np.exp(std_dev), color="black", linestyle="dashed"
            )
            ax.set_xlabel("Rrup (km)")
            ax.set_ylabel(im.pretty_im_name())
            ax.set_title(
                f"Mw: {mw} dip: {fault.dip} rake: {fault.rake} hdepth: {fault.hdepth} - {tect_type}"
            )
            ax.legend()

            # Aggregated model plot for each IM
            ax_im.loglog(rrups, median_im, label=model.name)
            ax_im.set_title(
                f"Mw: {mw} dip: {fault.dip} rake: {fault.rake} hdepth: {fault.hdepth} - {tect_type}"
            )
            fig.savefig(output_dir / f"{im.get_im_name()}_vs_rrup_{model}.png")
            plt.close(fig)

        ax_im.set_xlabel("Rrup (km)")
        ax_im.set_ylabel(im.pretty_im_name())
        ax_im.legend()
        fig_im.savefig(output_dir / f"{im.get_im_name()}_vs_rrup.png")
        plt.close(fig_im)
Exemple #2
0
def test_zhao_2006(set_up):
    set_up = Path(set_up)
    expected_results = pd.read_csv(set_up / "output" / "zhao_output_21p8.csv")

    all_results = {}
    for i, (hdepth, tect_type, site_class, rrup, period) in enumerate(
            itertools.product(hdepths, TECT_TYPES, SITE_CLASSES, rrups,
                              periods)):
        FAULT.hdepth = hdepth
        FAULT.tect_type = tect_type
        SITE.Rrup = rrup
        SITE.siteclass = site_class
        mean, (std_total, std_inter,
               std_intra) = compute_gmm(FAULT, SITE, GMM.ZA_06, IM, period)
        all_results[i] = {
            "period": period,
            "rrup": rrup,
            "siteclass": site_class,
            "tect_type": tect_type,
            "hdepth": hdepth,
            "mean": mean,
            "std_total": std_total,
            "std_inter": std_inter,
            "std_intra": std_intra,
        }
    results_df = pd.DataFrame.from_dict(all_results, orient="index")
    assert np.all(np.isclose(expected_results["mean"], results_df["mean"]))
    assert np.all(
        np.isclose(expected_results["std_total"], results_df["std_total"]))
    assert np.all(
        np.isclose(expected_results["std_inter"], results_df["std_inter"]))
    assert np.all(
        np.isclose(expected_results["std_intra"], results_df["std_intra"]))
Exemple #3
0
def test_Bradley_2013_Sa(set_up, test_rrup):
    SITE.Rrup = test_rrup
    test_results = empirical_factory.compute_gmm(FAULT, SITE, GMM.Br_10, IM,
                                                 PERIODS)

    with open(
            os.path.join(
                set_up, "output",
                "Bradley_2013_Sa_ret_val_rrup_{}.P".format(test_rrup)),
            "rb",
    ) as f:
        expected_results = pickle.load(f)

    assert test_results == expected_results
Exemple #4
0
def test_cb_2012(set_up, test_rrup, test_mag, test_im):
    SITE.Rrup = test_rrup
    FAULT.Mw = test_mag
    test_results = compute_gmm(FAULT, SITE, GMM.CB_12, test_im)

    with open(
        os.path.join(
            set_up,
            "output",
            "cb_2012_ret_val_rrup_{}_mag_{}_{}.P".format(test_rrup, test_mag, test_im),
        ),
        "rb",
    ) as f:
        expected_results = pickle.load(f)

    assert test_results == expected_results
def test_as_2016(set_up, test_rrup, test_mag, test_im):
    FAULT.Mw = test_mag
    SITE.Rrup = test_rrup
    test_results = compute_gmm(FAULT, SITE, GMM.AS_16, test_im)

    with open(
            os.path.join(
                set_up,
                "output",
                "as_2016_ret_val_rrup_{}_mag_{}_{}.P".format(
                    test_rrup, test_mag, test_im),
            ),
            "rb",
    ) as f:
        expected_results = pickle.load(f)

    assert test_results == expected_results
def get_empirical_values(fault, im, model_dict, r_rup_vals, period):
    gmm = empirical_factory.determine_gmm(fault, im, model_dict)[0]
    # https://github.com/ucgmsim/post-processing/blob/master/im_processing/computations/GMPE.py
    # line 145
    r_jbs_vals = np.sqrt(np.maximum(0, r_rup_vals**2 - fault.ztor**2))
    e_medians = []
    e_sigmas = []
    for i in range(len(r_rup_vals)):
        site = classdef.Site()
        site.Rrup = r_rup_vals[i]
        site.Rjb = r_jbs_vals[i]
        value = empirical_factory.compute_gmm(fault, site, gmm, im, period)
        if isinstance(value, tuple):
            e_medians.append(value[0])
            e_sigmas.append(value[1][0])
        elif isinstance(value, list):
            for v in value:
                e_medians.append(v[0])
                e_sigmas.append(v[1][0])

    return np.array(e_medians), np.array(e_sigmas)
def meta_model(fault,
               site,
               im,
               weights_path=None,
               period=None,
               config=None,
               **kwargs):
    """
    Computes the meta model gmm from a list of gmms and associated weights
    :param fault: Fault object representing the fault the empirical is to be calculated for
    :param site: Site object representing the location the empirical value is to be calculated for
    :param weights_path: Path to the weights file
    :param im: The intensity measure to be calculated
    :param period: If the im takes a period, then this should be a list of periods to calculate the values for
    :param config: A dictionary of any settings to be passed to subsequent gmpes
    :param kwargs: Any additional settings to be passed to all gmpes
    :return: a list of (median, (total sigma, intramodel sigma, intermodel sigma)) nested tuples.
    Of length one or equal to the length of period
    """

    # Local import to prevent cyclic dependencies
    from empirical.util.classdef import GMM
    from empirical.util.empirical_factory import compute_gmm

    # Load the models and weights, then make sure they correspond
    gmms = load_weights(weights_path, im, fault.tect_type)
    models, weights = zip(*gmms.items())
    assert np.isclose(np.sum(weights), 1, atol=0.01), (
        f"Weights don't add to 1 ({np.sum(weights)} is more than 0.01 "
        f"away from 1). Check your gmpe weights file. ")

    medians = []
    sigmas = []

    for gmm in models:
        if config is not None and gmm in config.keys():
            tmp_params_dict = config[gmm]
        else:
            tmp_params_dict = {}
        res = compute_gmm(fault, site, GMM[gmm], im, period, **tmp_params_dict,
                          **kwargs)
        if isinstance(res, tuple):
            median, (sigma, _, _) = res
            median = median[0] if isinstance(median, Iterable) else median
        else:
            if len(res) == 1:
                median, (sigma, _, _) = res[0]
            else:
                median, sigma_tuple = zip(*res)
                sigma, __, __ = zip(*sigma_tuple)

        medians.append(median)
        sigmas.append(sigma)

    # Get values as arrays in log space
    logmedians = np.log(np.asarray(medians))
    logsigmas = np.asarray(sigmas)

    # Get weighted median
    weighted_average_median = np.dot(weights, logmedians)

    # Get weighted sigmas
    sigma_average = np.dot(weights, logsigmas)
    sigma_intermodel = np.sqrt(
        np.square(logmedians - weighted_average_median).sum(axis=0) /
        len(weights))
    average_sigma_total = np.sqrt(
        np.square(sigma_average) + np.square(sigma_intermodel))

    # Get output matrices
    e_medians = np.exp(weighted_average_median).squeeze()
    e_sigmas = average_sigma_total.squeeze()

    # Convert output into (median, (total sigma, intramodel sigma, intermodel sigma)) format
    if isinstance(e_medians, np.ndarray):
        sigmas = list(zip(e_sigmas, sigma_average, sigma_intermodel))
        res = list(zip(e_medians, sigmas))
    else:
        res = [(e_medians, (e_sigmas, sigma_average, sigma_intermodel))]

    return res
def calculate_empirical(
    identifier,
    srf_info,
    output_dir,
    config_file,
    stations,
    vs30_file,
    vs30_default,
    ims,
    rupture_distance,
    max_rupture_distance,
    period,
    extended_period,
    components,
    gmm_param_config=None,
):
    """Calculate empirical intensity measures"""

    # Fault & Site parameters
    fault = create_fault_parameters(srf_info)

    sites = create_site_parameters(
        rupture_distance,
        vs30_file,
        stations=stations,
        vs30_default=vs30_default,
        max_distance=max_rupture_distance,
    )

    if extended_period:
        period = np.unique(np.append(period, constants.EXT_PERIOD))

    tect_type_model_dict = empirical_factory.read_model_dict(config_file)
    station_names = [site.name for site in sites] if stations is None else stations
    for im in ims:

        for cur_gmm, component in empirical_factory.determine_all_gmm(
            fault, im, tect_type_model_dict, components
        ):
            # File & column names
            cur_filename = "{}_{}_{}.csv".format(identifier, cur_gmm.name, im)
            cur_cols = []
            if im in MULTI_VALUE_IMS:
                if im == "IESDR":
                    for p in period:
                        for r in _STRENGTH_REDUCTION_FACTORS:
                            cur_cols.append("IESDR_{}_r_{}".format(p, r))
                            cur_cols.append("IESDR_{}_r_{}_sigma".format(p, r))
                else:
                    for p in period:
                        cur_cols.append("{}_{}".format(im, p))
                        cur_cols.append("{}_{}_sigma".format(im, p))
            else:
                cur_cols.append(im)
                cur_cols.append("{}_sigma".format(im))

            # Get & save the data
            cur_data = np.zeros((len(sites), len(cur_cols)), dtype=np.float)
            for ix, site in enumerate(sites):
                values = empirical_factory.compute_gmm(
                    fault,
                    site,
                    cur_gmm,
                    im,
                    period if im in MULTI_VALUE_IMS else None,
                    gmm_param_config,
                )
                if im in MULTI_VALUE_IMS:
                    cur_data[ix, :] = np.ravel(
                        [
                            [im_value, total_sigma]
                            for im_value, (total_sigma, *_) in values
                        ]
                    )
                else:
                    cur_data[ix, :] = [values[0], values[1][0]]

            df = pd.DataFrame(columns=cur_cols, data=cur_data)
            df[STATION_COL_NAME] = station_names
            df[COMPONENT_COL_NAME] = component.str_value

            # Correct column order
            df = order_im_cols_df(df)

            df.to_csv(os.path.join(output_dir, cur_filename), index=False)
Exemple #9
0
                        continue
                else:
                    if imt not in ["SA", "PGA"]:
                        # empirical engine ones don't have PGV etc...
                        # need to update as required
                        continue
                fault.tect_type = gmms[g][1]
                x = np.logspace(1, 3)
                y = []
                for rrup in x:
                    site.Rrup = rrup
                    site.Rjb = rrup * 0.9
                    period = None if imt != "SA" else im
                    # but zhao expects a list?
                    if g == GMM.ZA_06:
                        v = compute_gmm(fault, site, g, imt, period=[period])
                        if imt == "PGA":
                            # result
                            v, stdvs = v
                        else:
                            # list of result for each period
                            v, stdvs = v[0]
                    else:
                        v, stdvs = compute_gmm(fault,
                                               site,
                                               g,
                                               imt,
                                               period=period)
                    y.append(v[0] if hasattr(v, "__len__") else v)

                y = np.array(y)