示例#1
0
    def test_select_within_time(self):
        # Tests the function to select within a time period

        self.catalogue.data['year'] = np.arange(1900, 2010, 20)
        self.catalogue.data['month'] = np.arange(1, 12, 2)
        self.catalogue.data['day'] = np.ones(6, dtype=int)
        self.catalogue.data['hour'] = np.ones(6, dtype=int)
        self.catalogue.data['minute'] = np.zeros(6, dtype=int)
        self.catalogue.data['second'] = np.ones(6, dtype=float)

        selector0 = CatalogueSelector(self.catalogue)

        # Start time and End time not defined
        test_cat_1 = selector0.within_time_period()
        self._compare_time_data_dictionaries(test_cat_1.data,
                                             self.catalogue.data)

        # Start time defined - end time not defined
        begin_time = datetime.datetime(1975, 1, 1, 0, 0, 0, 0)
        expected_data = {
            'year': np.array([1980, 2000]),
            'month': np.array([9, 11]),
            'day': np.array([1, 1]),
            'hour': np.array([1, 1]),
            'minute': np.array([0, 0]),
            'second': np.array([1., 1.])
        }

        test_cat_1 = selector0.within_time_period(start_time=begin_time)
        self._compare_time_data_dictionaries(expected_data, test_cat_1.data)

        # Test 3 - Start time not defined, end-time defined
        finish_time = datetime.datetime(1965, 1, 1, 0, 0, 0, 0)
        expected_data = {
            'year': np.array([1900, 1920, 1940, 1960]),
            'month': np.array([1, 3, 5, 7]),
            'day': np.array([1, 1, 1, 1]),
            'hour': np.array([1, 1, 1, 1]),
            'minute': np.array([0, 0, 0, 0]),
            'second': np.array([1., 1., 1., 1.])
        }

        test_cat_1 = selector0.within_time_period(end_time=finish_time)
        self._compare_time_data_dictionaries(expected_data, test_cat_1.data)

        # Test 4 - both start time and end-time defined
        begin_time = datetime.datetime(1935, 1, 1, 0, 0, 0, 0)
        finish_time = datetime.datetime(1995, 1, 1, 0, 0, 0, 0)
        expected_data = {
            'year': np.array([1940, 1960, 1980]),
            'month': np.array([5, 7, 9]),
            'day': np.array([1, 1, 1]),
            'hour': np.array([1, 1, 1]),
            'minute': np.array([0, 0, 0]),
            'second': np.array([1., 1., 1.])
        }

        test_cat_1 = selector0.within_time_period(begin_time, finish_time)
        self._compare_time_data_dictionaries(expected_data, test_cat_1.data)
示例#2
0
    def test_select_within_time(self):
        # Tests the function to select within a time period

        self.catalogue.data['year'] = np.arange(1900, 2010, 20)
        self.catalogue.data['month'] = np.arange(1, 12, 2)
        self.catalogue.data['day'] = np.ones(6, dtype=int)
        self.catalogue.data['hour'] = np.ones(6, dtype=int)
        self.catalogue.data['minute'] = np.zeros(6, dtype=int)
        self.catalogue.data['second'] = np.ones(6, dtype=float)

        selector0 = CatalogueSelector(self.catalogue)

        # Start time and End time not defined
        test_cat_1 = selector0.within_time_period()
        self._compare_time_data_dictionaries(test_cat_1.data,
                                             self.catalogue.data)

        # Start time defined - end time not defined
        begin_time = datetime.datetime(1975, 1, 1, 0, 0, 0, 0)
        expected_data = {'year': np.array([1980, 2000]),
                         'month': np.array([9, 11]),
                         'day': np.array([1, 1]),
                         'hour': np.array([1, 1]),
                         'minute': np.array([0, 0]),
                         'second': np.array([1., 1.])}

        test_cat_1 = selector0.within_time_period(start_time=begin_time)
        self._compare_time_data_dictionaries(expected_data, test_cat_1.data)


        # Test 3 - Start time not defined, end-time defined
        finish_time = datetime.datetime(1965, 1, 1, 0, 0, 0, 0)
        expected_data = {'year': np.array([1900, 1920, 1940, 1960]),
                         'month': np.array([1, 3, 5, 7]),
                         'day': np.array([1, 1, 1, 1]),
                         'hour': np.array([1, 1, 1, 1]),
                         'minute': np.array([0, 0, 0, 0]),
                         'second': np.array([1., 1., 1., 1.])}

        test_cat_1 = selector0.within_time_period(end_time=finish_time)
        self._compare_time_data_dictionaries(expected_data, test_cat_1.data)

        # Test 4 - both start time and end-time defined
        begin_time = datetime.datetime(1935, 1, 1, 0, 0, 0, 0)
        finish_time = datetime.datetime(1995, 1, 1, 0, 0, 0, 0)
        expected_data = {'year': np.array([1940, 1960, 1980]),
                         'month': np.array([5, 7, 9]),
                         'day': np.array([1, 1, 1]),
                         'hour': np.array([1, 1, 1]),
                         'minute': np.array([0, 0, 0]),
                         'second': np.array([1., 1., 1.])}

        test_cat_1 = selector0.within_time_period(begin_time, finish_time)
        self._compare_time_data_dictionaries(expected_data, test_cat_1.data)
