예제 #1
0
파일: test_scan.py 프로젝트: bonaime/obspy
    def test_multiple_sampling_rates(self):
        """
        Check for multiple sampling rates
        """
        lines = [
            "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
            "2008-01-15T00:00:00.000000, SLIST, INTEGER, Counts",
            "TIMESERIES XX_TEST__BHZ_R,  50 samples,  50 sps, "
            "2008-01-15T00:00:00.900000, SLIST, INTEGER, Counts",
            "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
            "2008-01-15T00:00:02.000000, SLIST, INTEGER, Counts",
        ]
        files = []
        expected = [
            "XX.TEST..BHZ 2008-01-15T00:00:01.000000Z "
            "2008-01-15T00:00:00.899995Z -0.100",
            "XX.TEST..BHZ 2008-01-15T00:00:01.899999Z "
            "2008-01-15T00:00:02.000000Z 0.100"
        ]
        with NamedTemporaryFile() as f1, NamedTemporaryFile() as f2, \
                NamedTemporaryFile() as f3:
            for i, fp in enumerate([f1, f2, f3]):
                fp.write(("%s\n" % lines[i]).encode('ascii',
                                                    'strict'))
                fp.flush()
                fp.seek(0)
                files.append(fp.name)

            # make image comparison instance and set manual rms (see #2089)
            image_comp = ImageComparison(self.path, 'scan_mult_sampl.png')
            image_comp.tol = 40

            with image_comp as ic:

                obspy_scan(files + ['--output', ic.name, '--print-gaps'])

                with CatchOutput() as out:
                    obspy_scan(files + ['--output', ic.name, '--print-gaps'])

                # read output and compare with expected
                # only check if datetime objects are close, not exact
                output = out.stdout.splitlines()
                for ex_line, out_line in zip(expected, output):
                    ex_split = ex_line.split(' ')
                    out_split = out_line.split(' ')
                    for ex_str, out_str in zip(ex_split, out_split):
                        try:
                            utc1 = UTCDateTime(ex_str)
                            utc2 = UTCDateTime(out_str)
                        except (ValueError, TypeError):
                            # if str is not a datetime it should be equal
                            self.assertEqual(ex_str, out_str)
                        else:
                            # datetimes just need to be close
                            t1, t2 = utc1.timestamp, utc2.timestamp
                            self.assertTrue(abs(t1 - t2) < .001)
예제 #2
0
 def test_plotAzimSection(self):
     """
     Tests plotting 10 in a azimuthal distant section
     """
     start = UTCDateTime(0)
     st = Stream()
     for _i in range(10):
         st += self._createStream(start, start + 3600, 100)
         st[-1].stats.coordinates = AttribDict({
             'latitude': _i,
             'longitude': _i
         })
     # create and compare image
     with ImageComparison(self.path, 'waveform_azim_section.png') as ic:
         st.plot(outfile=ic.name,
                 type='section',
                 dist_degree=True,
                 ev_coord=(0.0, 0.0))
예제 #3
0
    def test_xcorrPickCorrection_images(self):
        """
        Test cross correlation pick correction on a set of two small local
        earthquakes.
        """
        st1 = read(os.path.join(self.path,
                                'BW.UH1._.EHZ.D.2010.147.a.slist.gz'))
        st2 = read(os.path.join(self.path,
                                'BW.UH1._.EHZ.D.2010.147.b.slist.gz'))

        tr1 = st1.select(component="Z")[0]
        tr2 = st2.select(component="Z")[0]
        t1 = UTCDateTime("2010-05-27T16:24:33.315000Z")
        t2 = UTCDateTime("2010-05-27T16:27:30.585000Z")

        with ImageComparison(self.path_images, 'xcorr_pick_corr.png') as ic:
            dt, coeff = xcorr_pick_correction(
                t1, tr1, t2, tr2, 0.05, 0.2, 0.1, plot=True, filename=ic.name)
