Example #1
0
    def test_read_invalid_filename(self):
        """
        Tests that we get a sane error message when calling read_events()
        with a filename that doesn't exist
        """
        doesnt_exist = 'dsfhjkfs'
        for i in range(10):
            if os.path.exists(doesnt_exist):
                doesnt_exist += doesnt_exist
                continue
            break
        else:
            self.fail('unable to get invalid file path')
        doesnt_exist = native_str(doesnt_exist)

        if PY2:
            exception_type = getattr(builtins, 'IOError')
        else:
            exception_type = getattr(builtins, 'FileNotFoundError')
        exception_msg = "[Errno 2] No such file or directory: '{}'"

        formats = _get_entry_points(
            'obspy.plugin.catalog', 'readFormat').keys()
        # try read_inventory() with invalid filename for all registered read
        # plugins and also for filetype autodiscovery
        formats = [None] + list(formats)
        for format in formats:
            with self.assertRaises(exception_type) as e:
                read_events(doesnt_exist, format=format)
            self.assertEqual(
                str(e.exception), exception_msg.format(doesnt_exist))
Example #2
0
 def test_writing_invalid_quakeml_id(self):
     """
     Some ids might be invalid. We still want to write them to not mess
     with any external tools relying on the ids. But we also raise a
     warning of course.
     """
     filename = os.path.join(self.path, 'invalid_id.xml')
     cat = read_events(filename)
     self.assertEqual(
         cat[0].resource_id.id,
         "smi:org.gfz-potsdam.de/geofon/RMHP(60)>>ITAPER(3)>>BW(4,5,15)")
     with NamedTemporaryFile() as tf:
         with warnings.catch_warnings(record=True) as w:
             warnings.simplefilter("always")
             cat.write(tf.name, format="quakeml")
             cat2 = read_events(tf.name)
     self.assertEqual(len(w), 19)
     self.assertEqual(
         w[0].message.args[0],
         "'smi:org.gfz-potsdam.de/geofon/RMHP(60)>>ITAPER(3)>>BW(4,5,15)' "
         "is not a valid QuakeML URI. It will be in the final file but "
         "note that the file will not be a valid QuakeML file.")
     self.assertEqual(
         cat2[0].resource_id.id,
         "smi:org.gfz-potsdam.de/geofon/RMHP(60)>>ITAPER(3)>>BW(4,5,15)")
Example #3
0
 def test_read_fnetmt_catalog_from_open_files(self):
     """
     Tests that reading an F-net moment tensor file from an open file works.
     """
     testfile = os.path.join(self.path, 'data', 'FNETMTCATALOG')
     with open(testfile, "rb") as fh:
         read_events(fh)
Example #4
0
 def test_avoid_empty_stub_elements(self):
     """
     Test for a bug in reading QuakeML. Makes sure that some subelements do
     not get assigned stub elements, but rather stay None.
     """
     # Test 1: Test subelements of moment_tensor
     memfile = io.BytesIO()
     # create virtually empty FocalMechanism
     mt = MomentTensor(derived_origin_id='smi:local/abc')
     fm = FocalMechanism(moment_tensor=mt)
     event = Event(focal_mechanisms=[fm])
     cat = Catalog(events=[event])
     cat.write(memfile, format="QUAKEML", validate=True)
     # now read again, and make sure there's no stub subelements on
     # MomentTensor, but rather `None`
     memfile.seek(0)
     cat = read_events(memfile, format="QUAKEML")
     self.assertEqual(cat[0].focal_mechanisms[0].moment_tensor.tensor, None)
     self.assertEqual(
         cat[0].focal_mechanisms[0].moment_tensor.source_time_function,
         None)
     # Test 2: Test subelements of focal_mechanism
     memfile = io.BytesIO()
     # create virtually empty FocalMechanism
     fm = FocalMechanism()
     event = Event(focal_mechanisms=[fm])
     cat = Catalog(events=[event])
     cat.write(memfile, format="QUAKEML", validate=True)
     # now read again, and make sure there's no stub MomentTensor, but
     # rather `None`
     memfile.seek(0)
     cat = read_events(memfile, format="QUAKEML")
     self.assertEqual(cat[0].focal_mechanisms[0].nodal_planes, None)
     self.assertEqual(cat[0].focal_mechanisms[0].principal_axes, None)