示例#3
0
def create_mtd(catalogue_fname,
               label,
               tr_fname,
               cumulative,
               store,
               mwid=0.1,
               twid=20.,
               pmint=None,
               pmaxt=None,
               ylim=None):
    """
    :param catalogue_fname:
    :param label:
    :param tr_fname:
    """
    mwid = float(mwid)
    twid = float(twid)
    if pmint is not None:
        pmint = int(pmint)
    if pmaxt is not None:
        pmaxt = int(pmaxt)
    #
    # loading catalogue
    if isinstance(catalogue_fname, str):
        cat = _load_catalogue(catalogue_fname)
    elif isinstance(catalogue_fname, Catalogue):
        cat = catalogue_fname
    else:
        raise ValueError('Unknown instance')

    # Check catalogue
    if cat is None or len(cat.data['magnitude']) < 1:
        return None

    # Select earthquakes belonging to a given TR
    idx = numpy.full(cat.data['magnitude'].shape, True, dtype=bool)
    if label is not None and tr_fname is not None:
        f = h5py.File(tr_fname, 'r')
        idx = f[label][:]
        f.close()
    #
    # select catalogue
    sel = CatalogueSelector(cat, create_copy=False)
    sel.select_catalogue(idx)
    start = datetime.datetime(pmint, 1, 1) if pmint is not None else None
    stop = datetime.datetime(pmaxt, 12, 31) if pmaxt is not None else None
    sel.within_time_period(start, stop)

    # Check if the catalogue contains earthquakes
    if len(cat.data['magnitude']) < 1:
        return None

    #
    # find rounded min and max magnitude
    mmin, mmax = _get_extremes(cat.data['magnitude'], mwid)
    tmin, tmax = _get_extremes(cat.data['year'], twid)
    if ylim is not None:
        mmin = ylim[0]
        mmax = ylim[1]
    #
    #
    if pmint is None:
        pmint = tmin
    if pmaxt is None:
        pmaxt = tmax
    #
    # histogram
    bins_ma = numpy.arange(mmin, mmax + mwid * 0.01, mwid)
    bins_time = numpy.arange(tmin, tmax + twid * 0.01, twid)
    his, _, _ = numpy.histogram2d(cat.data['year'],
                                  cat.data['magnitude'],
                                  bins=(bins_time, bins_ma))
    his = his.T
    #
    # complementary cumulative
    if cumulative:
        ccu = numpy.zeros_like(his)
        for i in range(his.shape[1]):
            cc = numpy.cumsum(his[::-1, i])
            ccu[:, i] = cc[::-1]
    #
    # plotting
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    #
    #
    X, Y = numpy.meshgrid(bins_time, bins_ma)
    if cumulative:
        his = ccu
    pcm = ax.pcolormesh(X,
                        Y,
                        his,
                        norm=colors.LogNorm(vmin=1e-1, vmax=his.max()),
                        cmap='BuGn')
    #
    # plotting number of occurrences
    for it, vt in enumerate(bins_time[:-1]):
        for im, vm in enumerate(bins_ma[:-1]):
            ax.text(vt + twid / 2,
                    vm + mwid / 2,
                    '{:.0f}'.format(his[im, it]),
                    fontsize=7,
                    ha='center')

    #
    # plotting colorbar
    cb = fig.colorbar(pcm, ax=ax, extend='max')
    cb.set_label('Number of occurrences')
    #
    # finishing the plot
    plt.ylabel('Magnitude')
    plt.xlabel('Time')
    if label is not None:
        plt.title('label: {:s}'.format(label))
    plt.grid(linestyle='-')

    return fig
示例#4
0
def create_mtd(catalogue_fname,
               label,
               tr_fname,
               cumulative,
               store,
               mwid=0.1,
               twid=20.,
               pmint=None,
               pmaxt=None,
               ylim=None):
    """
    :param catalogue_fname:
    :param label:
    :param tr_fname:
    """
    mwid = float(mwid)
    twid = float(twid)
    if pmint is not None:
        pmint = int(pmint)
    if pmaxt is not None:
        pmaxt = int(pmaxt)
    #
    # loading catalogue
    if isinstance(catalogue_fname, str):
        cat = _load_catalogue(catalogue_fname)
    elif isinstance(catalogue_fname, Catalogue):
        cat = catalogue_fname
    else:
        raise ValueError('Unknown instance')

    # Check catalogue
    if cat is None or len(cat.data['magnitude']) < 1:
        return None

    # Select earthquakes belonging to a given TR
    idx = numpy.full(cat.data['magnitude'].shape, True, dtype=bool)
    if label is not None and tr_fname is not None:
        f = h5py.File(tr_fname, 'r')
        idx = f[label][:]
        f.close()
    #
    # select catalogue
    sel = CatalogueSelector(cat, create_copy=False)
    sel.select_catalogue(idx)
    start = datetime.datetime(pmint, 1, 1) if pmint is not None else None
    stop = datetime.datetime(pmaxt, 12, 31) if pmaxt is not None else None
    sel.within_time_period(start, stop)

    # Check if the catalogue contains earthquakes
    if len(cat.data['magnitude']) < 1:
        return None

    # Get matrix
    bins_time, bins_ma, his = get_mtd(cat, mwid, twid, ylim, cumulative)

    # Plotting
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    X, Y = numpy.meshgrid(bins_time, bins_ma)
    tmp_col = colors.LogNorm(vmin=1e-1, vmax=his.max())
    pcm = ax.pcolormesh(X, Y, his, norm=tmp_col, cmap='BuGn')

    # Plotting number of occurrences
    for it, vt in enumerate(bins_time[:-1]):
        for im, vm in enumerate(bins_ma[:-1]):
            ax.text(vt + twid / 2,
                    vm + mwid / 2,
                    '{:.0f}'.format(his[im, it]),
                    fontsize=7,
                    ha='center')

    # Plotting colorbar
    cb = fig.colorbar(pcm, ax=ax, extend='max')
    cb.set_label('Number of occurrences')

    # Finishing the plot
    plt.ylabel('Magnitude')
    plt.xlabel('Time')
    if label is not None:
        plt.title('label: {:s}'.format(label))
    plt.grid(linestyle='-')

    return fig