예제 #4
0
    def test_response_plot(self):
        """
        Tests the response plot.
        """
        # Bug in matplotlib 1.4.0 - 1.4.x:
        # See https://github.com/matplotlib/matplotlib/issues/4012
        reltol = 1.0
        if [1, 4, 0] <= MATPLOTLIB_VERSION <= [1, 5, 0]:
            reltol = 2.0

        resp = read_inventory()[0][0][0].response
        with warnings.catch_warnings(record=True):
            warnings.simplefilter("ignore")
            with ImageComparison(self.image_dir, "response_response.png",
                                 reltol=reltol) as ic:
                rcParams['savefig.dpi'] = 72
                resp.plot(0.001, output="VEL", start_stage=1, end_stage=3,
                          outfile=ic.name)
예제 #5
0
    def test_response_plot(self):
        """
        Tests the response plot.
        """
        # Bug in matplotlib 1.4.0 - 1.4.x:
        # See https://github.com/matplotlib/matplotlib/issues/4012
        reltol = 1.0
        if [1, 4, 0] <= MATPLOTLIB_VERSION <= [1, 5, 0]:
            reltol = 2.0

        sta = read_inventory()[0][0]
        with warnings.catch_warnings(record=True):
            warnings.simplefilter("ignore")
            with ImageComparison(self.image_dir,
                                 "station_response.png",
                                 reltol=reltol) as ic:
                rcParams['savefig.dpi'] = 72
                sta.plot(0.05, channel="*[NE]", outfile=ic.name)
예제 #6
0
 def test_location_plot_local(self):
     """
     Tests the inventory location preview plot, local projection, some more
     non-default parameters, using Cartopy.
     """
     inv = read_inventory()
     with ImageComparison(self.image_dir,
                          'inventory_location-cartopy3.png') as ic:
         rcParams['savefig.dpi'] = 72
         inv.plot(method='cartopy',
                  projection='local',
                  resolution='50m',
                  size=20**2,
                  color_per_network={
                      'GR': 'b',
                      'BW': 'green'
                  },
                  outfile=ic.name)
예제 #7
0
 def test_location_plot_ortho(self):
     """
     Tests the inventory location preview plot, ortho projection, some
     non-default parameters, using Cartopy.
     """
     inv = read_inventory()
     with ImageComparison(self.image_dir,
                          'inventory_location-cartopy2.png') as ic:
         rcParams['savefig.dpi'] = 72
         inv.plot(method='cartopy',
                  projection='ortho',
                  resolution='c',
                  continent_fill_color='0.3',
                  marker='d',
                  label=False,
                  colormap='Set3',
                  color_per_network=True,
                  outfile=ic.name)
예제 #8
0
 def test_combined_station_event_plot(self):
     """
     Tests the coombined plotting of inventory/event data in one plot,
     reusing the basemap instance.
     """
     inv = read_inventory()
     cat = read_events()
     reltol = 1.1
     # Coordinate lines might be slightly off, depending on the basemap
     # version.
     if BASEMAP_VERSION < [1, 0, 7]:
         reltol = 3.0
     with ImageComparison(self.image_dir,
                          'basemap_combined_stations-events.png',
                          reltol=reltol) as ic:
         rcParams['savefig.dpi'] = 72
         fig = inv.plot(show=False)
         cat.plot(outfile=ic.name, fig=fig)
예제 #9
0
 def test_ppsd_plot_frequency(self):
     """
     Test plot of ppsd example data, normal (non-cumulative) style.
     """
     # Catch underflow warnings due to plotting on log-scale.
     with np.errstate(all='ignore'):
         with ImageComparison(self.path, 'ppsd_freq.png', reltol=2.0) as ic:
             self.ppsd.plot(
                 show=False, show_coverage=False, show_histogram=True,
                 show_percentiles=True, percentiles=[20, 40],
                 show_noise_models=True, grid=False, max_percentage=50,
                 period_lim=(0.2, 50), show_mode=True, show_mean=True,
                 xaxis_frequency=True)
             fig = plt.gcf()
             ax = fig.axes[0]
             ax.set_ylim(-160, -130)
             plt.draw()
             fig.savefig(ic.name, dpi=50)
