Beispiel #1
0
 def setUp(self):
     self.flinnengdahl = FlinnEngdahl()
     self.samples_file = os.path.join(
         os.path.dirname(__file__),
         'data',
         'flinnengdahl.csv'
     )
Beispiel #2
0
def main():
    parser = OptionParser(__doc__.strip(), version="%prog " + __version__)
    (options, args) = parser.parse_args()

    if len(args) != 2:
        parser.print_help()
        sys.exit(1)

    longitude = float(args[0])
    latitude = float(args[1])

    flinn_engdahl = FlinnEngdahl()
    print flinn_engdahl.get_region(longitude, latitude)
Beispiel #3
0
def main():
    parser = OptionParser(__doc__.strip(), version="%prog " + __version__)
    (_options, args) = parser.parse_args()

    if len(args) != 2:
        parser.print_help()
        sys.exit(1)

    longitude = float(args[0])
    latitude = float(args[1])

    flinn_engdahl = FlinnEngdahl()
    print(flinn_engdahl.get_region(longitude, latitude))
Beispiel #4
0
def main(argv=None):
    parser = ArgumentParser(prog='obspy-flinn-engdahl',
                            description=__doc__.strip())
    parser.add_argument('-V', '--version', action='version',
                        version='%(prog)s ' + __version__)
    parser.add_argument('longitude', type=float,
                        help='Longitude (in degrees) of point. Positive for '
                             'East, negative for West.')
    parser.add_argument('latitude', type=float,
                        help='Latitude (in degrees) of point. Positive for '
                             'North, negative for South.')
    args = parser.parse_args(argv)

    flinn_engdahl = FlinnEngdahl()
    print(flinn_engdahl.get_region(args.longitude, args.latitude))
Beispiel #5
0
 def setUp(self):
     self.flinnengdahl = FlinnEngdahl()
     self.samples_file = os.path.join(
         os.path.dirname(__file__),
         'data',
         'flinnengdahl.csv'
     )
Beispiel #6
0
class UtilFlinnEngdahlTestCase(unittest.TestCase):
    def setUp(self):
        self.flinnengdahl = FlinnEngdahl()
        self.samples_file = os.path.join(
            os.path.dirname(__file__),
            'data',
            'flinnengdahl.csv'
        )

    def test_coordinates(self):
        with open(self.samples_file, 'r') as fh:
            for line in fh:
                longitude, latitude, checked_region = line.strip().split('\t')
                longitude = float(longitude)
                latitude = float(latitude)

                region = self.flinnengdahl.get_region(longitude, latitude)
                self.assertEqual(
                    region,
                    checked_region,
                    msg="%f, %f got %s instead of %s" % (
                        longitude,
                        latitude,
                        region,
                        checked_region
                    )
                )
Beispiel #7
0
class UtilFlinnEngdahlTestCase(unittest.TestCase):
    def setUp(self):
        self.flinnengdahl = FlinnEngdahl()
        self.samples_file = os.path.join(
            os.path.dirname(__file__),
            'data',
            'flinnengdahl.csv'
        )

    def test_coordinates(self):
        with open(self.samples_file, 'r') as fh:
            for line in fh:
                longitude, latitude, checked_region = line.strip().split('\t')
                longitude = float(longitude)
                latitude = float(latitude)

                region = self.flinnengdahl.get_region(longitude, latitude)
                self.assertEqual(
                    region,
                    checked_region,
                    msg="%f, %f got %s instead of %s" % (
                        longitude,
                        latitude,
                        region,
                        checked_region
                    )
                )
Beispiel #8
0
    def get_event_info(self, event_name):
        """
        Returns a dictionary with information about one, specific event.
        """
        from obspy.core.util import FlinnEngdahl

        all_events = self.get_event_dict()
        if event_name not in all_events:
            msg = "Event '%s' not found in project." % event_name
            raise ValueError(msg)
        event = self.get_event(event_name)
        mag = event.preferred_magnitude() or event.magnitudes[0]
        org = event.preferred_origin() or event.origins[0]

        if org.depth is None:
            warnings.warn("Origin contains no depth. Will be assumed to be 0")
            org.depth = 0.0

        if mag.magnitude_type is None:
            warnings.warn("Magnitude has no specified type. Will be assumed "
                          "to be Mw")
            mag.magnitude_type = "Mw"

        info = {
            "latitude": org.latitude,
            "longitude": org.longitude,
            "origin_time": org.time,
            "depth_in_km": org.depth / 1000.0,
            "magnitude": mag.mag,
            "region": FlinnEngdahl().get_region(org.longitude, org.latitude),
            "magnitude_type": mag.magnitude_type
        }
        return info
Beispiel #9
0
    def _extract_index_values_quakeml(filename):
        """
        Reads QuakeML files and extracts some keys per channel. Only one
        event per file is allows.
        """
        from obspy.core.util import FlinnEngdahl

        try:
            cat = obspy.readEvents(filename)
        except:
            msg = "Not a valid QuakeML file?"
            raise EventCacheError(msg)

        if len(cat) != 1:
            warnings.warn(
                "Each QuakeML file must have exactly one event. Event '%s' "
                "has %i. Only the first one will be parsed." % (
                    filename, len(cat)), LASIFWarning)

        event = cat[0]

        # Extract information.
        mag = event.preferred_magnitude() or event.magnitudes[0]
        org = event.preferred_origin() or event.origins[0]
        if org.depth is None:
            warnings.warn("Origin contains no depth. Will be assumed to be 0",
                          LASIFWarning)
            org.depth = 0.0
        if mag.magnitude_type is None:
            warnings.warn("Magnitude has no specified type. Will be assumed "
                          "to be Mw", LASIFWarning)
            mag.magnitude_type = "Mw"

        # Get the moment tensor.
        fm = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
        mt = fm.moment_tensor.tensor

        event_name = os.path.splitext(os.path.basename(filename))[0]

        return [[
            str(filename),
            str(event_name),
            float(org.latitude),
            float(org.longitude),
            float(org.depth / 1000.0),
            float(org.time.timestamp),
            float(mt.m_rr),
            float(mt.m_pp),
            float(mt.m_tt),
            float(mt.m_rp),
            float(mt.m_rt),
            float(mt.m_tp),
            float(mag.mag),
            str(mag.magnitude_type),
            str(FlinnEngdahl().get_region(org.longitude, org.latitude))
        ]]