Example #5
0
 def test_latest_in_scope_object_returned(self):
     """
     Test that the most recently defined object with the same resource_id,
     that is still in scope, is returned from the get_referred_object
     method
     """
     cat1 = read_events()
     # The resource_id attached to the first event is self-pointing
     self.assertIs(cat1[0], cat1[0].resource_id.get_referred_object())
     # make a copy and re-read catalog
     cat2 = cat1.copy()
     cat3 = read_events()
     # the resource_id on the new catalogs point to their attached objects
     self.assertIs(cat1[0], cat1[0].resource_id.get_referred_object())
     self.assertIs(cat2[0], cat2[0].resource_id.get_referred_object())
     self.assertIs(cat3[0], cat3[0].resource_id.get_referred_object())
     # now delete cat1 and make sure cat2 and cat3 still work
     del cat1
     self.assertIs(cat2[0], cat2[0].resource_id.get_referred_object())
     self.assertIs(cat3[0], cat3[0].resource_id.get_referred_object())
     # create a resource_id with the same id as the last defined object
     # with the same resource id (that is still in scope) is returned
     new_id = cat2[0].resource_id.id
     rid = ResourceIdentifier(new_id)
     self.assertIs(rid.get_referred_object(), cat3[0])
     del cat3
     self.assertIs(rid.get_referred_object(), cat2[0])
     del cat2
     self.assertIs(rid.get_referred_object(), None)
Example #6
0
 def test_read_events_with_wildcard(self):
     """
     Tests the read_events() function with a filename wild card.
     """
     # without wildcard..
     expected = read_events(self.iris_xml)
     expected += read_events(self.neries_xml)
     # with wildcard
     got = read_events(os.path.join(self.path, "*_events.xml"))
     self.assertEqual(expected, got)
Example #7
0
    def test_read_fnetmt_catalog_from_bytes_io(self):
        """
        Tests that reading an F-net moment tensor file from a BytesIO objects
        works.
        """
        testfile = os.path.join(self.path, 'data', 'FNETMTCATALOG')
        with open(testfile, "rb") as fh:
            buf = io.BytesIO(fh.read())

        with buf:
            read_events(buf)
Example #8
0
 def test_read_events(self):
     """
     Tests reading a QuakeML document via read_events.
     """
     with NamedTemporaryFile() as tf:
         tmpfile = tf.name
         catalog = read_events(self.neries_filename)
         self.assertTrue(len(catalog), 3)
         catalog.write(tmpfile, format='QUAKEML')
         # Read file again. Avoid the (legit) warning about the already used
         # resource identifiers.
         with warnings.catch_warnings(record=True):
             warnings.simplefilter("ignore")
             catalog2 = read_events(tmpfile)
     self.assertTrue(len(catalog2), 3)
Example #9
0
 def test_readEvents(self):
     """
     Tests the read_events function using entry points.
     """
     # iris
     catalog = read_events(self.iris_xml)
     self.assertEqual(len(catalog), 2)
     self.assertEqual(catalog[0]._format, 'QUAKEML')
     self.assertEqual(catalog[1]._format, 'QUAKEML')
     # neries
     catalog = read_events(self.neries_xml)
     self.assertEqual(len(catalog), 3)
     self.assertEqual(catalog[0]._format, 'QUAKEML')
     self.assertEqual(catalog[1]._format, 'QUAKEML')
     self.assertEqual(catalog[2]._format, 'QUAKEML')