예제 #10
0
 def test_location_plot_local(self):
     """
     Tests the network location preview plot, local projection, some more
     non-default parameters, using Basemap.
     """
     net = read_inventory()[0]
     # Coordinate lines might be slightly off, depending on the basemap
     # version.
     reltol = 2.0
     # Basemap smaller 1.0.4 has a serious issue with plotting. Thus the
     # tolerance must be much higher.
     if BASEMAP_VERSION < [1, 0, 4]:
         reltol = 100.0
     with ImageComparison(self.image_dir, 'network_location-basemap3.png',
                          reltol=reltol) as ic:
         rcParams['savefig.dpi'] = 72
         net.plot(method='basemap', projection='local', resolution='l',
                  size=13**2, outfile=ic.name)
예제 #11
0
파일: test_event.py 프로젝트: davcra/obspy
 def test_catalog_plot_ortho_longitude_wrap(self):
     """
     Tests the catalog preview plot, ortho projection, some non-default
     parameters, using Cartopy, with longitudes that need the mean to be
     computed in a circular fashion.
     """
     cat = read_events('/path/to/events_longitude_wrap.zmap', format='ZMAP')
     with ImageComparison(self.image_dir,
                          'catalog-cartopy_long-wrap.png') as ic:
         rcParams['savefig.dpi'] = 40
         cat.plot(method='cartopy',
                  outfile=ic.name,
                  projection='ortho',
                  resolution='c',
                  label=None,
                  title='',
                  colorbar=False,
                  water_fill_color='b')
예제 #12
0
    def test_collection(self):
        """
        Tests to plot beachballs as collection into an existing axis
        object. The moment tensor values are taken form the
        test_Beachball unit test. See that test for more information about
        the parameters.
        """
        reltol = 1
        if MATPLOTLIB_VERSION < [1, 2, 0]:
            reltol = 20
        mt = [[0.91, -0.89, -0.02, 1.78, -1.55, 0.47], [274, 13, 55],
              [130, 79, 98], [264.98, 45.00, -159.99], [160.55, 76.00, -46.78],
              [1.45, -6.60, 5.14, -2.67, -3.16, 1.36], [235, 80, 35],
              [138, 56, 168], [1, 1, 1, 0, 0, 0], [-1, -1, -1, 0, 0, 0],
              [1, -2, 1, 0, 0, 0], [1, -1, 0, 0, 0, 0], [1, -1, 0, 0, 0, -1],
              [179, 55, -78], [10, 42.5, 90], [10, 42.5, 92], [150, 87, 1],
              [0.99, -2.00, 1.01, 0.92, 0.48, 0.15],
              [5.24, -6.77, 1.53, 0.81, 1.49, -0.05],
              [16.578, -7.987, -8.592, -5.515, -29.732, 7.517],
              [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94], [150, 87, 1]]

        # Initialize figure
        fig = plt.figure(figsize=(6, 6), dpi=300)
        ax = fig.add_subplot(111, aspect='equal')

        # Plot the stations or borders
        ax.plot([-100, -100, 100, 100], [-100, 100, -100, 100], 'rv')

        x = -100
        y = -100
        for i, t in enumerate(mt):
            # add the beachball (a collection of two patches) to the axis
            ax.add_collection(Beach(t, width=30, xy=(x, y), linewidth=.6))
            x += 50
            if (i + 1) % 5 == 0:
                x = -100
                y += 50

        # set the x and y limits and save the output
        ax.axis([-120, 120, -120, 120])
        # create and compare image
        with ImageComparison(self.path, 'bb_collection.png',
                             reltol=reltol) as ic:
            fig.savefig(ic.name)
예제 #13
0
    def test_response_plot(self):
        """
        Tests the response plot.
        """
        # Bug in matplotlib 1.4.0 - 1.4.2:
        # See https://github.com/matplotlib/matplotlib/issues/4012
        reltol = 1.0
        if [1, 4, 0] <= MATPLOTLIB_VERSION <= [1, 4, 2]:
            reltol = 2.0

        net = read_inventory()[0]
        t = UTCDateTime(2008, 7, 1)
        with warnings.catch_warnings(record=True):
            warnings.simplefilter("ignore")
            with ImageComparison(self.image_dir, "network_response.png",
                                 reltol=reltol) as ic:
                rcParams['savefig.dpi'] = 72
                net.plot_response(0.002, output="DISP", channel="B*E",
                                  time=t, outfile=ic.name)