Beispiel #10
0
class UtilFlinnEngdahlTestCase(unittest.TestCase):
    def setUp(self):
        self.flinnengdahl = FlinnEngdahl()
        self.samples_file = os.path.join(
            os.path.dirname(__file__),
            'data',
            'flinnengdahl.csv'
        )

    def test_coordinates(self):
        with open(self.samples_file, 'r') as fh:
            for line in fh:
                longitude, latitude, checked_region = line.strip().split('\t')
                longitude = float(longitude)
                latitude = float(latitude)

                region = self.flinnengdahl.get_region(longitude, latitude)
                self.assertEqual(
                    region,
                    checked_region,
                    msg="(%f, %f) got %s instead of %s" % (
                        longitude,
                        latitude,
                        region,
                        checked_region
                    )
                )

    def test_script(self):
        with open(self.samples_file, 'r') as fh:
            # Testing once is sufficient.
            line = fh.readline()
            longitude, latitude, checked_region = line.strip().split('\t')

            with CatchOutput() as out:
                obspy_flinnengdahl([longitude, latitude])
            region = out.stdout.strip()

            self.assertEqual(
                region,
                checked_region.encode('utf-8'),
                msg='(%s, %s) got %s instead of %s' % (
                    longitude,
                    latitude,
                    region,
                    checked_region
                )
            )
Beispiel #11
0
    def _plotEvent(self, event):
        """
        Helper function to plot an event into the dayplot.
        """
        if hasattr(event, "preferred_origin"):
            # Get the time from the preferred origin, alternatively the first
            # origin.
            origin = event.preferred_origin()
            if origin is None:
                if event.origins:
                    origin = event.origins[0]
                else:
                    return
            time = origin.time

            # Do the same for the magnitude.
            mag = event.preferred_magnitude()
            if mag is None:
                if event.magnitudes:
                    mag = event.magnitudes[0]
            if mag is None:
                mag = ""
            else:
                mag = "%.1f %s" % (mag.mag, mag.magnitude_type)

            region = FlinnEngdahl().get_region(origin.longitude,
                                               origin.latitude)
            text = region
            if mag:
                text += ", %s" % mag
        else:
            time = event["time"]
            text = event["text"] if "text" in event else None

        # Nothing to do if the event is not on the plot.
        if time < self.starttime or time > self.endtime:
            return
        # Now find the position of the event in plot coordinates.
        frac = (time - self.starttime) / (self.endtime - self.starttime)
        int_frac = (self.interval) / (self.endtime - self.starttime)
        event_frac = frac / int_frac
        y_pos = self.extreme_values.shape[0] - int(event_frac) - 0.5
        x_pos = (event_frac - int(event_frac)) * self.width

        if text:
            # Some logic to get a somewhat sane positioning of the annotation
            # box and the arrow..
            text_offset_x = 0.10 * self.width
            text_offset_y = 1.00
            # Relpos determines the connection of the arrow on the box in
            # relative coordinates.
            relpos = [0.0, 0.5]
            # Arc strength is the amount of bending of the arrow.
            arc_strength = 0.25
            if x_pos < (self.width / 2.0):
                text_offset_x_sign = 1.0
                ha = "left"
                # Arc sign determines the direction of bending.
                arc_sign = "+"
            else:
                text_offset_x_sign = -1.0
                ha = "right"
                relpos[0] = 1.0
                arc_sign = "-"
            if y_pos < (self.extreme_values.shape[0] / 2.0):
                text_offset_y_sign = 1.0
                va = "bottom"
            else:
                text_offset_y_sign = -1.0
                va = "top"
                if arc_sign == "-":
                    arc_sign = "+"
                else:
                    arc_sign = "-"

            # Draw the annotation including box.
            self.fig.axes[0].annotate(
                text,
                # The position of the event.
                xy=(x_pos, y_pos),
                # The position of the text, offset depending on the previously
                # calculated variables.
                xytext=(x_pos + text_offset_x_sign * text_offset_x,
                        y_pos + text_offset_y_sign * text_offset_y),
                # Everything in data coordinates.
                xycoords="data",
                textcoords="data",
                # Set the text alignment.
                ha=ha,
                va=va,
                # Text box style.
                bbox=dict(boxstyle="round", fc="w", alpha=0.6),
                # Arrow style
                arrowprops=dict(arrowstyle="-",
                                connectionstyle="arc3, rad=%s%.1f" %
                                (arc_sign, arc_strength),
                                relpos=relpos,
                                shrinkB=7),
                zorder=10)
        # Draw the actual point. Use a marker with a star shape.
        self.fig.axes[0].plot(x_pos, y_pos, "*", color="yellow", markersize=12)