def test_cumulative_detections(self): dates = [] for i in range(3): dates.append([dt.datetime(2012, 3, 26) + dt.timedelta(n) for n in np.random.randn(100)]) fig = cumulative_detections( dates, ['a', 'b', 'c'], show=False, return_figure=True) return fig
def plot(self, plot_grouped=False): """ Plot the cumulative number of detections in time. .. rubric:: Example >>> from eqcorrscan import Template, Detection >>> family = Family( ... template=Template(name='a'), detections=[ ... Detection(template_name='a', detect_time=UTCDateTime(0) + 200, ... no_chans=8, detect_val=4.2, threshold=1.2, ... typeofdet='corr', threshold_type='MAD', ... threshold_input=8.0), ... Detection(template_name='a', detect_time=UTCDateTime(0), ... no_chans=8, detect_val=4.5, threshold=1.2, ... typeofdet='corr', threshold_type='MAD', ... threshold_input=8.0), ... Detection(template_name='a', detect_time=UTCDateTime(0) + 10, ... no_chans=8, detect_val=4.5, threshold=1.2, ... typeofdet='corr', threshold_type='MAD', ... threshold_input=8.0)]) >>> family.plot(plot_grouped=True) # doctest: +SKIP .. plot:: from eqcorrscan.core.match_filter import Family, Template from eqcorrscan.core.match_filter import Detection from obspy import UTCDateTime family = Family( template=Template(name='a'), detections=[ Detection(template_name='a', detect_time=UTCDateTime(0) + 200, no_chans=8, detect_val=4.2, threshold=1.2, typeofdet='corr', threshold_type='MAD', threshold_input=8.0), Detection(template_name='a', detect_time=UTCDateTime(0), no_chans=8, detect_val=4.5, threshold=1.2, typeofdet='corr', threshold_type='MAD', threshold_input=8.0), Detection(template_name='a', detect_time=UTCDateTime(0) + 10, no_chans=8, detect_val=4.5, threshold=1.2, typeofdet='corr', threshold_type='MAD', threshold_input=8.0)]) family.plot(plot_grouped=True) """ cumulative_detections(detections=self.detections, plot_grouped=plot_grouped)
# Create two dataframes for each set of detections df_sub = pd.read_csv('/home/chet/data/detections/2015_corr_groups/2015_all_det_corrgrps.csv', header=None) df_all = pd.read_csv('/home/chet/data/detections/2015_alltemps_1sec/2015_all_det_1sec.csv', header=None) df = pd.concat([df_sub, df_all]) det_dict = {} for index, row in df.iterrows(): if row[0] in det_dict: if UTCDateTime(row[1]) < UTCDateTime(2015, 11, 20) and row[4] > 5: det_dict[row[0]].append(UTCDateTime(row[1]).datetime) else: if UTCDateTime(row[1]) < UTCDateTime(2015, 11, 20) and row[4] > 5: det_dict[row[0]] = [UTCDateTime(row[1]).datetime] for grp in corr_groups: temp_names = [] temp_times = [] cat = read_events(grp) if len(cat) > 1: sub_dets = grp.split('/')[-1].rstrip('.xml') subs = [sub_dets + '_2n', sub_dets + '_1st'] plot_file = '/media/chet/hdd/seismic/NZ/figs/cum_det_plots/' +\ sub_dets + '.png' for sub in subs: temp_names.append(sub) temp_times.append(det_dict[sub]) for ev in cat: ev_name = str(ev.resource_id).split('/')[-1] temp_names.append(ev_name) temp_times.append(det_dict[ev_name + '_1sec']) plotting.cumulative_detections(temp_times, temp_names, show=True, save=False, savefile=plot_file)
def plot(self, plot_grouped=False, dates=None, min_dets=1, rate=False, **kwargs): """ Plot the cumulative detections in time. :type plot_grouped: bool :param plot_grouped: Whether to plot all families together (plot_grouped=True), or each as a separate line. :type dates: list :param dates: list of obspy.core.UTCDateTime objects bounding the plot. The first should be the start date, the last the end date. :type min_dets: int :param min_dets: Plot only families with this number of detections or more. :type rate: bool :param rate: Whether or not to plot the daily rate of detection as opposed to cumulative number. Only works with plot_grouped=True. :param \**kwargs: Any other arguments accepted by :func:`eqcorrscan.utils.plotting.cumulative_detections` .. rubric:: Examples Plot cumulative detections for all templates individually: >>> Party().read().plot() # doctest: +SKIP Plot cumulative detections for all templates grouped together: >>> Party().read().plot(plot_grouped=True) # doctest: +SKIP Plot the rate of detection for all templates grouped together: >>> Party().read().plot(plot_grouped=True, rate=True) # doctest: +SKIP Plot cumulative detections for all templates with more than five detections between June 1st, 2012 and July 31st, 2012: >>> from obspy import UTCDateTime >>> Party().read().plot(dates=[UTCDateTime(2012, 6, 1), ... UTCDateTime(2012, 7, 31)], ... min_dets=5) # doctest: +SKIP """ all_dets = [] if dates: new_party = self.filter(dates=dates, min_dets=min_dets) for fam in new_party.families: all_dets.extend(fam.detections) else: for fam in self.families: all_dets.extend(fam.detections) fig = cumulative_detections(detections=all_dets, plot_grouped=plot_grouped, rate=rate, **kwargs) return fig
def plot_detections_rate(cat, temp_list='all', bbox=None, depth_thresh=None, cumulative=False, detection_rate=False): """ Plotting detections for some catalog of detected events :type cat: obspy.core.Catalog :param cat: Catalog containting detections. Should have detecting template info in the resource_id :type temp_list: list :param temp_list: list of template names which we want to consider for this plot :type bbox: tuple of tuple :param bbox: select only events within a certain geographic area bound by ((long, long), (lat, lat)) :type depth_thresh: float :param depth_thresh: Depth cutoff for detections being plotted in km :type cumulative: bool :param cumulative: Whether or not to combine detections into :type detection_rate: bool :param detection_rate: Do we plot derivative of detections? :return: """ # If specified, filter catalog to only events in geographic area if bbox: det_cat = bounding_box(cat, bbox, depth_thresh) # Sort det_cat by origin time else: det_cat = cat if not det_cat[0].origins[-1]: det_cat.events.sort(key=lambda x: x.origins[0].time) else: det_cat.events.sort(key=lambda x: x.origins[-1].time) # Put times and names into sister lists if detection_rate and not cumulative: cat_start = min([ev.origins[-1].time.datetime for ev in det_cat]) cat_end = max([ev.origins[-1].time.datetime for ev in det_cat]) det_rates = [] dates = [] if not det_cat[0].origins[-1]: for date in date_generator(cat_start, cat_end): dates.append(date) det_rates.append(len([ev for ev in det_cat if ev.origins[0].time.datetime > date and ev.origins[0].time.datetime < date + timedelta(days=1)])) else: for date in date_generator(cat_start, cat_end): dates.append(date) det_rates.append(len([ev for ev in det_cat if ev.origins[-1].time.datetime > date and ev.origins[-1].time.datetime < date + timedelta(days=1)])) fig, ax1 = plt.subplots() # ax1.step(dates, det_rates, label='All templates', linewidth=1.0, color='black') ax1 = plt.subplot(111) ax1.bar(dates, det_rates) ax1.xaxis_date() ax1.xaxis.set_major_locator(mdates.MonthLocator()) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b')) ax1.set_xlabel('Date') ax1.set_ylabel('Cumulative detection rate (events/day)') plt.title('Cumulative detection rate for all templates') else: det_times = [] temp_names = [] temp_dict = {} for ev in det_cat: temp_name = str(ev.resource_id).split('/')[-1].split('_')[0] o = ev.origins[-1] or ev.origins[0] if temp_name not in temp_dict: temp_dict[temp_name] = [o.time.datetime] else: temp_dict[temp_name].append(o.time.datetime) for temp_name, det_time_list in temp_dict.iteritems(): if temp_name in temp_list: det_times.append(det_time_list) temp_names.append(temp_name) elif temp_list == 'all': det_times.append(det_time_list) temp_names.append(temp_name) if cumulative: fig = plotting.cumulative_detections(dates=det_times, template_names=temp_names, plot_grouped=True, show=False, plot_legend=False) if detection_rate: ax2 = fig.get_axes()[0].twinx() cat_start = min([ev.origins[-1].time.datetime for ev in det_cat]) cat_end = max([ev.origins[-1].time.datetime for ev in det_cat]) det_rates = [] dates = [] for date in date_generator(cat_start, cat_end): dates.append(date) det_rates.append(len([ev for ev in det_cat if ev.origins[-1].time.datetime > date and ev.origins[-1].time.datetime < date + timedelta(days=1)])) ax2.step(dates, det_rates, label='All templates', linewidth=2.0, color='black') ax2.set_ylabel('Cumulative detection rate (events/day)') else: fig = plotting.cumulative_detections(dates=det_times, template_names=temp_names) return fig