예제 #14
0
 def test_plotBenchmark(self):
     """
     Test benchmark plot.
     """
     path = os.path.join(os.path.dirname(__file__), 'data')
     path_images = os.path.join(os.path.dirname(__file__), "images")
     sufiles = sorted(glob.glob(os.path.join(path, 'seismic01_*_vz.su')))
     # new temporary file with PNG extension
     with ImageComparison(path_images, 'test_plotBenchmark.png') as ic:
         # generate plot
         with warnings.catch_warnings(record=True) as w:
             warnings.resetwarnings()
             np_err = np.seterr(all="warn")
             plotBenchmark(sufiles, outfile=ic.name, format='PNG')
             np.seterr(**np_err)
         self.assertEqual(len(w), 1)
         self.assertEqual(w[0].category, RuntimeWarning)
         self.assertEqual(str(w[0].message),
                          'underflow encountered in divide')
예제 #15
0
    def test_response_plot(self):
        """
        Tests the response plot.
        """
        # Bug in matplotlib 1.4.0 - 1.4.x:
        # See https://github.com/matplotlib/matplotlib/issues/4012
        reltol = 1.0
        if [1, 4, 0] <= MATPLOTLIB_VERSION <= [1, 5, 0]:
            reltol = 2.0

        inv = read_inventory()
        t = UTCDateTime(2008, 7, 1)
        with warnings.catch_warnings(record=True):
            warnings.simplefilter("ignore")
            with ImageComparison(self.image_dir, "inventory_response.png",
                                 reltol=reltol) as ic:
                rcParams['savefig.dpi'] = 72
                inv.plot_response(0.01, output="ACC", channel="*N",
                                  station="[WR]*", time=t, outfile=ic.name)
예제 #16
0
    def test_mopad_fallback(self):
        """
        Test the fallback to mopad.
        """
        mt = [0.000, -1.232e25, 1.233e25, 0.141e25, -0.421e25, 2.531e25]

        with warnings.catch_warnings(record=True) as w:
            # Always raise warning.
            warnings.simplefilter("always")
            with ImageComparison(self.path, 'mopad_fallback.png') as ic:
                beachball(mt, outfile=ic.name)

        # Make sure the appropriate warnings has been raised.
        self.assertTrue(w)
        # Filter
        w = [_i.message.args[0] for _i in w]
        w = [_i for _i in w
             if "falling back to the mopad wrapper" in _i.lower()]
        self.assertTrue(w)
예제 #17
0
 def test_plot_wiggles_positive_section(self):
     """
     Tests plotting 10 traces in a horizontal section,
     with colored wiggles only on the positive side.
     """
     start = UTCDateTime(0)
     st = Stream()
     for _i in range(10):
         this_start = start + 300 * np.sin(np.pi * _i / 9)
         st += self._create_stream(this_start, this_start + 3600, 100)
         st[-1].stats.distance = _i * 10e3
         st[-1].stats.channel = str(_i % 3)
     # create and compare image
     with ImageComparison(self.path,
                          'waveform_wiggles_positive_section.png') as ic:
         st.plot(outfile=ic.name,
                 type='section',
                 orientation='horizontal',
                 fillcolors=("black", None))
예제 #18
0
 def test_scan(self):
     """
     Run obspy-scan on selected tests/data directories
     """
     reltol = 1
     if MATPLOTLIB_VERSION < [1, 3, 0]:
         reltol = 60
     # using mseed increases test time by factor 2
     waveform_dirs = [
         join(self.root, n, 'tests', 'data') for n in ('sac', 'gse2')
     ]
     with ImageComparison(self.path, 'scan.png', reltol=reltol) as ic:
         try:
             tmp_stdout = sys.stdout
             sys.stdout = open(os.devnull, 'wb')
             obspy_scan(waveform_dirs + ['--output', ic.name])
         finally:
             sys.stdout.close()
             sys.stdout = tmp_stdout
