def test_weichert_full(self): """ Tests the Weichert function for the synthetic catalogue """ wchrt = Weichert() bval, sigmab, rate, sigma_rate = wchrt.calculate( self.catalogue, self.config, self.completeness) self.assertAlmostEqual(bval, 0.890, 3) self.assertAlmostEqual(sigmab, 0.015, 3) self.assertAlmostEqual(rate, 100.1078, 4) self.assertAlmostEqual(sigma_rate, 2.1218, 4)
def test_weichert_full(self): """ Tests the Weichert function for the synthetic catalogue """ wchrt = Weichert() bval, sigmab, rate, sigma_rate = wchrt.calculate(self.catalogue, self.config, self.completeness) self.assertAlmostEqual(bval, 0.890, 3) self.assertAlmostEqual(sigmab, 0.015, 3) self.assertAlmostEqual(rate, 100.1078, 4) self.assertAlmostEqual(sigma_rate, 2.1218, 4)
def _compute_mfd(cat, compl_table, mwid): """ """ cat = _add_defaults(cat) weichert_config = {'magnitude_interval': mwid, 'reference_magnitude': 0.0} weichert = Weichert() bval_wei, sigmab, aval_wei, sigmaa = weichert.calculate( cat, weichert_config, compl_table) # # info print('bval: %.6f (sigma=%.3f)' % (bval_wei, sigmab)) print('aval: %.6f (sigma=%.3f)' % (aval_wei, sigmaa)) return aval_wei, bval_wei, sigmaa, sigmab
def completeness_analysis(fname, idxs, years, mags, binw, ref_mag, bgrlim, src_id, folder_out_figs, rewrite=False): tcat = _load_catalogue(fname) tcat = _add_defaults(tcat) tcat.data["dtime"] = tcat.get_decimal_time() print('\nSOURCE:', src_id) print('Catalogue contains {:d} events'.format(len(tcat.data['magnitude']))) # See http://shorturl.at/adsvA fname_disp = 'dispositions.npy' perms = np.load(fname_disp) mags = np.flipud(np.load('mags.npy')) years = np.load('years.npy') wei_conf = {'magnitude_interval': binw, 'reference_magnitude': 0.0} weichert = Weichert() rate = -1e10 save = [] mags = np.array(mags) for prm in perms: idx = prm.astype(int) tmp = np.array([(y, m) for y, m in zip(years, mags[idx])]) ctab = clean_completeness(tmp) try: cent_mag, t_per, n_obs = get_completeness_counts(tcat, ctab, binw) bval, sigb, aval, siga = weichert.calculate(tcat, wei_conf, ctab) tmp_rate = 10**(-bval * ref_mag + aval) if tmp_rate > rate and bval <= bgrlim[1] and bval >= bgrlim[0]: rate = tmp_rate save = [aval, bval, rate, ctab] gwci = get_weichert_confidence_intervals lcl, ucl, ex_rates, ex_rates_scaled = gwci( cent_mag, n_obs, t_per, bval) mmax = max(tcat.data['magnitude']) wei = [ cent_mag, n_obs, binw, t_per, ex_rates_scaled, lcl, ucl, mmax, aval, bval ] except RuntimeWarning: logging.debug('Skipping', ctab) except UserWarning: logging.debug('Skipping', ctab) except: logging.debug('Skipping', ctab) if True: fmt = 'Maximum annual rate for {:.1f}: {:.4f}' print(fmt.format(ref_mag, save[2])) fmt = 'GR a and b : {:.4f} {:.4f}' print(fmt.format(save[0], save[1])) print('Completeness:\n', save[3]) _weichert_plot(wei[0], wei[1], wei[2], wei[3], wei[4], wei[5], wei[6], wei[7], wei[8], wei[9], src_id=src_id) # Saving figure if folder_out_figs is not None: ext = 'png' fmt = 'fig_mfd_{:s}.{:s}' figure_fname = os.path.join(folder_out_figs, fmt.format(src_id, ext)) plt.savefig(figure_fname, format=ext) plt.close() return save
def weichert_analysis(fname_input_pattern, fname_config, folder_out=None, folder_out_figs=None, skip=[], binw=None, plt_show=False): """ Computes GR parameters for a set of catalogues stored in a .csv file :param fname_input_pattern: It can be either a string (definining a pattern) or a list of .csv files. The file names must have the source ID at the end. The delimiter of the source ID on the left is `_` :param fname_config: The name of the .toml configuration file :param folder_out: The folder where to store the files with the counting of occurrences :param folder_out_figs: The folder where to store the figures :param skip: A list with the IDs of the sources to skip """ if folder_out is not None: create_folder(folder_out) if folder_out_figs is not None: create_folder(folder_out_figs) # Parsing config if fname_config is not None: model = toml.load(fname_config) if binw is None and fname_config is not None: binw = model['bin_width'] else: binw = 0.1 if isinstance(fname_input_pattern, str): fname_list = [f for f in glob(fname_input_pattern)] else: fname_list = fname_input_pattern # Processing files for fname in sorted(fname_list): print(fname) # Get source ID src_id = _get_src_id(fname) if src_id in skip: print(" skipping") continue if 'sources' in model: if (src_id in model['sources'] and 'mmax' in model['sources'][src_id]): mmax = model['sources'][src_id]['mmax'] else: mmax = model['default']['mmax'] if (src_id in model['sources'] and 'completeness_table' in model['sources'][src_id]): key_tmp = 'completeness_table' ctab = numpy.array(model['sources'][src_id][key_tmp]) print('Using source specific completeness') else: ctab = numpy.array(model['default']['completeness_table']) else: mmax = model['default']['mmax'] ctab = numpy.array(model['default']['completeness_table']) # Processing catalogue tcat = _load_catalogue(fname) if tcat is None or len(tcat.data['magnitude']) < 2: print(' Source {:s} has less than 2 eqks'.format(src_id)) continue tcat.data["dtime"] = tcat.get_decimal_time() cent_mag, t_per, n_obs = get_completeness_counts(tcat, ctab, binw) if folder_out is not None: df = pd.DataFrame() df['mag'] = cent_mag df['deltaT'] = t_per df['nobs'] = n_obs fmt = 'occ_count_zone_{:s}' fout = os.path.join(folder_out, fmt.format(src_id)) df.to_csv(fout, index=False) # Computing GR a and b tcat = _add_defaults(tcat) weichert_config = { 'magnitude_interval': binw, 'reference_magnitude': 0.0 } weichert = Weichert() bval_wei, sigmab, aval_wei, sigmaa = weichert.calculate( tcat, weichert_config, ctab) # Computing confidence intervals gwci = get_weichert_confidence_intervals lcl, ucl, ex_rates, ex_rates_scaled = gwci(cent_mag, n_obs, t_per, bval_wei) if 'sources' not in model: model['sources'] = {} if src_id not in model['sources']: model['sources'][src_id] = {} tmp = "{:.5e}".format(aval_wei) model['sources'][src_id]['agr_weichert'] = float(tmp) tmp = "{:.3f}".format(bval_wei) model['sources'][src_id]['bgr_weichert'] = float(tmp) _ = plt.figure() ax = plt.gca() plt.plot(cent_mag, n_obs / t_per, 'o', markerfacecolor='none') plt.plot(cent_mag - binw / 2, ex_rates_scaled, 's', markerfacecolor='none', color='red') plt.plot(cent_mag - binw / 2, lcl, '--', color='darkgrey') plt.plot(cent_mag - binw / 2, ucl, '--', color='darkgrey') xmag = numpy.arange(cent_mag[0] - binw / 2, mmax - 0.01 * binw, binw / 2) exra = (10.0**(aval_wei - bval_wei * xmag) - 10.0**(aval_wei - bval_wei * mmax)) plt.plot(xmag, exra, '--', lw=3, color='green') plt.yscale('log') plt.xlabel('Magnitude') plt.ylabel('Annual rate of exceedance') plt.text(0.75, 0.95, 'b_GR = {:.2f}'.format(bval_wei), transform=ax.transAxes) plt.grid(which='major', color='grey') plt.grid(which='minor', linestyle='--', color='lightgrey') plt.title(src_id) if plt_show: plt.show() # Saving figures if folder_out_figs is not None: ext = 'png' fmt = 'fig_mfd_{:s}.{:s}' figure_fname = os.path.join(folder_out_figs, fmt.format(src_id, ext)) plt.savefig(figure_fname, format=ext) plt.close() # Saving results into the config file if fname_config is not None: with open(fname_config, 'w') as f: f.write(toml.dumps(model)) print('Updated {:s}'.format(fname_config))