Example #10
0
 def test_event_copying_does_not_raise_duplicate_resource_id_warning(self):
     """
     Tests that copying an event does not raise a duplicate resource id
     warning.
     """
     ev = read_events()[0]
     with warnings.catch_warnings(record=True) as w:
         warnings.simplefilter("always")
         ev2 = copy.copy(ev)
         self.assertEqual(len(w), 0)
         ev3 = copy.deepcopy(ev)
         self.assertEqual(len(w), 0)
     # The two events should compare equal.
     self.assertEqual(ev, ev2)
     self.assertEqual(ev, ev3)
     # get resource_ids and referred objects from each of the events
     rid1 = ev.resource_id
     rid2 = ev2.resource_id
     rid3 = ev3.resource_id
     rob1 = rid1.get_referred_object()
     rob2 = rid2.get_referred_object()
     rob3 = rid3.get_referred_object()
     # A shallow copy should just use the exact same resource identifier,
     # while a deep copy should not, although they should be qual.
     self.assertIs(rid1, rid2)
     self.assertIsNot(rid1, rid3)
     self.assertEqual(rid1, rid3)
     # make sure the object_id on the resource_ids are not the same
     self.assertEqual(rid1._object_id, rid2._object_id)
     self.assertNotEqual(rid1._object_id, rid3._object_id)
     # copy should point to the same object, deep copy should not
     self.assertIs(rob1, rob2)
     self.assertIsNot(rob1, rob3)
     # although the referred objects should be equal
     self.assertEqual(rob1, rob3)
Example #11
0
 def test_read_fnetmt_catalog(self):
     testfile = os.path.join(self.path, 'data', 'FNETMTCATALOG')
     cat = read_events(testfile, 'FNETMT')
     self.assertEqual(len(cat), 1)
     ev = cat[0]
     self.assertEqual(len(ev.origins), 2)
     self.assertEqual(len(ev.magnitudes), 2)
Example #12
0
 def test_preferred_tags(self):
     """
     Testing preferred magnitude, origin and focal mechanism tags
     """
     # testing empty event
     ev = Event()
     self.assertEqual(ev.preferred_origin(), None)
     self.assertEqual(ev.preferred_magnitude(), None)
     self.assertEqual(ev.preferred_focal_mechanism(), None)
     # testing existing event
     filename = os.path.join(self.path, 'preferred.xml')
     catalog = read_events(filename)
     self.assertEqual(len(catalog), 1)
     ev_str = "Event:\t2012-12-12T05:46:24.120000Z | +38.297, +142.373 " + \
              "| 2.0 MW"
     self.assertIn(ev_str, str(catalog.events[0]))
     # testing ids
     ev = catalog.events[0]
     self.assertEqual('smi:orig2', ev.preferred_origin_id)
     self.assertEqual('smi:mag2', ev.preferred_magnitude_id)
     self.assertEqual('smi:fm2', ev.preferred_focal_mechanism_id)
     # testing objects
     self.assertEqual(ev.preferred_origin(), ev.origins[1])
     self.assertEqual(ev.preferred_magnitude(), ev.magnitudes[1])
     self.assertEqual(
         ev.preferred_focal_mechanism(), ev.focal_mechanisms[1])
Example #13
0
 def test_str(self):
     """
     Testing the __str__ method of the Event object.
     """
     event = read_events()[1]
     s = event.short_str()
     self.assertEqual("2012-04-04T14:18:37.000000Z | +39.342,  +41.044" + " | 4.3 ML | manual", s)
Example #14
0
 def test_str(self):
     """
     Testing the __str__ method of the Catalog object.
     """
     catalog = read_events()
     self.assertTrue(catalog.__str__().startswith("3 Event(s) in Catalog:"))
     self.assertTrue(catalog.__str__().endswith("37.736 | 3.0 ML | manual"))