예제 #19
0
    def test_plot(self):
        """
        Run obspy-plot on selected tests
        """
        reltol = 1
        if MATPLOTLIB_VERSION < [1, 3, 0]:
            reltol = 60

        # Copy files to a temp folder to avoid wildcard scans.
        with TemporaryWorkingDirectory():
            all_files = []
            for filename in self.all_files:
                newname = join(os.curdir, basename(filename))
                shutil.copy(filename, newname)
                all_files += [newname]

            with ImageComparison(self.path, 'plot.png', reltol=reltol) as ic:
                with CatchOutput():
                    obspy_plot(['--outfile', ic.name] + all_files)
예제 #20
0
    def test_plot_complex_gap_few_samples(self):
        """
        Plots three hours with a gap.

        There are 45 minutes of data at the beginning and 45 minutes of data at
        the end.
        """
        start = UTCDateTime(0)
        st = self._create_stream(start, start + 3600 * 3 / 4, 5.0)
        st += self._create_stream(start + 2.25 * 3600, start + 3 * 3600, 5.0)
        st[0].stats.location = '01'
        st[1].stats.location = '01'
        temp_st = self._create_stream(start + 3600 * 3 / 4,
                                      start + 2.25 * 3600, 5.0)
        temp_st[0].stats.location = '02'
        st += temp_st
        # create and compare image
        image_name = 'waveform_complex_gap_few_samples.png'
        with ImageComparison(self.path, image_name) as ic:
            st.plot(outfile=ic.name)
예제 #21
0
 def test_spherical_diff_phases(self):
     """
     Spherical plot of ``diff`` phases.
     """
     with ImageComparison(self.image_dir,
                          "spherical_diff_phases.png") as ic:
         self.model.get_ray_paths(700,
                                  140,
                                  phase_list=[
                                      "Pdiff", "Sdiff", "pSdiff", "sSdiff",
                                      "pPdiff", "sPdiff"
                                  ]).plot_rays(phase_list=[
                                      "Pdiff", "Sdiff", "pSdiff", "sSdiff",
                                      "pPdiff", "sPdiff"
                                  ],
                                               plot_type="spherical",
                                               legend=True,
                                               plot_all=True,
                                               show=False)
         plt.savefig(ic.name)
예제 #22
0
 def test_ppsd_plot_cumulative(self):
     """
     Test plot of ppsd example data, cumulative style.
     """
     # Catch underflow warnings due to plotting on log-scale.
     with np.errstate(all='ignore'):
         with ImageComparison(self.path, 'ppsd_cumulative.png',
                              reltol=1.5) as ic:
             self.ppsd.plot(
                 show=False, show_coverage=True, show_histogram=True,
                 show_noise_models=True, grid=True, period_lim=(0.02, 100),
                 cumulative=True,
                 # This does not do anything but silences a warning that
                 # the `cumulative` and `max_percentage` arguments cannot
                 #  be used at the same time.
                 max_percentage=None)
             fig = plt.gcf()
             ax = fig.axes[0]
             ax.set_ylim(-160, -130)
             plt.draw()
             fig.savefig(ic.name)
예제 #23
0
    def test_scanTimes(self):
        """
        Checks for timing related options
        """
        reltol = 1
        if MATPLOTLIB_VERSION < [1, 3, 0]:
            reltol = 60

        # Copy files to a temp folder to avoid wildcard scans.
        with TemporaryWorkingDirectory():
            for filename in self.all_files:
                shutil.copy(filename, os.curdir)

            with ImageComparison(self.path, 'scan_times.png',
                                 reltol=reltol) as ic:
                with CatchOutput():
                    obspy_scan([os.curdir] + ['--output', ic.name] +
                               ['--start-time', '2004-01-01'] +
                               ['--end-time', '2004-12-31'] +
                               ['--event-time', '2004-03-14T15:09:26'] +
                               ['--event-time', '2004-02-07T18:28:18'])
