def data(self, index, role):
     if not index.isValid():
         return QtCore.QVariant()
     if role == QtCore.Qt.DisplayRole:
         pick = self.picks[index.row()]
         # Map the column to an attribute.
         column = index.column()
         if column == 0:
             return QtCore.QVariant(pick.waveform_id.getSEEDString())
         elif column == 1:
             phase_hint = pick.phase_hint
             if phase_hint is None:
                 phase_hint = "-"
             return QtCore.QVariant(str(phase_hint))
         elif column == 2:
             polarity = pick.polarity
             if polarity is None:
                 polarity = "-"
             return QtCore.QVariant(str(polarity))
         elif column == 3:
             evaluation_mode = pick.evaluation_mode
             if evaluation_mode is None:
                 evaluation_mode = "-"
             return QtCore.QVariant(str(evaluation_mode))
         # The distance column.
         elif column == 4:
             coods = pick.data[0].stats.coordinates
             distance = lat_long_to_distance(
                 self.event.origins[0].latitude,
                 self.event.origins[0].longitude,
                 self.event.origins[0].depth, coods.latitude,
                 coods.longitude, coods.elevation / 1000.0)
             return QtCore.QVariant("%.3f" % distance)
         elif column == 5:
             if hasattr(pick, "data"):
                 return QtCore.QVariant("Yes")
             return QtCore.QVariant("No")
     # Set the background color for column id 4
     if role == QtCore.Qt.BackgroundRole and index.column() == 5:
         pick = self.picks[index.row()]
         if hasattr(pick, "data"):
             return QtGui.QBrush(QtGui.QColor("#e2ffa4"))
         return QtGui.QBrush(QtGui.QColor("#ff8768"))
     # Some tooltip for everything.
     if role == QtCore.Qt.ToolTipRole:
         pick = self.picks[index.row()]
         coods = pick.data[0].stats.coordinates
         coods = "Lat: %.4f | Lng: %.4f | Elevation: %.1f" % ( \
             coods.latitude, coods.longitude, coods.elevation)
         return QtCore.QVariant(coods)
 def data(self, index, role):
     if not index.isValid():
         return QtCore.QVariant()
     if role == QtCore.Qt.DisplayRole:
         pick = self.picks[index.row()]
         # Map the column to an attribute.
         column = index.column()
         if column == 0:
             return QtCore.QVariant(pick.waveform_id.getSEEDString())
         elif column == 1:
             phase_hint = pick.phase_hint
             if phase_hint is None:
                 phase_hint = "-"
             return QtCore.QVariant(str(phase_hint))
         elif column == 2:
             polarity = pick.polarity
             if polarity is None:
                 polarity = "-"
             return QtCore.QVariant(str(polarity))
         elif column == 3:
             evaluation_mode = pick.evaluation_mode
             if evaluation_mode is None:
                 evaluation_mode = "-"
             return QtCore.QVariant(str(evaluation_mode))
         # The distance column.
         elif column == 4:
             coods = pick.data[0].stats.coordinates
             distance = lat_long_to_distance(self.event.origins[0].latitude,
                 self.event.origins[0].longitude,
                 self.event.origins[0].depth, coods.latitude,
                 coods.longitude, coods.elevation / 1000.0)
             return QtCore.QVariant("%.3f" % distance)
         elif column == 5:
             if hasattr(pick, "data"):
                 return QtCore.QVariant("Yes")
             return QtCore.QVariant("No")
     # Set the background color for column id 4
     if role == QtCore.Qt.BackgroundRole and index.column() == 5:
         pick = self.picks[index.row()]
         if hasattr(pick, "data"):
             return QtGui.QBrush(QtGui.QColor("#e2ffa4"))
         return QtGui.QBrush(QtGui.QColor("#ff8768"))
     # Some tooltip for everything.
     if role == QtCore.Qt.ToolTipRole:
         pick = self.picks[index.row()]
         coods = pick.data[0].stats.coordinates
         coods = "Lat: %.4f | Lng: %.4f | Elevation: %.1f" % ( \
             coods.latitude, coods.longitude, coods.elevation)
         return QtCore.QVariant(coods)
    def _calculate_final_values(self):
        """
        Takes every dict stored in self.results and produces the final output.
        """
        # If no results are available, nothing is to be done.
        if len(self.results) == 0:
            self.ui.mean_parameter_line_1.setText("-")
            self.ui.mean_parameter_line_2.setText("-")
            if hasattr(self, "current_status"):
                self.current_status["final_results"] = {}
            self.ui.save_file_button.setEnabled(False)
            return
        # Do all the calculations per station and phase.
        stations = {}
        for result in self.results:
            station = ".".join(result["channel"].split(".")[:2])
            if not station in stations:
                stations[station] = { \
                    "p": [],
                    "s": []}
            # The conditional is not strictly necessary but takes care that no
            # other phases slip in.
            if result["phase"].lower() == "p":
                stations[station]["p"].append(result)
            elif result["phase"].lower() == "s":
                stations[station]["s"].append(result)
        # Save the station count for later inclusion in the QuakeML file.
        station_count = len(stations.keys())
        # For every phase, calculate the seismic source parameters M_0 and r.
        # Also take the mean of all Q values, just because they are available.
        final_results = { \
            "M_0": [],
            "r": [],
            "Q": []}
        # Loop over all picks and calculate the values.
        for station_id, phases in stations.iteritems():
            for phase, results in phases.iteritems():
                if len(results) == 0:
                    continue
                # Collect the three variables extracted from the spectra.
                omega_0 = [_i["omega_0"] for _i in results]
                f_c = [_i["corner_frequency"] for _i in results]
                Q = [_i["quality_factor"] for _i in results]

                # The traveltime is necessary for the seismic moment
                # calculation.
                # XXX: This is also calculated for the pick table. Get it from
                # there!
                coordinates = None
                for pick in self.current_state["event"].picks:
                    if ("%s.%s" % (pick.data[0].stats.network,
                        pick.data[0].stats.station)) == station_id:
                        coordinates = pick.data[0].stats.coordinates
                if coordinates is None:
                    print "Warning: No coordinates for the station found."
                    continue
                # Hypocentral distance in meter.
                distance = lat_long_to_distance( \
                    self.current_state["event"].origins[0].latitude,
                    self.current_state["event"].origins[0].longitude,
                    self.current_state["event"].origins[0].depth,
                    coordinates.latitude,
                    coordinates.longitude,
                    coordinates.elevation / 1000.0) * 1000.0
                # Now everything necessary is available. Call the function
                # necessary to calculate everything.
                M_0 = moment_from_low_freq_amplitude(omega_0,
                    self.current_state["density"],
                    self.current_state["p_wave_speed"],
                    distance, phase)
                source_radius = source_radius_from_corner_frequency(f_c,
                    self.current_state["s_wave_speed"], phase)
                # Append it to the final result.
                final_results["M_0"].append(M_0)
                final_results["r"].append(source_radius)
                final_results["Q"].extend(Q)
        # Now calculate the composite result.
        station_count = len(final_results["M_0"])
        M_0 = sum(final_results["M_0"]) / float(len(final_results["M_0"]))
        mag = moment_to_moment_magnitude(M_0)
        source_radius = \
            sum(final_results["r"]) / float(len(final_results["r"]))
        stress_drop = calculate_stress_drop(M_0, source_radius)
        quality_factor = sum(final_results["Q"]) / \
            float(len(final_results["Q"]))
        self.final_result = { \
            "seismic_moment": M_0,
            "moment_magnitude": mag,
            "source_radius": source_radius,
            "stress_drop": stress_drop,
            "quality_factor": quality_factor,
            "station_count": station_count}
        string = u"M₀: %.3e [Nm] || Mw: %.3f || Q: %.1f" % \
            (M_0, mag, quality_factor)
        self.ui.mean_parameter_line_1.setText(string)
        string = u"Source radius: %.1f || Stress drop: %.2f" % \
            (source_radius, stress_drop / 1E5)
        self.ui.mean_parameter_line_2.setText(string)
        self.ui.save_file_button.setEnabled(True)
    def _calculate_final_values(self):
        """
        Takes every dict stored in self.results and produces the final output.
        """
        # If no results are available, nothing is to be done.
        if len(self.results) == 0:
            self.ui.mean_parameter_line_1.setText("-")
            self.ui.mean_parameter_line_2.setText("-")
            if hasattr(self, "current_status"):
                self.current_status["final_results"] = {}
            self.ui.save_file_button.setEnabled(False)
            return
        # Do all the calculations per station and phase.
        stations = {}
        for result in self.results:
            station = ".".join(result["channel"].split(".")[:2])
            if not station in stations:
                stations[station] = { \
                    "p": [],
                    "s": []}
            # The conditional is not strictly necessary but takes care that no
            # other phases slip in.
            if result["phase"].lower() == "p":
                stations[station]["p"].append(result)
            elif result["phase"].lower() == "s":
                stations[station]["s"].append(result)
        # Save the station count for later inclusion in the QuakeML file.
        station_count = len(stations.keys())
        # For every phase, calculate the seismic source parameters M_0 and r.
        # Also take the mean of all Q values, just because they are available.
        final_results = { \
            "M_0": [],
            "r": [],
            "Q": []}
        # Loop over all picks and calculate the values.
        for station_id, phases in stations.iteritems():
            for phase, results in phases.iteritems():
                if len(results) == 0:
                    continue
                # Collect the three variables extracted from the spectra.
                omega_0 = [_i["omega_0"] for _i in results]
                f_c = [_i["corner_frequency"] for _i in results]
                Q = [_i["quality_factor"] for _i in results]

                # The traveltime is necessary for the seismic moment
                # calculation.
                # XXX: This is also calculated for the pick table. Get it from
                # there!
                coordinates = None
                for pick in self.current_state["event"].picks:
                    if ("%s.%s" % (pick.data[0].stats.network,
                                   pick.data[0].stats.station)) == station_id:
                        coordinates = pick.data[0].stats.coordinates
                if coordinates is None:
                    print "Warning: No coordinates for the station found."
                    continue
                # Hypocentral distance in meter.
                distance = lat_long_to_distance( \
                    self.current_state["event"].origins[0].latitude,
                    self.current_state["event"].origins[0].longitude,
                    self.current_state["event"].origins[0].depth,
                    coordinates.latitude,
                    coordinates.longitude,
                    coordinates.elevation / 1000.0) * 1000.0
                # Now everything necessary is available. Call the function
                # necessary to calculate everything.
                M_0 = moment_from_low_freq_amplitude(
                    omega_0, self.current_state["density"],
                    self.current_state["p_wave_speed"], distance, phase)
                source_radius = source_radius_from_corner_frequency(
                    f_c, self.current_state["s_wave_speed"], phase)
                # Append it to the final result.
                final_results["M_0"].append(M_0)
                final_results["r"].append(source_radius)
                final_results["Q"].extend(Q)
        # Now calculate the composite result.
        station_count = len(final_results["M_0"])
        M_0 = sum(final_results["M_0"]) / float(len(final_results["M_0"]))
        mag = moment_to_moment_magnitude(M_0)
        source_radius = \
            sum(final_results["r"]) / float(len(final_results["r"]))
        stress_drop = calculate_stress_drop(M_0, source_radius)
        quality_factor = sum(final_results["Q"]) / \
            float(len(final_results["Q"]))
        self.final_result = { \
            "seismic_moment": M_0,
            "moment_magnitude": mag,
            "source_radius": source_radius,
            "stress_drop": stress_drop,
            "quality_factor": quality_factor,
            "station_count": station_count}
        string = u"M₀: %.3e [Nm] || Mw: %.3f || Q: %.1f" % \
            (M_0, mag, quality_factor)
        self.ui.mean_parameter_line_1.setText(string)
        string = u"Source radius: %.1f || Stress drop: %.2f" % \
            (source_radius, stress_drop / 1E5)
        self.ui.mean_parameter_line_2.setText(string)
        self.ui.save_file_button.setEnabled(True)