Example #15
0
    def test_event_copying_does_not_raise_duplicate_resource_id_warnings(self):
        """
        Tests that copying an event does not raise a duplicate resource id
        warning.
        """
        ev = read_events()[0]

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            ev2 = copy.copy(ev)
            self.assertEqual(len(w), 0)
            ev3 = copy.deepcopy(ev)
            self.assertEqual(len(w), 0)

        # The two events should compare equal.
        self.assertEqual(ev, ev2)
        self.assertEqual(ev, ev3)

        # A shallow copy should just use the exact same resource identifier,
        # while a deep copy should not.
        self.assertIs(ev.resource_id, ev2.resource_id)
        self.assertIsNot(ev.resource_id, ev3.resource_id)
        self.assertEqual(ev.resource_id, ev3.resource_id)

        # But all should point to the same object.
        self.assertIs(ev.resource_id.get_referred_object(),
                      ev2.resource_id.get_referred_object())
        self.assertIs(ev.resource_id.get_referred_object(),
                      ev3.resource_id.get_referred_object())
Example #16
0
 def test_read_events(self):
     """
     Tests reading a GSE2.0 document via read_events.
     """
     filename = os.path.join(self.path, 'gse_2.0_2_events.txt')
     catalog = read_events(filename)
     self.assertEqual(len(catalog), 2)
Example #17
0
 def test_catalog_plot_global(self):
     """
     Tests the catalog preview plot, default parameters, using Cartopy.
     """
     cat = read_events()
     with ImageComparison(self.image_dir, 'catalog-cartopy1.png') as ic:
         rcParams['savefig.dpi'] = 72
         cat.plot(method='cartopy', outfile=ic.name)
Example #18
0
 def test_plot_farfield_without_quiver_with_maps(self):
     """
     Tests to plot P/S wave farfield radiation pattern, also with beachball
     and some map plots.
     """
     ev = read_events("/path/to/CMTSOLUTION", format="CMTSOLUTION")[0]
     with ImageComparison(self.image_dir, "event.png") as ic:
         ev.plot(kind=[["global"], ["ortho", "beachball"], ["p_sphere", "s_sphere"]], outfile=ic.name)
Example #19
0
    def test_read_string(self):
        """
        Test reading a QuakeML string/unicode object via read_events.
        """
        with open(self.neries_filename, 'rb') as fp:
            data = fp.read()

        catalog = read_events(data)
        self.assertEqual(len(catalog), 3)
Example #20
0
 def setUp(self):
     # Clear the Resource Identifier dict for the tests. NEVER do this
     # otherwise.
     ResourceIdentifier._ResourceIdentifier__resource_id_weak_dict.clear()
     # Also clear the tracker.
     ResourceIdentifier._ResourceIdentifier__resource_id_tracker.clear()
     # set the test catalog as an attr for test access
     self.catalog = self.make_test_catalog()
     # save the catalog to a temp file for testing reading in the catalog
     self.catalog_path = tempfile.mkstemp()[1]
     self.catalog.write(self.catalog_path, 'quakeml')
     # create a list of equal catalogs/events created with read and copy
     self.event_list = [
         self.catalog[0],
         read_events(self.catalog_path)[0],
         read_events(self.catalog_path)[0],
         self.catalog.copy()[0],
         self.catalog.copy()[0],
     ]
Example #21
0
 def test_catalog_plot_ortho(self):
     """
     Tests the catalog preview plot, ortho projection, some non-default
     parameters, using Cartopy.
     """
     cat = read_events()
     with ImageComparison(self.image_dir, 'catalog-cartopy2.png') as ic:
         rcParams['savefig.dpi'] = 72
         cat.plot(method='cartopy', outfile=ic.name, projection='ortho',
                  resolution='c', water_fill_color='b', label=None)
Example #22
0
 def test_read_events(self):
     """
     Tests reading an mchedr document via read_events.
     """
     filename = os.path.join(self.path, 'mchedr.dat')
     # Read file again. Avoid the (legit) warning about the already used
     # resource identifiers.
     with warnings.catch_warnings(record=True):
         catalog = read_events(filename)
         self.assertTrue(len(catalog), 1)