예제 #24
0
 def test_plot_day_plot_explicit_event(self):
     '''
     Plots day plot, starting Jan 1970, with several events.
     '''
     start = UTCDateTime(0)
     event1 = UTCDateTime(30)       # Event: Top left; Note: below right
     event2 = UTCDateTime(14 * 60)  # Event: Top right; Note: below left
     event3 = UTCDateTime(46 * 60)  # Event: Bottom left; Note: above right
     event4 = UTCDateTime(59 * 60)  # Event: Bottom right; Note: above left
     event5 = UTCDateTime(61 * 60)  # Should be ignored
     st = self._create_stream(start, start + 3600, 100)
     # create and compare image
     image_name = 'waveform_dayplot_event.png'
     with ImageComparison(self.path, image_name) as ic:
         st.plot(outfile=ic.name, type='dayplot',
                 timezone='EST', time_offset=-5,
                 events=[{'time': event1, 'text': 'Event 1'},
                         {'time': event2, 'text': 'Event 2'},
                         {'time': event3, 'text': 'Event 3'},
                         {'time': event4, 'text': 'Event 4'},
                         {'time': event5, 'text': 'Event 5'}])
예제 #25
0
파일: test_scan.py 프로젝트: sphinx07/obspy
    def test_scanner_manually_add_streams(self):
        """
        Test Scanner class, manually adding streams of read data files
        """
        scanner = Scanner()
        # Copy files to a temp folder to avoid wildcard scans.
        with TemporaryWorkingDirectory():
            for filename in self.all_files:
                shutil.copy(filename, os.curdir)

            for file_ in os.listdir(os.curdir):
                # some files used in the test cases actually can not
                # be read with obspy..
                if file_ in ('STA2.testlines_out', 'STA2.testlines',
                             'seism-shorter.sac', 'seism-longer.sac'):
                    continue
                st = read(file_, headonly=True)
                scanner.add_stream(st)

        with ImageComparison(self.path, 'scan.png') as ic:
            scanner.plot(ic.name)
예제 #26
0
 def test_ppsd_plot(self):
     """
     """
     with ImageComparison(self.path, 'ppsd.png') as ic:
         self.ppsd.plot(show=False,
                        show_coverage=True,
                        show_histogram=True,
                        show_percentiles=True,
                        percentiles=[75, 90],
                        show_noise_models=True,
                        grid=True,
                        max_percentage=50,
                        period_lim=(0.02, 100),
                        show_mode=True,
                        show_mean=True)
         from matplotlib.pyplot import gcf, draw
         fig = gcf()
         ax = fig.axes[0]
         ax.set_ylim(-160, -130)
         draw()
         fig.savefig(ic.name)
예제 #27
0
 def test_ppsd_plot(self):
     """
     Test plot of ppsd example data, normal (non-cumulative) style.
     """
     with ImageComparison(self.path, 'ppsd.png') as ic:
         self.ppsd.plot(show=False,
                        show_coverage=True,
                        show_histogram=True,
                        show_percentiles=True,
                        percentiles=[75, 90],
                        show_noise_models=True,
                        grid=True,
                        max_percentage=50,
                        period_lim=(0.02, 100),
                        show_mode=True,
                        show_mean=True)
         fig = plt.gcf()
         ax = fig.axes[0]
         ax.set_ylim(-160, -130)
         plt.draw()
         fig.savefig(ic.name)
예제 #28
0
 def test_catalog_plot_local(self):
     """
     Tests the catalog preview plot, local projection, some more non-default
     parameters, using Basemap.
     """
     cat = read_events()
     reltol = 1.5
     # Basemap smaller 1.0.4 has a serious issue with plotting. Thus the
     # tolerance must be much higher.
     if BASEMAP_VERSION < [1, 0, 4]:
         reltol = 100
     with ImageComparison(self.image_dir,
                          "catalog-basemap3.png",
                          reltol=reltol) as ic:
         rcParams['savefig.dpi'] = 72
         cat.plot(method='basemap',
                  outfile=ic.name,
                  projection='local',
                  resolution='i',
                  continent_fill_color='0.3',
                  color='date',
                  colormap='gist_heat')