Example #23
0
 def test_read_equivalence(self):
     """
     See #662.
     Tests if _read_quakeml() and read_events() return the same results.
     """
     warnings.simplefilter("ignore", UserWarning)
     cat1 = read_events(self.neries_filename)
     cat2 = _read_quakeml(self.neries_filename)
     warnings.filters.pop(0)
     self.assertEqual(cat1, cat2)
Example #24
0
 def test_catalog_plot_ortho(self):
     """
     Tests the catalog preview plot, ortho projection, some non-default
     parameters.
     """
     cat = read_events()
     with ImageComparison(self.image_dir, "catalog2.png") as ic:
         rcParams['savefig.dpi'] = 72
         cat.plot(outfile=ic.name, projection="ortho",
                  resolution="c",
                  water_fill_color="b", label=None)
Example #25
0
 def test_issue_2339(self):
     """
     Make sure an empty EventDescription object does not prevent a catalog
     from being saved to disk and re-read, while still being equal.
     """
     # create a catalog  with an empty event description
     empty_description = EventDescription()
     cat1 = Catalog(events=[read_events()[0]])
     cat1[0].event_descriptions.append(empty_description)
     # serialize the catalog using quakeml and re-read
     bio = io.BytesIO()
     cat1.write(bio, 'quakeml')
     bio.seek(0)
     cat2 = read_events(bio)
     # the text of the empty EventDescription instances should be equal
     text1 = cat1[0].event_descriptions[-1].text
     text2 = cat2[0].event_descriptions[-1].text
     self.assertEqual(text1, text2)
     # the two catalogs should be equal
     self.assertEqual(cat1, cat2)
Example #26
0
 def test_plotDayPlotCatalog(self):
     """
     Plots day plot, with a catalog of events.
     """
     start = UTCDateTime(2012, 4, 4, 14, 0, 0)
     cat = read_events()
     st = self._createStream(start, start + 3600, 100)
     # create and compare image
     image_name = "waveform_dayplot_catalog.png"
     with ImageComparison(self.path, image_name) as ic:
         st.plot(outfile=ic.name, type="dayplot", timezone="EST", time_offset=-5, events=cat)
Example #27
0
 def test_catalog_plot_global(self):
     """
     Tests the catalog preview plot, default parameters, using Basemap.
     """
     cat = read_events()
     reltol = 1
     if BASEMAP_VERSION < [1, 0, 7]:
         reltol = 3
     with ImageComparison(self.image_dir, "catalog-basemap1.png", reltol=reltol) as ic:
         rcParams["savefig.dpi"] = 72
         cat.plot(method="basemap", outfile=ic.name)
Example #28
0
 def test_getitem(self):
     """
     Tests the __getitem__ method of the Catalog object.
     """
     catalog = read_events()
     self.assertEqual(catalog[0], catalog.events[0])
     self.assertEqual(catalog[-1], catalog.events[-1])
     self.assertEqual(catalog[2], catalog.events[2])
     # out of index should fail
     self.assertRaises(IndexError, catalog.__getitem__, 3)
     self.assertRaises(IndexError, catalog.__getitem__, -99)
Example #29
0
 def test_catalog_plot_local(self):
     """
     Tests the catalog preview plot, local projection, some more non-default
     parameters, using Cartopy.
     """
     cat = read_events()
     with ImageComparison(self.image_dir, 'catalog-cartopy3.png') as ic:
         rcParams['savefig.dpi'] = 72
         cat.plot(method='cartopy', outfile=ic.name, projection='local',
                  resolution='50m', continent_fill_color='0.3',
                  color='date', colormap='gist_heat')
Example #30
0
 def test_copy(self):
     """
     Testing the copy method of the Catalog object.
     """
     cat = read_events()
     cat2 = cat.copy()
     self.assertEqual(cat, cat2)
     self.assertEqual(cat2, cat)
     self.assertFalse(cat is cat2)
     self.assertFalse(cat2 is cat)
     self.assertEqual(cat.events[0], cat2.events[0])
     self.assertFalse(cat.events[0] is cat2.events[0])