예제 #29
0
 def test_plotMultipleTraces(self):
     """
     Plots multiple traces underneath.
     """
     reltol = 1
     if [1, 0, 0] < MATPLOTLIB_VERSION < [1, 2, 0]:
         reltol = 20
     # 1 trace
     st = read()[1]
     with ImageComparison(self.path, 'waveform_1_trace.png',
                          reltol=reltol) as ic:
         st.plot(outfile=ic.name, automerge=False)
     # 3 traces
     st = read()
     with ImageComparison(self.path, 'waveform_3_traces.png',
                          reltol=reltol) as ic:
         st.plot(outfile=ic.name, automerge=False)
     # 5 traces
     st = st[1] * 5
     with ImageComparison(self.path, 'waveform_5_traces.png',
                          reltol=reltol) as ic:
         st.plot(outfile=ic.name, automerge=False)
     # 10 traces
     st = st[1] * 10
     with ImageComparison(self.path,
                          'waveform_10_traces.png',
                          reltol=reltol) as ic:
         st.plot(outfile=ic.name, automerge=False)
     # 10 traces - huge numbers
     st = st[1] * 10
     for i, tr in enumerate(st):
         # scale data to have huge numbers
         st[i].data = tr.data * 10**i
     with ImageComparison(self.path,
                          'waveform_10_traces_huge.png',
                          reltol=reltol) as ic:
         st.plot(outfile=ic.name, automerge=False, equal_scale=False)
     # 10 traces - tiny numbers
     st = st[1] * 10
     for i, tr in enumerate(st):
         # scale data to have huge numbers
         st[i].data = tr.data / (10**i)
     with ImageComparison(self.path,
                          'waveform_10_traces_tiny.png',
                          reltol=reltol) as ic:
         st.plot(outfile=ic.name, automerge=False, equal_scale=False)
예제 #30
0
    def test_multiple_sampling_rates(self):
        """
        Check for multiple sampling rates
        """
        lines = [
            "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
            "2008-01-15T00:00:00.000000, SLIST, INTEGER, Counts",
            "TIMESERIES XX_TEST__BHZ_R,  50 samples,  50 sps, "
            "2008-01-15T00:00:01.000000, SLIST, INTEGER, Counts",
            "TIMESERIES XX_TEST__BHZ_R, 200 samples, 200 sps, "
            "2008-01-15T00:00:02.000000, SLIST, INTEGER, Counts",
        ]

        files = []
        with NamedTemporaryFile() as f1, NamedTemporaryFile() as f2, \
                NamedTemporaryFile() as f3:
            for i, fp in enumerate([f1, f2, f3]):
                fp.write(("%s\n" % lines[i]).encode('ascii', 'strict'))
                fp.flush()
                fp.seek(0)
                files.append(fp.name)
            with ImageComparison(self.path, 'scan_mult_sampl.png')\
                    as ic:
                obspy_scan(files + ['--output', ic.name, '--quiet'])
예제 #31
0
    def test_ppsd_restricted_stacks(self):
        """
        Test PPSD.calculate_histogram() with restrictions to what data should
        be stacked. Also includes image tests.
        """
        # set up a bogus PPSD, with fixed random psds but with real start times
        # of psd pieces, to facilitate testing the stack selection.
        ppsd = PPSD(stats=Stats(dict(sampling_rate=150)),
                    metadata=None,
                    db_bins=(-200, -50, 20.),
                    period_step_octaves=1.4)
        # change data to nowadays used nanoseconds POSIX timestamp
        ppsd._times_processed = [
            UTCDateTime(t)._ns for t in np.load(
                os.path.join(self.path, "ppsd_times_processed.npy")).tolist()
        ]
        np.random.seed(1234)
        ppsd._binned_psds = [
            arr for arr in np.random.uniform(-200, -50, (
                len(ppsd._times_processed), len(ppsd.period_bin_centers)))
        ]

        # Test callback function that selects a fixed random set of the
        # timestamps.  Also checks that we get passed the type we expect,
        # which is 1D numpy ndarray of int type.
        def callback(t_array):
            self.assertIsInstance(t_array, np.ndarray)
            self.assertEqual(t_array.shape, (len(ppsd._times_processed), ))
            self.assertTrue(np.issubdtype(t_array.dtype, np.integer))
            np.random.seed(1234)
            res = np.random.randint(0, 2, len(t_array)).astype(np.bool)
            return res

        # test several different sets of stack criteria, should cover
        # everything, even with lots of combined criteria
        stack_criteria_list = [
            dict(starttime=UTCDateTime(2015, 3, 8), month=[2, 3, 5, 7, 8]),
            dict(endtime=UTCDateTime(2015, 6, 7),
                 year=[2015],
                 time_of_weekday=[(1, 0, 24), (2, 0, 24), (-1, 0, 11)]),
            dict(year=[2013, 2014, 2016, 2017], month=[2, 3, 4]),
            dict(month=[1, 2, 5, 6, 8], year=2015),
            dict(isoweek=[4, 5, 6, 13, 22, 23, 24, 44, 45]),
            dict(time_of_weekday=[(5, 22, 24), (6, 0, 2), (6, 22, 24)]),
            dict(callback=callback, month=[1, 3, 5, 7]),
            dict(callback=callback)
        ]
        expected_selections = np.load(
            os.path.join(self.path, "ppsd_stack_selections.npy"))

        # test every set of criteria
        for stack_criteria, expected_selection in zip(stack_criteria_list,
                                                      expected_selections):
            selection_got = ppsd._stack_selection(**stack_criteria)
            np.testing.assert_array_equal(selection_got, expected_selection)

        # test one particular selection as an image test
        plot_kwargs = dict(max_percentage=15,
                           xaxis_frequency=True,
                           period_lim=(0.01, 50))
        ppsd.calculate_histogram(**stack_criteria_list[1])
        with ImageComparison(self.path_images,
                             'ppsd_restricted_stack.png',
                             reltol=1.5) as ic:
            fig = ppsd.plot(show=False, **plot_kwargs)
            # some matplotlib/Python version combinations lack the left-most
            # tick/label "Jan 2015". Try to circumvent and get the (otherwise
            # OK) test by changing the left x limit a bit further out (by two
            # days, axis is in mpl days). See e.g.
            # https://tests.obspy.org/30657/#1
            fig.axes[1].set_xlim(left=fig.axes[1].get_xlim()[0] - 2)
            with np.errstate(under='ignore'):
                fig.savefig(ic.name)

        # test it again, checking that updating an existing plot with different
        # stack selection works..
        #  a) we start with the stack for the expected image and test that it
        #     matches (like above):
        ppsd.calculate_histogram(**stack_criteria_list[1])
        with ImageComparison(self.path_images,
                             'ppsd_restricted_stack.png',
                             reltol=1.5,
                             plt_close_all_exit=False) as ic:
            fig = ppsd.plot(show=False, **plot_kwargs)
            # some matplotlib/Python version combinations lack the left-most
            # tick/label "Jan 2015". Try to circumvent and get the (otherwise
            # OK) test by changing the left x limit a bit further out (by two
            # days, axis is in mpl days). See e.g.
            # https://tests.obspy.org/30657/#1
            fig.axes[1].set_xlim(left=fig.axes[1].get_xlim()[0] - 2)
            with np.errstate(under='ignore'):
                fig.savefig(ic.name)
        #  b) now reuse figure and set the histogram with a different stack,
        #     image test should fail:
        ppsd.calculate_histogram(**stack_criteria_list[3])
        try:
            with ImageComparison(self.path_images,
                                 'ppsd_restricted_stack.png',
                                 adjust_tolerance=False,
                                 plt_close_all_enter=False,
                                 plt_close_all_exit=False) as ic:
                # rms of the valid comparison above is ~31,
                # rms of the invalid comparison we test here is ~36
                if MATPLOTLIB_VERSION == [1, 1, 1]:
                    ic.tol = 33
                ppsd._plot_histogram(fig=fig, draw=True)
                with np.errstate(under='ignore'):
                    fig.savefig(ic.name)
        except ImageComparisonException:
            pass
        else:
            msg = "Expected ImageComparisonException was not raised."
            self.fail(msg)
        #  c) now reuse figure and set the original histogram stack again,
        #     image test should pass agin:
        ppsd.calculate_histogram(**stack_criteria_list[1])
        with ImageComparison(self.path_images,
                             'ppsd_restricted_stack.png',
                             reltol=1.5,
                             plt_close_all_enter=False) as ic:
            ppsd._plot_histogram(fig=fig, draw=True)
            with np.errstate(under='ignore'):
                fig.savefig(ic.name)