Exemplo n.º 1
0
    def __init__(self):

        super(TimeFrequencyFrame, self).__init__()
        self.setupUi(self)
        self.__stations_dir = None
        self.__metadata_manager = None
        self.inventory = {}
        self._stations_info = {}
        self.tr1 = []
        self.tr2 = []
        self.canvas_plot1 = MatplotlibCanvas(self.widget_plot_up, nrows=2)
        # self.canvas_plot1.set_xlabel(1, "Time (s)")
        # self.canvas_plot1.set_ylabel(0, "Amplitude ")
        # self.canvas_plot1.set_ylabel(1, "Frequency (Hz)")
        self.canvas_plot2 = MatplotlibCanvas(self.widget_plot_down, nrows=2)
        # self.canvas_plot2.set_xlabel(1, "Time (s)")
        # self.canvas_plot2.set_ylabel(0, "Amplitude ")
        # self.canvas_plot2.set_ylabel(1, "Frequency (Hz)")
        # Binding
        self.canvas_plot1.mpl_connect('key_press_event', self.key_pressed)
        self.canvas_plot2.mpl_connect('key_press_event', self.key_pressed)
        self.root_path_bind = BindPyqtObject(self.rootPathForm,
                                             self.onChange_root_path)
        self.dataless_path_bind = BindPyqtObject(self.datalessPathForm)
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        # Add file selector to the widget
        self.file_selector = FilesView(
            self.root_path_bind.value,
            parent=self.fileSelectorWidget,
            on_change_file_callback=lambda file_path: self.onChange_file(
                file_path))
        # Binds
        self.selectDirBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.root_path_bind))
        self.datalessBtn.clicked.connect(
            lambda: self.on_click_select_file(self.dataless_path_bind))
        # Action Buttons
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.actionOpen_Spectral_Analysis.triggered.connect(
            self.time_frequency_advance)
        self.plotBtn.clicked.connect(self.plot_seismogram)
        self.stationsBtn.clicked.connect(self.stations_info)

        # help Documentation
        self.help = HelpDoc()

        # Parameters settings
        self.parameters = ParametersSettings()
Exemplo n.º 2
0
    def __init__(self):
        super(MTIFrame, self).__init__()
        self.setupUi(self)

        #super(MTIFrame, self).__init__()
        self.setupUi(self)
        self.__stations_dir = None
        self.__metadata_manager = None
        self.inventory = {}
        self._stations_info = {}
        self.stream = None
        # Binding
        self.root_path_bind = BindPyqtObject(self.rootPathForm)
        #self.dataless_path_bind = BindPyqtObject(self.datalessPathForm)
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        self.earth_path_bind = BindPyqtObject(self.earth_modelPathForm)

        # Binds
        self.selectDirBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.root_path_bind))
        self.datalessBtn.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.metadata_path_bind
                                                       ))
        self.earthmodelBtn.clicked.connect(
            lambda: self.on_click_select_file(self.earth_path_bind))

        # Action Buttons
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.plotBtn.clicked.connect(self.plot_seismograms)
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionWrite.triggered.connect(self.write)
        self.actionEarth_Model.triggered.connect(
            lambda: self.open_earth_model())
        self.actionFrom_File.triggered.connect(
            lambda: self.load_event_from_isolapath())
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.stationsBtn.clicked.connect(self.stationsInfo)
        self.run_inversionBtn.clicked.connect(lambda: self.run_inversion())
        self.stations_mapBtn.clicked.connect(lambda: self.plot_map_stations())
        self.plot_solutionBtn.clicked.connect(lambda: self.plot_solution())
        #self.earthmodelBtn.clicked.connect(self.read_earth_model)
        # Parameters settings
        self.parameters = ParametersSettings()
        self.earth_model = CrustalModelParametersFrame()
        # help Documentation

        self.help = HelpDoc()
Exemplo n.º 3
0
 def __init__(self):
     self.main_frame = None
     self.time_frequency_frame = None
     self.earthquake_analysis_frame = None
     self.array_analysis_frame = None
     self.moment_tensor_frame = None
     self.receiver_functions_frame = None
     self.project_frame = None
     self.synthetics_frame = None
     self.data_download_frame = None
     self.ppds_frame = None
     self.realtime_frame = None
     self.noise_frame = None
     self.help = HelpDoc()
Exemplo n.º 4
0
    def __init__(self):
        super(NoiseFrame, self).__init__()
        self.setupUi(self)

        self.setWindowTitle('Seismic Ambient Noise')
        self.setWindowIcon(pqg.QIcon(':\icons\map-icon.png'))

        # Settings dialog
        self.settings_dialog = SettingsDialogNoise(self)

        # Parameters settings
        self.parameters = ParametersSettings()

        # Create tabs and add them to tabWidget
        # TODO: sharing parameters and settings this way. Should they be shared?
        # Or they are only specific to EGFFrame?
        self.egf_frame = EGFFrame(self.parameters, self.settings_dialog)
        self.ft_frame = FrequencyTimeFrame()
        self.tabWidget.addTab(self.egf_frame, 'EGFs')
        self.tabWidget.addTab(self.ft_frame, 'Frequency Time Analysis')

        # Help Documentation
        self.help = HelpDoc()

        # Actions
        self.actionSet_Parameters.triggered.connect(
            self.open_parameters_settings)
        self.actionOpen_Settings.triggered.connect(self.settings_dialog.show)

        # Shortcuts
        self.shortcut_open = pw.QShortcut(pqg.QKeySequence('Ctrl+L'), self)
        self.shortcut_open.activated.connect(self.open_parameters_settings)
Exemplo n.º 5
0
    def __init__(self):
        super(BaseFrame, self).__init__()
        self.setupUi(self)
        self.inventory = {}
        self.network_list = []
        self.stations_list = []
        self.catalogBtn.clicked.connect(self.get_catalog)
        self.event_dataBtn.clicked.connect(self.download_events)
        self.plotstationsBtn.clicked.connect(self.stations)
        self.TimeBtn.clicked.connect(self.download_time_series)
        self.MetadataBtn.clicked.connect(self.download_stations_xml)
        self.LoadBtn.clicked.connect(self.load_inventory)
        # Map
        self.cartopy_canvas = CartopyCanvas(self.map)
        self.cartopy_canvas.global_map(0)
        self.cartopy_canvas.figure.subplots_adjust(left=0.00,
                                                   bottom=0.055,
                                                   right=0.97,
                                                   top=0.920,
                                                   wspace=0.0,
                                                   hspace=0.0)
        self.activated_colorbar = True
        self.cartopy_canvas.on_double_click(self.on_click_matplotlib)
        self.cartopy_canvas.mpl_connect('key_press_event', self.key_pressed)
        self.cartopy_canvas.mpl_connect('button_press_event', self.press_right)
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        # signal doubleclick
        self.tableWidget.cellDoubleClicked.connect(self.get_coordinates)

        # help Documentation

        self.help = HelpDoc()

        #
        self.latitudes = []
        self.longitudes = []
        self.depths = []
        self.magnitudes = []
Exemplo n.º 6
0
class TimeFrequencyFrame(BaseFrame, UiTimeFrequencyFrame):
    def __init__(self):

        super(TimeFrequencyFrame, self).__init__()
        self.setupUi(self)
        self.__stations_dir = None
        self.__metadata_manager = None
        self.inventory = {}
        self._stations_info = {}
        self.tr1 = []
        self.tr2 = []
        self.canvas_plot1 = MatplotlibCanvas(self.widget_plot_up, nrows=2)
        # self.canvas_plot1.set_xlabel(1, "Time (s)")
        # self.canvas_plot1.set_ylabel(0, "Amplitude ")
        # self.canvas_plot1.set_ylabel(1, "Frequency (Hz)")
        self.canvas_plot2 = MatplotlibCanvas(self.widget_plot_down, nrows=2)
        # self.canvas_plot2.set_xlabel(1, "Time (s)")
        # self.canvas_plot2.set_ylabel(0, "Amplitude ")
        # self.canvas_plot2.set_ylabel(1, "Frequency (Hz)")
        # Binding
        self.canvas_plot1.mpl_connect('key_press_event', self.key_pressed)
        self.canvas_plot2.mpl_connect('key_press_event', self.key_pressed)
        self.root_path_bind = BindPyqtObject(self.rootPathForm,
                                             self.onChange_root_path)
        self.dataless_path_bind = BindPyqtObject(self.datalessPathForm)
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        # Add file selector to the widget
        self.file_selector = FilesView(
            self.root_path_bind.value,
            parent=self.fileSelectorWidget,
            on_change_file_callback=lambda file_path: self.onChange_file(
                file_path))
        # Binds
        self.selectDirBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.root_path_bind))
        self.datalessBtn.clicked.connect(
            lambda: self.on_click_select_file(self.dataless_path_bind))
        # Action Buttons
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.actionOpen_Spectral_Analysis.triggered.connect(
            self.time_frequency_advance)
        self.plotBtn.clicked.connect(self.plot_seismogram)
        self.stationsBtn.clicked.connect(self.stations_info)

        # help Documentation
        self.help = HelpDoc()

        # Parameters settings
        self.parameters = ParametersSettings()

        # Time Frequency Advance
        #self.time_frequency_advance = TimeFrequencyAdvance()

    def filter_error_message(self, msg):
        md = MessageDialog(self)
        md.set_info_message(msg)

    def message_dataless_not_found(self):
        if len(self.dataless_not_found) > 1:
            md = MessageDialog(self)
            md.set_info_message("Metadata not found.")
        else:
            for file in self.dataless_not_found:
                md = MessageDialog(self)
                md.set_info_message("Metadata for {} not found.".format(file))

        self.dataless_not_found.clear()

    def open_parameters_settings(self):
        self.parameters.show()

    def time_frequency_advance(self):
        self._time_frequency_advance = TimeFrequencyAdvance(self.tr1, self.tr2)
        self._time_frequency_advance.show()

    def validate_file(self):
        if not MseedUtil.is_valid_mseed(self.file_selector.file_path):
            msg = "The file {} is not a valid mseed. Please, choose a valid format". \
                format(self.file_selector.file_name)
            raise InvalidFile(msg)

    def onChange_root_path(self, value):
        """
        Fired every time the root_path is changed

        :param value: The path of the new directory.

        :return:
        """
        self.file_selector.set_new_rootPath(value)

    def onChange_file(self, file_path):
        # Called every time user select a different file
        pass

    def on_click_select_directory(self, bind: BindPyqtObject):
        if "darwin" == platform:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', bind.value)
        else:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', bind.value,
                pw.QFileDialog.DontUseNativeDialog)
        if dir_path:
            bind.value = dir_path

    def on_click_select_file(self, bind: BindPyqtObject):
        selected = pw.QFileDialog.getOpenFileName(self, "Select metadata file")
        if isinstance(selected[0], str) and os.path.isfile(selected[0]):
            bind.value = selected[0]

    def onChange_metadata_path(self, value):
        md = MessageDialog(self)
        try:
            self.__metadata_manager = MetadataManager(value)
            self.inventory = self.__metadata_manager.get_inventory()
            md.set_info_message(
                "Loaded Metadata, please check your terminal for further details"
            )
        except:
            md.set_error_message(
                "Something went wrong. Please check your metada file is a correct one"
            )

    @property
    def trace(self):
        return ObspyUtil.get_tracer_from_file(self.file_selector.file_path)

    def get_data(self):
        file = self.file_selector.file_path
        starttime = convert_qdatetime_utcdatetime(self.starttime_date)
        endtime = convert_qdatetime_utcdatetime(self.endtime_date)
        diff = endtime - starttime
        parameters = self.parameters.getParameters()
        sd = SeismogramDataAdvanced(file)

        if self.trimCB.isChecked() and diff >= 0:
            tr = sd.get_waveform_advanced(
                parameters,
                self.inventory,
                filter_error_callback=self.filter_error_message,
                start_time=starttime,
                end_time=endtime)
        else:
            tr = sd.get_waveform_advanced(
                parameters,
                self.inventory,
                filter_error_callback=self.filter_error_message)

        t = tr.times()
        return tr, t

    def get_time_window(self):

        t1 = convert_qdatetime_utcdatetime(self.starttime_date)
        t2 = convert_qdatetime_utcdatetime(self.endtime_date)

        return t1, t2

    def stations_info(self):
        obsfiles = MseedUtil.get_mseed_files(self.root_path_bind.value)
        obsfiles.sort()
        sd = []
        for file in obsfiles:
            st = SeismogramDataAdvanced(file)
            station = [
                st.stats.Network, st.stats.Station, st.stats.Location,
                st.stats.Channel, st.stats.StartTime, st.stats.EndTime,
                st.stats.Sampling_rate, st.stats.Npts
            ]
            sd.append(station)
        self._stations_info = StationsInfo(sd, check=False)
        self._stations_info.show()

    def plot_seismogram(self):
        selection = self.selectCB.currentText()

        if selection == "Seismogram 1":
            #self.validate_file()
            [self.tr1, t] = self.get_data()
            self.canvas_plot1.plot(t,
                                   self.tr1.data,
                                   0,
                                   clear_plot=True,
                                   color="black",
                                   linewidth=0.5)
            self.canvas_plot1.set_xlabel(1, "Time (s)")
            self.canvas_plot1.set_ylabel(0, "Amplitude ")
            self.canvas_plot1.set_ylabel(1, "Frequency (Hz)")
            info = "{}.{}.{}".format(self.tr1.stats.network,
                                     self.tr1.stats.station,
                                     self.tr1.stats.channel)
            self.canvas_plot1.set_plot_label(0, info)

            if self.time_frequencyChB.isChecked():
                self.time_frequency(self.tr1, selection)

        if selection == "Seismogram 2":
            #self.validate_file()
            [self.tr2, t] = self.get_data()
            self.canvas_plot2.plot(t,
                                   self.tr2.data,
                                   0,
                                   clear_plot=True,
                                   color="black",
                                   linewidth=0.5)
            self.canvas_plot2.set_xlabel(1, "Time (s)")
            self.canvas_plot2.set_ylabel(0, "Amplitude ")
            self.canvas_plot2.set_ylabel(1, "Frequency (Hz)")
            info = "{}.{}.{}".format(self.tr2.stats.network,
                                     self.tr2.stats.station,
                                     self.tr2.stats.channel)
            self.canvas_plot2.set_plot_label(0, info)

            if self.time_frequencyChB.isChecked():
                self.time_frequency(self.tr2, selection)

    @AsycTime.run_async()
    def time_frequency(self, tr, order):
        selection = self.time_frequencyCB.currentText()
        ts, te = self.get_time_window()
        diff = te - ts
        if selection == "Multitaper Spectrogram":

            win = int(self.mt_window_lengthDB.value() * tr.stats.sampling_rate)
            tbp = self.time_bandwidth_DB.value()
            ntapers = self.number_tapers_mtSB.value()
            f_min = self.freq_min_mtDB.value()
            f_max = self.freq_max_mtDB.value()
            mtspectrogram = MTspectrogram(self.file_selector.file_path, win,
                                          tbp, ntapers, f_min, f_max)

            if self.trimCB.isChecked() and diff >= 0:
                x, y, log_spectrogram = mtspectrogram.compute_spectrogram(
                    tr, start_time=ts, end_time=te)
            else:
                x, y, log_spectrogram = mtspectrogram.compute_spectrogram(tr)

            log_spectrogram = np.clip(log_spectrogram,
                                      a_min=self.minlevelCB.value(),
                                      a_max=0)
            min_log_spectrogram = self.minlevelCB.value()
            max_log_spectrogram = 0

            if order == "Seismogram 1":
                if self.typeCB.currentText() == 'contourf':

                    self.canvas_plot1.plot_contour(x,
                                                   y,
                                                   log_spectrogram,
                                                   axes_index=1,
                                                   clabel="Power [dB]",
                                                   cmap=plt.get_cmap("jet"),
                                                   vmin=min_log_spectrogram,
                                                   vmax=max_log_spectrogram)
                elif self.typeCB.currentText() == 'pcolormesh':

                    print("plotting pcolormesh")
                    self.canvas_plot1.pcolormesh(x,
                                                 y,
                                                 log_spectrogram,
                                                 axes_index=1,
                                                 clabel="Power [dB]",
                                                 cmap=plt.get_cmap("jet"),
                                                 vmin=min_log_spectrogram,
                                                 vmax=max_log_spectrogram)
                self.canvas_plot1.set_xlabel(1, "Time (s)")
                self.canvas_plot1.set_ylabel(0, "Amplitude ")
                self.canvas_plot1.set_ylabel(1, "Frequency (Hz)")

            elif order == "Seismogram 2":
                if self.typeCB.currentText() == 'contourf':

                    self.canvas_plot2.plot_contour(x,
                                                   y,
                                                   log_spectrogram,
                                                   axes_index=1,
                                                   clear_plot=True,
                                                   clabel="Power [dB]",
                                                   cmap=plt.get_cmap("jet"),
                                                   vmin=min_log_spectrogram,
                                                   vmax=max_log_spectrogram)
                elif self.typeCB.currentText() == 'pcolormesh':

                    self.canvas_plot2.pcolormesh(x,
                                                 y,
                                                 log_spectrogram,
                                                 axes_index=1,
                                                 clear_plot=True,
                                                 clabel="Power [dB]",
                                                 cmap=plt.get_cmap("jet"),
                                                 vmin=min_log_spectrogram,
                                                 vmax=max_log_spectrogram)

                self.canvas_plot2.set_xlabel(1, "Time (s)")
                self.canvas_plot2.set_ylabel(0, "Amplitude ")
                self.canvas_plot2.set_ylabel(1, "Frequency (Hz)")

        elif selection == "Wigner Spectrogram":

            win = int(self.mt_window_lengthDB.value() * tr.stats.sampling_rate)
            tbp = self.time_bandwidth_DB.value()
            ntapers = self.number_tapers_mtSB.value()
            f_min = self.freq_min_mtDB.value()
            f_max = self.freq_max_mtDB.value()
            wignerspec = WignerVille(self.file_selector.file_path, win, tbp,
                                     ntapers, f_min, f_max)

            if self.trimCB.isChecked() and diff >= 0:
                x, y, log_spectrogram = wignerspec.compute_wigner_spectrogram(
                    tr, start_time=ts, end_time=te)
            else:
                x, y, log_spectrogram = wignerspec.compute_wigner_spectrogram(
                    tr)

            if order == "Seismogram 1":
                if self.typeCB.currentText() == 'contourf':
                    self.canvas_plot1.plot_contour(x,
                                                   y,
                                                   log_spectrogram,
                                                   axes_index=1,
                                                   clear_plot=True,
                                                   clabel="Rel Power ",
                                                   cmap=plt.get_cmap("jet"))
                elif self.typeCB.currentText() == 'pcolormesh':
                    self.canvas_plot1.pcolormesh(x,
                                                 y,
                                                 log_spectrogram,
                                                 axes_index=1,
                                                 clear_plot=True,
                                                 clabel="Rel Power ",
                                                 cmap=plt.get_cmap("jet"))
                self.canvas_plot1.set_xlabel(1, "Time (s)")
                self.canvas_plot1.set_ylabel(0, "Amplitude ")
                self.canvas_plot1.set_ylabel(1, "Frequency (Hz)")

            elif order == "Seismogram 2":
                if self.typeCB.currentText() == 'contourf':
                    self.canvas_plot2.plot_contour(x,
                                                   y,
                                                   log_spectrogram,
                                                   axes_index=1,
                                                   clear_plot=True,
                                                   clabel="Power [dB]",
                                                   cmap=plt.get_cmap("jet"))
                elif self.typeCB.currentText() == 'pcolormesh':
                    self.canvas_plot2.pcolormesh(x,
                                                 y,
                                                 log_spectrogram,
                                                 axes_index=1,
                                                 clear_plot=True,
                                                 clabel="Power [dB]",
                                                 cmap=plt.get_cmap("jet"))
                self.canvas_plot2.set_xlabel(1, "Time (s)")
                self.canvas_plot2.set_ylabel(0, "Amplitude ")
                self.canvas_plot2.set_ylabel(1, "Frequency (Hz)")

        elif selection == "Continuous Wavelet Transform":

            fs = tr.stats.sampling_rate
            nf = self.atomsSB.value()
            f_min = self.freq_min_cwtDB.value()
            f_max = self.freq_max_cwtDB.value()
            wmin = self.wminSB.value()
            wmax = self.wminSB.value()
            #tt = int( self.wavelet_lenghtDB.value()*fs)
            npts = len(tr.data)
            t = np.linspace(0, tr.stats.delta * npts, npts)
            #cw = ConvolveWaveletScipy(self.file_selector.file_path)
            cw = ConvolveWaveletScipy(tr)
            wavelet = self.wavelet_typeCB.currentText()

            m = self.wavelets_param.value()
            if self.trimCB.isChecked() and diff >= 0:

                cw.setup_wavelet(ts,
                                 te,
                                 wmin=wmin,
                                 wmax=wmax,
                                 tt=int(fs / f_min),
                                 fmin=f_min,
                                 fmax=f_max,
                                 nf=nf,
                                 use_wavelet=wavelet,
                                 m=m,
                                 decimate=False)
            else:
                cw.setup_wavelet(wmin=wmin,
                                 wmax=wmax,
                                 tt=int(fs / f_min),
                                 fmin=f_min,
                                 fmax=f_max,
                                 nf=nf,
                                 use_wavelet=wavelet,
                                 m=m,
                                 decimate=False)

            scalogram2 = cw.scalogram_in_dbs()
            scalogram2 = np.clip(scalogram2,
                                 a_min=self.minlevelCB.value(),
                                 a_max=0)
            cf = cw.cf_lowpass()
            freq = np.logspace(np.log10(f_min), np.log10(f_max))
            k = wmin / (2 * np.pi * freq)
            delay = int(fs * np.mean(k))
            x, y = np.meshgrid(
                t,
                np.logspace(np.log10(f_min), np.log10(f_max),
                            scalogram2.shape[0]))
            c_f = wmin / 2 * math.pi
            f = np.linspace((f_min), (f_max), scalogram2.shape[0])
            pred = (math.sqrt(2) * c_f / f) - (math.sqrt(2) * c_f / f_max)

            pred_comp = t[len(t) - 1] - pred
            min_cwt = self.minlevelCB.value()
            max_cwt = 0

            norm = Normalize(vmin=min_cwt, vmax=max_cwt)

            tf = t[delay:len(t)]
            cf = cf[0:len(tf)]
            if order == "Seismogram 1":

                #self.canvas_plot1.plot(tf, cf, 0, clear_plot=True, is_twinx=True, color="red",
                #                       linewidth=0.5)
                if self.typeCB.currentText() == 'pcolormesh':
                    self.canvas_plot1.pcolormesh(x,
                                                 y,
                                                 scalogram2,
                                                 axes_index=1,
                                                 clear_plot=True,
                                                 clabel="Power [dB]",
                                                 cmap=plt.get_cmap("jet"),
                                                 vmin=min_cwt,
                                                 vmax=max_cwt)
                elif self.typeCB.currentText() == 'contourf':
                    self.canvas_plot1.plot_contour(x,
                                                   y,
                                                   scalogram2,
                                                   axes_index=1,
                                                   clear_plot=True,
                                                   clabel="Power [dB]",
                                                   cmap=plt.get_cmap("jet"),
                                                   vmin=min_cwt,
                                                   vmax=max_cwt)

                ax_cone = self.canvas_plot1.get_axe(1)
                ax_cone.fill_between(pred,
                                     f,
                                     0,
                                     color="black",
                                     edgecolor="red",
                                     alpha=0.3)
                ax_cone.fill_between(pred_comp,
                                     f,
                                     0,
                                     color="black",
                                     edgecolor="red",
                                     alpha=0.3)
                self.canvas_plot1.set_xlabel(1, "Time (s)")
                self.canvas_plot1.set_ylabel(0, "Amplitude ")
                self.canvas_plot1.set_ylabel(1, "Frequency (Hz)")

            if order == "Seismogram 2":

                #self.canvas_plot2.plot(tf, cf, 0, clear_plot=True, is_twinx=True, color="red",
                #                       linewidth=0.5)

                if self.typeCB.currentText() == 'pcolormesh':
                    self.canvas_plot2.pcolormesh(x,
                                                 y,
                                                 scalogram2,
                                                 axes_index=1,
                                                 clear_plot=True,
                                                 clabel="Power [dB]",
                                                 cmap=plt.get_cmap("jet"),
                                                 vmin=min_cwt,
                                                 vmax=max_cwt)
                elif self.typeCB.currentText() == 'contourf':
                    self.canvas_plot2.plot_contour(x,
                                                   y,
                                                   scalogram2,
                                                   axes_index=1,
                                                   clear_plot=True,
                                                   clabel="Power [dB]",
                                                   cmap=plt.get_cmap("jet"),
                                                   vmin=min_cwt,
                                                   vmax=max_cwt)

                ax_cone2 = self.canvas_plot2.get_axe(1)
                ax_cone2.fill_between(pred,
                                      f,
                                      0,
                                      color="black",
                                      edgecolor="red",
                                      alpha=0.3)
                ax_cone2.fill_between(pred_comp,
                                      f,
                                      0,
                                      color="black",
                                      edgecolor="red",
                                      alpha=0.3)
                self.canvas_plot2.set_xlabel(1, "Time (s)")
                self.canvas_plot2.set_ylabel(0, "Amplitude ")
                self.canvas_plot2.set_ylabel(1, "Frequency (Hz)")

        else:
            pass

    def key_pressed(self, event):
        selection = self.selectCB.currentText()

        if event.key == 'w':
            self.plot_seismogram()

        if event.key == 'q':
            if selection == "Seismogram 1":
                [tr, t] = self.get_data()
                x1, y1 = event.xdata, event.ydata
                tt = tr.stats.starttime + x1
                set_qdatetime(tt, self.starttime_date)
                self.canvas_plot1.draw_arrow(x1,
                                             0,
                                             arrow_label="st",
                                             color="purple",
                                             linestyles='--',
                                             picker=False)
            elif selection == "Seismogram 2":
                [tr, t] = self.get_data()
                x1, y1 = event.xdata, event.ydata
                tt = tr.stats.starttime + x1
                set_qdatetime(tt, self.starttime_date)
                self.canvas_plot2.draw_arrow(x1,
                                             0,
                                             arrow_label="st",
                                             color="purple",
                                             linestyles='--',
                                             picker=False)

        if event.key == 'e':

            if selection == "Seismogram 1":
                [tr, t] = self.get_data()
                x1, y1 = event.xdata, event.ydata
                tt = tr.stats.starttime + x1
                set_qdatetime(tt, self.endtime_date)
                self.canvas_plot1.draw_arrow(x1,
                                             0,
                                             arrow_label="et",
                                             color="purple",
                                             linestyles='--',
                                             picker=False)
            elif selection == "Seismogram 2":
                [tr, t] = self.get_data()
                x1, y1 = event.xdata, event.ydata
                tt = tr.stats.starttime + x1
                set_qdatetime(tt, self.endtime_date)
                self.canvas_plot2.draw_arrow(x1,
                                             0,
                                             arrow_label="et",
                                             color="purple",
                                             linestyles='--',
                                             picker=False)

    def open_help(self):
        self.help.show()
Exemplo n.º 7
0
    def __init__(self):
        super(RealTimeFrame, self).__init__()
        self.setupUi(self)
        self.setWindowIcon(pqg.QIcon(':\\icons\\map-icon.png'))
        self.widget_map = None
        self.settings_dialog = SettingsDialog(self)
        self.inventory = {}
        self.files = []
        self.events_times = []
        self.total_items = 0
        self.items_per_page = 1
        self.__dataless_manager = None
        self.__metadata_manager = None
        self.st = None
        self.client = None
        self.stations_available = []
        self.data_dict = {}
        self.dataless_not_found = set(
        )  # a set of mseed files that the dataless couldn't find.
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        self.canvas = MatplotlibCanvas(self.plotMatWidget,
                                       nrows=self.numTracesCB.value(),
                                       constrained_layout=False)
        self.canvas.figure.tight_layout()
        self.timer_outdated = pyc.QTimer()
        self.timer_outdated.setInterval(1000)  # 1 second
        self.timer_outdated.timeout.connect(self.outdated_stations)

        # Binding
        self.root_path_bind = BindPyqtObject(self.rootPathForm)
        self.dataless_path_bind = BindPyqtObject(self.datalessPathForm)

        # Bind

        self.selectDirBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.root_path_bind))

        #self.selectDatalessDirBtn.clicked.connect(lambda: self.on_click_select_directory(self.dataless_path_bind))

        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        self.selectDatalessDirBtn.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.metadata_path_bind
                                                       ))

        self.actionSet_Parameters.triggered.connect(
            lambda: self.open_parameters_settings())
        self.mapBtn.clicked.connect(self.show_map)
        # self.__metadata_manager = MetadataManager(self.dataless_path_bind.value)
        self.actionSet_Parameters.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionArray_Anlysis.triggered.connect(self.open_array_analysis)
        self.actionMoment_Tensor_Inversion.triggered.connect(
            self.open_moment_tensor)
        self.actionTime_Frequency_Analysis.triggered.connect(
            self.time_frequency_analysis)
        self.actionReceiver_Functions.triggered.connect(
            self.open_receiver_functions)
        self.actionOpen_Settings.triggered.connect(
            lambda: self.settings_dialog.show())
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.RetrieveBtn.clicked.connect(self.retrieve_data)
        self.stopBtn.clicked.connect(self.stop)
        # Parameters settings
        self.parameters = ParametersSettings()
        # Earth Model Viewer
        self.earthmodel = EarthModelViewer()
        # help Documentation
        self.help = HelpDoc()
Exemplo n.º 8
0
    def __init__(self):
        super(ArrayAnalysisFrame, self).__init__()
        self.setupUi(self)
        self.__stations_dir = None
        self.stream_frame = None
        self.__metadata_manager = None
        self.inventory = {}
        self._stations_info = {}
        self._stations_coords = {}
        self.stack = None
        self.canvas = MatplotlibCanvas(self.responseMatWidget)
        self.canvas_fk = MatplotlibCanvas(self.widget_fk, nrows=4)
        self.canvas_slow_map = MatplotlibCanvas(self.widget_slow_map)
        self.canvas_fk.on_double_click(self.on_click_matplotlib)
        self.canvas_stack = MatplotlibCanvas(self.widget_stack)
        self.cartopy_canvas = CartopyCanvas(self.widget_map)
        self.canvas.set_new_subplot(1, ncols=1)

        #Binding
        self.root_pathFK_bind = BindPyqtObject(self.rootPathFormFK)
        self.root_pathBP_bind = BindPyqtObject(self.rootPathFormBP)
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        self.metadata_path_bindBP = BindPyqtObject(self.datalessPathFormBP,
                                                   self.onChange_metadata_path)
        self.output_path_bindBP = BindPyqtObject(self.outputPathFormBP,
                                                 self.onChange_metadata_path)
        self.fmin_bind = BindPyqtObject(self.fminSB)
        self.fmax_bind = BindPyqtObject(self.fmaxSB)
        self.grid_bind = BindPyqtObject(self.gridSB)
        self.smax_bind = BindPyqtObject(self.smaxSB)

        # On select
        self.canvas_fk.register_on_select(self.on_select,
                                          rectprops=dict(alpha=0.2,
                                                         facecolor='red'))
        self.fminFK_bind = BindPyqtObject(self.fminFKSB)
        self.fmaxFK_bind = BindPyqtObject(self.fmaxFKSB)
        self.overlap_bind = BindPyqtObject(self.overlapSB)
        self.timewindow_bind = BindPyqtObject(self.timewindowSB)
        self.smaxFK_bind = BindPyqtObject(self.slowFKSB)
        self.slow_grid_bind = BindPyqtObject(self.gridFKSB)

        # Bind buttons
        self.selectDirBtnFK.clicked.connect(
            lambda: self.on_click_select_directory(self.root_pathFK_bind))
        self.datalessBtn.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.metadata_path_bind
                                                       ))

        # Bind buttons BackProjection
        self.selectDirBtnBP.clicked.connect(
            lambda: self.on_click_select_directory(self.root_pathBP_bind))
        self.datalessBtnBP.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.
                                                       metadata_path_bindBP))
        self.outputBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.output_path_bindBP))

        #Action Buttons
        self.arfBtn.clicked.connect(lambda: self.arf())
        self.runFKBtn.clicked.connect(lambda: self.FK_plot())
        self.plotBtn.clicked.connect(lambda: self.plot_seismograms())
        self.plotBtnBP.clicked.connect(lambda: self.plot_seismograms(FK=False))
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionProcessed_Seimograms.triggered.connect(self.write)
        self.actionStacked_Seismograms.triggered.connect(self.write_stack)
        self.stationsBtn.clicked.connect(lambda: self.stationsInfo())
        self.stationsBtnBP.clicked.connect(lambda: self.stationsInfo(FK=False))
        self.mapBtn.clicked.connect(self.stations_map)
        self.actionCreate_Stations_File.triggered.connect(
            self.stations_coordinates)
        self.actionLoad_Stations_File.triggered.connect(self.load_path)
        self.actionRunVespagram.triggered.connect(self.open_vespagram)
        self.shortcut_open = pw.QShortcut(pqg.QKeySequence('Ctrl+O'), self)
        self.shortcut_open.activated.connect(self.open_solutions)
        self.create_gridBtn.clicked.connect(self.create_grid)
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.load_videoBtn.clicked.connect(self.loadvideoBP)

        # help Documentation
        self.help = HelpDoc()

        # Parameters settings
        self.__parameters = ParametersSettings()

        # Stations Coordinates
        self.__stations_coords = StationsCoords()

        # picks
        self.picks = {
            'Time': [],
            'Phase': [],
            'BackAzimuth': [],
            'Slowness': [],
            'Power': []
        }

        # video
        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.player.setVideoOutput(self.backprojection_widget)
        self.player.stateChanged.connect(self.mediaStateChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.durationChanged.connect(self.durationChanged)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play_bp)
        self.positionSlider.sliderMoved.connect(self.setPosition)
Exemplo n.º 9
0
class ArrayAnalysisFrame(BaseFrame, UiArrayAnalysisFrame):
    def __init__(self):
        super(ArrayAnalysisFrame, self).__init__()
        self.setupUi(self)
        self.__stations_dir = None
        self.stream_frame = None
        self.__metadata_manager = None
        self.inventory = {}
        self._stations_info = {}
        self._stations_coords = {}
        self.stack = None
        self.canvas = MatplotlibCanvas(self.responseMatWidget)
        self.canvas_fk = MatplotlibCanvas(self.widget_fk, nrows=4)
        self.canvas_slow_map = MatplotlibCanvas(self.widget_slow_map)
        self.canvas_fk.on_double_click(self.on_click_matplotlib)
        self.canvas_stack = MatplotlibCanvas(self.widget_stack)
        self.cartopy_canvas = CartopyCanvas(self.widget_map)
        self.canvas.set_new_subplot(1, ncols=1)

        #Binding
        self.root_pathFK_bind = BindPyqtObject(self.rootPathFormFK)
        self.root_pathBP_bind = BindPyqtObject(self.rootPathFormBP)
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        self.metadata_path_bindBP = BindPyqtObject(self.datalessPathFormBP,
                                                   self.onChange_metadata_path)
        self.output_path_bindBP = BindPyqtObject(self.outputPathFormBP,
                                                 self.onChange_metadata_path)
        self.fmin_bind = BindPyqtObject(self.fminSB)
        self.fmax_bind = BindPyqtObject(self.fmaxSB)
        self.grid_bind = BindPyqtObject(self.gridSB)
        self.smax_bind = BindPyqtObject(self.smaxSB)

        # On select
        self.canvas_fk.register_on_select(self.on_select,
                                          rectprops=dict(alpha=0.2,
                                                         facecolor='red'))
        self.fminFK_bind = BindPyqtObject(self.fminFKSB)
        self.fmaxFK_bind = BindPyqtObject(self.fmaxFKSB)
        self.overlap_bind = BindPyqtObject(self.overlapSB)
        self.timewindow_bind = BindPyqtObject(self.timewindowSB)
        self.smaxFK_bind = BindPyqtObject(self.slowFKSB)
        self.slow_grid_bind = BindPyqtObject(self.gridFKSB)

        # Bind buttons
        self.selectDirBtnFK.clicked.connect(
            lambda: self.on_click_select_directory(self.root_pathFK_bind))
        self.datalessBtn.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.metadata_path_bind
                                                       ))

        # Bind buttons BackProjection
        self.selectDirBtnBP.clicked.connect(
            lambda: self.on_click_select_directory(self.root_pathBP_bind))
        self.datalessBtnBP.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.
                                                       metadata_path_bindBP))
        self.outputBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.output_path_bindBP))

        #Action Buttons
        self.arfBtn.clicked.connect(lambda: self.arf())
        self.runFKBtn.clicked.connect(lambda: self.FK_plot())
        self.plotBtn.clicked.connect(lambda: self.plot_seismograms())
        self.plotBtnBP.clicked.connect(lambda: self.plot_seismograms(FK=False))
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionProcessed_Seimograms.triggered.connect(self.write)
        self.actionStacked_Seismograms.triggered.connect(self.write_stack)
        self.stationsBtn.clicked.connect(lambda: self.stationsInfo())
        self.stationsBtnBP.clicked.connect(lambda: self.stationsInfo(FK=False))
        self.mapBtn.clicked.connect(self.stations_map)
        self.actionCreate_Stations_File.triggered.connect(
            self.stations_coordinates)
        self.actionLoad_Stations_File.triggered.connect(self.load_path)
        self.actionRunVespagram.triggered.connect(self.open_vespagram)
        self.shortcut_open = pw.QShortcut(pqg.QKeySequence('Ctrl+O'), self)
        self.shortcut_open.activated.connect(self.open_solutions)
        self.create_gridBtn.clicked.connect(self.create_grid)
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.load_videoBtn.clicked.connect(self.loadvideoBP)

        # help Documentation
        self.help = HelpDoc()

        # Parameters settings
        self.__parameters = ParametersSettings()

        # Stations Coordinates
        self.__stations_coords = StationsCoords()

        # picks
        self.picks = {
            'Time': [],
            'Phase': [],
            'BackAzimuth': [],
            'Slowness': [],
            'Power': []
        }

        # video
        self.player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
        self.player.setVideoOutput(self.backprojection_widget)
        self.player.stateChanged.connect(self.mediaStateChanged)
        self.player.positionChanged.connect(self.positionChanged)
        self.player.durationChanged.connect(self.durationChanged)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playButton.clicked.connect(self.play_bp)
        self.positionSlider.sliderMoved.connect(self.setPosition)

    def mediaStateChanged(self):
        if self.player.state() == QMediaPlayer.PlayingState:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPause))
        else:
            self.playButton.setIcon(self.style().standardIcon(
                QStyle.SP_MediaPlay))

    def positionChanged(self, position):
        self.positionSlider.setValue(position)

    def durationChanged(self, duration):
        self.positionSlider.setRange(0, duration)

    def setPosition(self, position):
        self.player.setPosition(position)

    def open_parameters_settings(self):
        self.__parameters.show()

    def stations_coordinates(self):
        self.__stations_coords.show()

    def open_vespagram(self):
        if self.st and self.inventory and self.t1 and self.t2:
            self.__vespagram = Vespagram(self.st, self.inventory, self.t1,
                                         self.t2)
            self.__vespagram.show()

    def on_click_select_directory(self, bind: BindPyqtObject):
        if "darwin" == platform:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', bind.value)
        else:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', bind.value,
                pw.QFileDialog.DontUseNativeDialog)
        if dir_path:
            bind.value = dir_path

    def onChange_metadata_path(self, value):

        md = MessageDialog(self)
        try:

            self.__metadata_manager = MetadataManager(value)
            self.inventory = self.__metadata_manager.get_inventory()
            print(self.inventory)
            md.set_info_message(
                "Loaded Metadata, please check your terminal for further details"
            )

        except:

            md.set_error_message(
                "Something went wrong. Please check your metada file is a correct one"
            )

    def on_click_select_metadata_file(self, bind: BindPyqtObject):
        selected = pw.QFileDialog.getOpenFileName(self, "Select metadata file")
        if isinstance(selected[0], str) and os.path.isfile(selected[0]):
            bind.value = selected[0]

    def load_path(self):
        selected_file = pw.QFileDialog.getOpenFileName(
            self, "Select Stations Coordinates file")
        self.path_file = selected_file[0]
        df = pd.read_csv(self.path_file, delim_whitespace=True)
        n = len(df)
        self.coords = np.zeros([n, 3])
        for i in range(n):
            #coords[i]=data[i]
            self.coords[i] = np.array(
                [df['Lon'][i], df['Lat'][i], df['Depth'][i]])

    def arf(self):
        try:
            if self.coords.all():

                wavenumber = array_analysis.array()
                arf = wavenumber.arf(self.coords, self.fmin_bind.value,
                                     self.fmax_bind.value,
                                     self.smax_bind.value,
                                     self.grid_bind.value)

                slim = self.smax_bind.value
                x = y = np.linspace(-1 * slim, slim, len(arf))
                self.canvas.plot_contour(x,
                                         y,
                                         arf,
                                         axes_index=0,
                                         clabel="Power [dB]",
                                         cmap=plt.get_cmap("jet"))
                self.canvas.set_xlabel(0, "Sx (s/km)")
                self.canvas.set_ylabel(0, "Sy (s/km)")
        except:
            md = MessageDialog(self)
            md.set_error_message(
                "Couldn't compute ARF, please check if you have loaded stations coords"
            )

    def stations_map(self):
        coords = {}

        if self.path_file:
            df = pd.read_csv(self.path_file, delim_whitespace=True)
            n = len(df)
            self.coords = np.zeros([n, 3])
            for i in range(n):
                coords[df['Name'][i]] = [
                    df['Lat'][i],
                    df['Lon'][i],
                ]
        #try:
            self.cartopy_canvas.plot_map(df['Lat'][0],
                                         df['Lon'][0],
                                         0,
                                         0,
                                         0,
                                         0,
                                         resolution="low",
                                         stations=coords)
        #except:
        #    pass

    def FK_plot(self):
        self.canvas_stack.set_new_subplot(nrows=1, ncols=1)
        starttime = convert_qdatetime_utcdatetime(self.starttime_date)
        endtime = convert_qdatetime_utcdatetime(self.endtime_date)
        selection = self.inventory.select(station=self.stationLE.text(),
                                          channel=self.channelLE.text())
        if self.trimCB.isChecked():
            wavenumber = array_analysis.array()
            relpower, abspower, AZ, Slowness, T = wavenumber.FK(
                self.st, selection, starttime, endtime, self.fminFK_bind.value,
                self.fmaxFK_bind.value, self.smaxFK_bind.value,
                self.slow_grid_bind.value, self.timewindow_bind.value,
                self.overlap_bind.value)
            self.canvas_fk.scatter3d(T,
                                     relpower,
                                     relpower,
                                     axes_index=0,
                                     clabel="Power [dB]")
            self.canvas_fk.scatter3d(T,
                                     abspower,
                                     relpower,
                                     axes_index=1,
                                     clabel="Power [dB]")
            self.canvas_fk.scatter3d(T,
                                     AZ,
                                     relpower,
                                     axes_index=2,
                                     clabel="Power [dB]")
            self.canvas_fk.scatter3d(T,
                                     Slowness,
                                     relpower,
                                     axes_index=3,
                                     clabel="Power [dB]")
            self.canvas_fk.set_ylabel(0, " Rel Power ")
            self.canvas_fk.set_ylabel(1, " Absolute Power ")
            self.canvas_fk.set_ylabel(2, " Back Azimuth ")
            self.canvas_fk.set_ylabel(3, " Slowness [s/km] ")
            self.canvas_fk.set_xlabel(3, " Time [s] ")
            ax = self.canvas_fk.get_axe(3)
            formatter = mdt.DateFormatter('%H:%M:%S')
            ax.xaxis.set_major_formatter(formatter)
            ax.xaxis.set_tick_params(rotation=30)
        else:
            md = MessageDialog(self)
            md.set_info_message("Please select dates and then check Trim box")

    def on_click_matplotlib(self, event, canvas):
        output_path = os.path.join(ROOT_DIR, 'arrayanalysis', 'dataframe.csv')

        if isinstance(canvas, MatplotlibCanvas):
            st = self.st.copy()
            wavenumber = array_analysis.array()
            selection = self.inventory.select(station=self.stationLE.text(),
                                              channel=self.channelLE.text())
            x1, y1 = event.xdata, event.ydata
            DT = x1
            Z, Sxpow, Sypow, coord = wavenumber.FKCoherence(
                st, selection, DT, self.fminFK_bind.value,
                self.fmaxFK_bind.value, self.smaxFK_bind.value,
                self.timewindow_bind.value, self.slow_grid_bind.value,
                self.methodSB.currentText())

            backacimuth = wavenumber.azimuth2mathangle(
                np.arctan2(Sypow, Sxpow) * 180 / np.pi)
            slowness = np.abs(Sxpow, Sypow)
            if self.methodSB.currentText() == "FK":
                clabel = "Power"
            elif self.methodSB.currentText() == "MTP.COHERENCE":
                clabel = "Magnitude Coherence"

            Sx = np.arange(-1 * self.smaxFK_bind.value, self.smaxFK_bind.value,
                           self.slow_grid_bind.value)[np.newaxis]
            nx = len(Sx[0])
            x = y = np.linspace(-1 * self.smaxFK_bind.value,
                                self.smaxFK_bind.value, nx)
            X, Y = np.meshgrid(x, y)
            self.canvas_slow_map.plot_contour(X,
                                              Y,
                                              Z,
                                              axes_index=0,
                                              clabel=clabel,
                                              cmap=plt.get_cmap("jet"))
            self.canvas_slow_map.set_xlabel(0, "Sx [s/km]")
            self.canvas_slow_map.set_ylabel(0, "Sy [s/km]")

            # Save in a dataframe the pick value
            x1 = wavenumber.gregorian2date(x1)

            self.picks['Time'].append(x1.isoformat())
            self.picks['Phase'].append(self.phaseCB.currentText())
            self.picks['BackAzimuth'].append(backacimuth[0])
            self.picks['Slowness'].append(slowness[0])
            self.picks['Power'].append(np.max(Z))
            df = pd.DataFrame(self.picks)
            df.to_csv(output_path, index=False, header=True)

            # Call Stack and Plot###
            #stream_stack, time = wavenumber.stack_stream(self.root_pathFK_bind.value, Sxpow, Sypow, coord)

            if st:
                st2 = self.st.copy()
                # Align for the maximum power and give the data of the traces
                stream_stack, self.time, self.stats = wavenumber.stack_stream(
                    st2, Sxpow, Sypow, coord)
                # stack the traces
                self.stack = wavenumber.stack(
                    stream_stack, stack_type=self.stackCB.currentText())
                self.canvas_stack.plot(self.time,
                                       self.stack,
                                       axes_index=0,
                                       linewidth=0.75)
                self.canvas_stack.set_xlabel(0, " Time [s] ")
                self.canvas_stack.set_ylabel(0, "Stack Amplitude")

    def filter_error_message(self, msg):
        md = MessageDialog(self)
        md.set_info_message(msg)

    def plot_seismograms(self, FK=True):

        if FK:
            starttime = convert_qdatetime_utcdatetime(self.starttime_date)
            endtime = convert_qdatetime_utcdatetime(self.endtime_date)
        else:
            starttime = convert_qdatetime_utcdatetime(self.starttime_date_BP)
            endtime = convert_qdatetime_utcdatetime(self.endtime_date_BP)

        diff = endtime - starttime

        if FK:
            file_path = self.root_pathFK_bind.value
        else:
            file_path = self.root_pathBP_bind.value

        obsfiles = []

        for dirpath, _, filenames in os.walk(file_path):
            for f in filenames:
                if f != ".DS_Store":
                    obsfiles.append(os.path.abspath(os.path.join(dirpath, f)))

        obsfiles.sort()
        parameters = self.__parameters.getParameters()
        all_traces = []
        trace_number = 0

        for file in obsfiles:
            sd = SeismogramDataAdvanced(file)

            if FK:
                if self.trimCB.isChecked() and diff >= 0:
                    tr = sd.get_waveform_advanced(
                        parameters,
                        self.inventory,
                        filter_error_callback=self.filter_error_message,
                        start_time=starttime,
                        end_time=endtime,
                        trace_number=trace_number)
                else:
                    tr = sd.get_waveform_advanced(
                        parameters,
                        self.inventory,
                        filter_error_callback=self.filter_error_message,
                        trace_number=trace_number)
            else:
                if self.trimCB_BP.isChecked() and diff >= 0:
                    tr = sd.get_waveform_advanced(
                        parameters,
                        self.inventory,
                        filter_error_callback=self.filter_error_message,
                        start_time=starttime,
                        end_time=endtime,
                        trace_number=trace_number)
                else:
                    tr = sd.get_waveform_advanced(
                        parameters,
                        self.inventory,
                        filter_error_callback=self.filter_error_message,
                        trace_number=trace_number)

            all_traces.append(tr)
            trace_number = trace_number + 1

        self.st = Stream(traces=all_traces)

        if FK:
            if self.selectCB.isChecked():
                self.st = self.st.select(station=self.stationLE.text(),
                                         channel=self.channelLE.text())

        else:
            if self.selectCB_BP.isChecked():
                self.st = self.st.select(network=self.stationLE_BP.text(),
                                         station=self.stationLE_BP.text(),
                                         channel=self.channelLE_BP.text())

        self.stream_frame = MatplotlibFrame(self.st, type='normal')
        self.stream_frame.show()

    def stationsInfo(self, FK=True):
        if FK:
            obsfiles = MseedUtil.get_mseed_files(self.root_pathFK_bind.value)
        else:
            obsfiles = MseedUtil.get_mseed_files(self.root_pathBP_bind.value)
        obsfiles.sort()
        sd = []
        for file in obsfiles:
            st = SeismogramDataAdvanced(file)
            station = [
                st.stats.Network, st.stats.Station, st.stats.Location,
                st.stats.Channel, st.stats.StartTime, st.stats.EndTime,
                st.stats.Sampling_rate, st.stats.Npts
            ]
            sd.append(station)
        self._stations_info = StationsInfo(sd, check=True)
        self._stations_info.show()

    def write(self):
        root_path = os.path.dirname(os.path.abspath(__file__))
        if "darwin" == platform:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', root_path)
        else:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', root_path,
                pw.QFileDialog.DontUseNativeDialog)
        if dir_path:
            n = len(self.st)
            try:
                if len(n) > 0:
                    for j in range(n):
                        tr = self.st[j]
                        t1 = tr.stats.starttime
                        id = tr.id + "." + "D" + "." + str(
                            t1.year) + "." + str(t1.julday)
                        print(tr.id, "Writing data processed")
                        path_output = os.path.join(dir_path, id)
                        tr.write(path_output, format="MSEED")
                else:
                    md = MessageDialog(self)
                    md.set_info_message("Nothing to write")
            except:
                pass

    def write_stack(self):
        if self.stack is not None and len(self.stack) > 0:
            root_path = os.path.dirname(os.path.abspath(__file__))
            if "darwin" == platform:
                dir_path = pw.QFileDialog.getExistingDirectory(
                    self, 'Select Directory', root_path)
            else:
                dir_path = pw.QFileDialog.getExistingDirectory(
                    self, 'Select Directory', root_path,
                    pw.QFileDialog.DontUseNativeDialog)
            if dir_path:
                tr = Trace(data=self.stack, header=self.stats)
                file = os.path.join(dir_path, tr.id)
                tr.write(file, format="MSEED")
        else:
            md = MessageDialog(self)
            md.set_info_message("Nothing to write")

    def __to_UTC(self, DT):

        # Convert start from Greogorian to actual date
        Time = DT
        Time = Time - int(Time)
        d = date.fromordinal(int(DT))
        date1 = d.isoformat()
        H = (Time * 24)
        H1 = int(H)  # Horas
        minutes = (H - int(H)) * 60
        minutes1 = int(minutes)
        seconds = (minutes - int(minutes)) * 60
        H1 = str(H1).zfill(2)
        minutes1 = str(minutes1).zfill(2)
        seconds = "%.2f" % seconds
        seconds = str(seconds).zfill(2)
        DATE = date1 + "T" + str(H1) + minutes1 + seconds

        t1 = UTCDateTime(DATE)
        return t1

    def on_select(self, ax_index, xmin, xmax):
        self.t1 = self.__to_UTC(xmin)
        self.t2 = self.__to_UTC(xmax)

    def open_solutions(self):
        output_path = os.path.join(ROOT_DIR, 'arrayanalysis', 'dataframe.csv')
        try:
            command = "{} {}".format('open', output_path)
            exc_cmd(command, cwd=ROOT_DIR)
        except:
            md = MessageDialog(self)
            md.set_error_message("Coundn't open solutions file")

    ### New part back-projection

    def create_grid(self):
        area_coords = [
            self.minLonBP, self.maxLonBP, self.minLatBP, self.maxLatBP
        ]
        bp = back_proj_organize(self, self.rootPathFormBP,
                                self.datalessPathFormBP, area_coords,
                                self.sxSB.value, self.sxSB.value,
                                self.depthSB.value)

        mapping = bp.create_dict()

        try:
            self.path_file = os.path.join(self.output_path_bindBP.value,
                                          "mapping.pkl")
            file_to_store = open(self.path_file, "wb")
            pickle.dump(mapping, file_to_store)
            md = MessageDialog(self)
            md.set_info_message("BackProjection grid created succesfully!!!")

        except:
            md = MessageDialog(self)
            md.set_error_message("Coundn't create a BackProjection grid")

    def run_bp(self):

        try:
            if os.path.exists(self.path_file):
                with open(self.path_file, 'rb') as handle:
                    mapping = pickle.load(handle)
        except:
            md = MessageDialog(self)
            md.set_error_message(
                "Please you need try to previously create a BackProjection grid"
            )

        power = backproj.run_back(self.st,
                                  mapping,
                                  self.time_winBP.value,
                                  self.stepBP.value,
                                  window=self.slide_winBP.value,
                                  multichannel=self.mcccCB.isChecked(),
                                  stack_process=self.methodBP.currentText())

        #plot_cum(power, mapping['area_coords'], self.cum_sumBP.value, self.st)
        plot_bp(power,
                mapping['area_coords'],
                self.cum_sumBP.value,
                self.st,
                output=self.output_path_bindBP.value)

        fname = os.path.join(self.output_path_bindBP.value, "power.pkl")

        file_to_store = open(fname, "wb")
        pickle.dump(power, file_to_store)

    def loadvideoBP(self):
        self.path_video, _ = pw.QFileDialog.getOpenFileName(
            self, "Choose your BackProjection", ".",
            "Video Files (*.mp4 *.flv *.ts *.mts *.avi)")
        if self.path_video != '':

            self.player.setVideoOutput(self.backprojection_widget)
            self.player.setMedia(
                QMediaContent(pyc.QUrl.fromLocalFile(self.path_video)))
            md = MessageDialog(self)
            md.set_info_message(
                "Video containing BackProjection succesfully loaded")
        else:
            md = MessageDialog(self)
            md.set_error_message(
                "Video containing BackProjection couldn't be loaded")

    def play_bp(self):

        if self.player.state() == QMediaPlayer.PlayingState:
            self.player.pause()
        else:
            self.player.play()

    def open_help(self):
        self.help.show()
Exemplo n.º 10
0
class MTIFrame(BaseFrame, UiMomentTensor):
    def __init__(self):
        super(MTIFrame, self).__init__()
        self.setupUi(self)

        #super(MTIFrame, self).__init__()
        self.setupUi(self)
        self.__stations_dir = None
        self.__metadata_manager = None
        self.inventory = {}
        self._stations_info = {}
        self.stream = None
        # Binding
        self.root_path_bind = BindPyqtObject(self.rootPathForm)
        #self.dataless_path_bind = BindPyqtObject(self.datalessPathForm)
        self.metadata_path_bind = BindPyqtObject(self.datalessPathForm,
                                                 self.onChange_metadata_path)
        self.earth_path_bind = BindPyqtObject(self.earth_modelPathForm)

        # Binds
        self.selectDirBtn.clicked.connect(
            lambda: self.on_click_select_directory(self.root_path_bind))
        self.datalessBtn.clicked.connect(
            lambda: self.on_click_select_metadata_file(self.metadata_path_bind
                                                       ))
        self.earthmodelBtn.clicked.connect(
            lambda: self.on_click_select_file(self.earth_path_bind))

        # Action Buttons
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.plotBtn.clicked.connect(self.plot_seismograms)
        self.actionSettings.triggered.connect(
            lambda: self.open_parameters_settings())
        self.actionWrite.triggered.connect(self.write)
        self.actionEarth_Model.triggered.connect(
            lambda: self.open_earth_model())
        self.actionFrom_File.triggered.connect(
            lambda: self.load_event_from_isolapath())
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        self.stationsBtn.clicked.connect(self.stationsInfo)
        self.run_inversionBtn.clicked.connect(lambda: self.run_inversion())
        self.stations_mapBtn.clicked.connect(lambda: self.plot_map_stations())
        self.plot_solutionBtn.clicked.connect(lambda: self.plot_solution())
        #self.earthmodelBtn.clicked.connect(self.read_earth_model)
        # Parameters settings
        self.parameters = ParametersSettings()
        self.earth_model = CrustalModelParametersFrame()
        # help Documentation

        self.help = HelpDoc()

    def open_parameters_settings(self):
        self.parameters.show()

    def open_earth_model(self):
        self.earth_model.show()

    def filter_error_message(self, msg):
        md = MessageDialog(self)
        md.set_info_message(msg)

    def message_dataless_not_found(self):
        if len(self.dataless_not_found) > 1:
            md = MessageDialog(self)
            md.set_info_message("Metadata not found.")
        else:
            for file in self.dataless_not_found:
                md = MessageDialog(self)
                md.set_info_message("Metadata for {} not found.".format(file))

    def validate_file(self):
        if not MseedUtil.is_valid_mseed(self.file_selector.file_path):
            msg = "The file {} is not a valid mseed. Please, choose a valid format". \
                format(self.file_selector.file_name)
            raise InvalidFile(msg)

    def on_click_select_directory(self, bind: BindPyqtObject):
        if "darwin" == platform:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', bind.value)
        else:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', bind.value,
                pw.QFileDialog.DontUseNativeDialog)
        if dir_path:
            bind.value = dir_path

    def on_click_select_file(self, bind: BindPyqtObject):
        file_path = pw.QFileDialog.getOpenFileName(self, 'Select Directory',
                                                   bind.value)
        file_path = file_path[0]

        if file_path:
            bind.value = file_path

    def on_click_select_metadata_file(self, bind: BindPyqtObject):
        selected = pw.QFileDialog.getOpenFileName(self, "Select metadata file")
        if isinstance(selected[0], str) and os.path.isfile(selected[0]):
            bind.value = selected[0]

    def onChange_metadata_path(self, value):
        md = MessageDialog(self)
        try:
            self.__metadata_manager = MetadataManager(value)
            self.inventory = self.__metadata_manager.get_inventory()
            print(self.inventory)
            md.set_info_message(
                "Loaded Metadata, please check your terminal for further details"
            )
        except:
            md.set_error_message(
                "Something went wrong. Please check your metada file is a correct one"
            )

    # def read_earth_model(self):
    #     model = self.earth_model.getParametersWithFormat()
    #     print(model)

    def plot_seismograms(self):
        parameters = self.get_inversion_parameters()
        lat = float(parameters['latitude'])
        lon = float(parameters['longitude'])
        starttime = convert_qdatetime_utcdatetime(self.starttime_date)
        endtime = convert_qdatetime_utcdatetime(self.endtime_date)
        diff = endtime - starttime

        parameters = self.parameters.getParameters()
        all_traces = []
        obsfiles = MseedUtil.get_mseed_files(self.root_path_bind.value)
        obsfiles.sort()

        for file in obsfiles:
            sd = SeismogramDataAdvanced(file)
            if self.trimCB.isChecked() and diff >= 0:
                tr = sd.get_waveform_advanced(
                    parameters,
                    self.inventory,
                    filter_error_callback=self.filter_error_message,
                    start_time=starttime,
                    end_time=endtime)
            else:
                tr = sd.get_waveform_advanced(
                    parameters,
                    self.inventory,
                    filter_error_callback=self.filter_error_message)

            all_traces.append(tr)

        self.st = Stream(traces=all_traces)
        self.stream_frame = MatplotlibFrame(self.st, type='normal')
        self.stream_frame.show()

        if self.st:
            min_dist = self.min_distCB.value()
            max_dist = self.max_distCB.value()
            mt = MTIManager(self.st, self.inventory, lat, lon, min_dist,
                            max_dist)
            [self.stream, self.deltas,
             self.stations_isola_path] = mt.get_stations_index()

    def stationsInfo(self):

        file_path = self.root_path_bind.value
        obsfiles = MseedUtil.get_mseed_files(self.root_path_bind.value)
        obsfiles.sort()
        sd = []

        for file in obsfiles:

            st = SeismogramDataAdvanced(file)

            station = [
                st.stats.Network, st.stats.Station, st.stats.Location,
                st.stats.Channel, st.stats.StartTime, st.stats.EndTime,
                st.stats.Sampling_rate, st.stats.Npts
            ]

            sd.append(station)

        self._stations_info = StationsInfo(sd, check=True)
        self._stations_info.show()

    def write(self):
        root_path = os.path.dirname(os.path.abspath(__file__))
        if "darwin" == platform:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', root_path)
        else:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', root_path,
                pw.QFileDialog.DontUseNativeDialog)
        if not dir_path:
            return

        n = len(self.st)
        for j in range(n):
            tr = self.st[j]
            print(tr.id, "Writing data processed")
            path_output = os.path.join(dir_path, tr.id)
            tr.write(path_output, format="MSEED")

    ##In progress##
    def load_event_from_isolapath(self):
        root_path = os.path.dirname(os.path.abspath(__file__))
        file_path = pw.QFileDialog.getOpenFileName(self, 'Select Directory',
                                                   root_path)
        file = file_path[0]
        frame = pd.read_csv(file, sep='\s+', header=None)
        time = frame.iloc[3][0]
        year = time[0:4]
        mm = time[4:6]
        dd = time[6:8]
        hour = frame.iloc[4][0]
        minute = frame.iloc[5][0]
        sec = frame.iloc[6][0]
        sec = float(sec)
        dec = sec - int(sec)
        dec = int(sec)

        time = UTCDateTime(int(year), int(mm), int(dd), int(hour), int(minute),
                           int(sec), dec)
        event = {
            'lat': frame.iloc[0][0],
            'lon': frame.iloc[0][1],
            'depth': frame.iloc[1][0],
            'mag': frame.iloc[2][0],
            'time': time,
            'istitution': frame.iloc[7][0]
        }

        return event

    @AsycTime.run_async()
    def run_inversion(self):
        parameters = self.get_inversion_parameters()
        try:
            stations_map = self._stations_info.get_stations_map()
        except:
            md = MessageDialog(self)
            md.set_info_message("Press Stations info and check your selection")

        if len(self.stream) and len(stations_map) > 0:

            isola = ISOLA(self.stream,
                          self.deltas,
                          location_unc=parameters['location_unc'],
                          depth_unc=parameters['depth_unc'],
                          time_unc=parameters['time_unc'],
                          deviatoric=parameters['deviatoric'],
                          threads=8,
                          circle_shape=parameters['circle_shape'],
                          use_precalculated_Green=parameters['GFs'])
            #
            isola.set_event_info(parameters['latitude'],
                                 parameters['longitude'], parameters['depth'],
                                 parameters['magnitude'],
                                 parameters['origin_time'])
            #
            print(isola.event)
            #
            #
            if self.stations_isola_path:
                isola.read_network_coordinates(self.stations_isola_path)
                isola.set_use_components(stations_map)
                #print(isola.stations)
                isola.read_crust(self.earth_path_bind.value)

                isola.set_parameters(parameters['freq_max'],
                                     parameters['freq_min'])
                self.infoTx.setPlainText("Calculated GFs")
                if not isola.calculate_or_verify_Green():
                    exit()
                self.infoTx.appendPlainText("Filtered and trim")
                isola.trim_filter_data()
                try:

                    if parameters['covariance']:
                        self.infoTx.appendPlainText(
                            "Calculating Covariance Matrix")
                        isola.covariance_matrix(crosscovariance=True,
                                                save_non_inverted=True,
                                                save_covariance_function=True)
                except:
                    md = MessageDialog(self)
                    md.set_error_message(
                        "No Possible calculate covariance matrix, "
                        "please try increasing the noise time window")
            #
                self.infoTx.appendPlainText("decimate and shift")
                isola.decimate_shift()
                self.infoTx.appendPlainText("Run inversion")
                isola.run_inversion()
                self.infoTx.appendPlainText("Finished Inversion")
                isola.find_best_grid_point()
                isola.print_solution()
                isola.print_fault_planes()
                self.infoTx.appendPlainText("Plotting Solutions")
                if len(isola.grid) > len(isola.depths):
                    isola.plot_maps()
                    self.infoTx.appendPlainText("plot_maps")
                if len(isola.depths) > 1:
                    isola.plot_slices()
                    self.infoTx.appendPlainText("plot_slices")
                if len(isola.grid) > len(isola.depths) and len(
                        isola.depths) > 1:
                    isola.plot_maps_sum()
                    self.infoTx.appendPlainText("plot_maps_sum")

                try:

                    isola.plot_MT()
                    self.infoTx.appendPlainText("plot_MT")
                    isola.plot_uncertainty(n=400)
                    self.infoTx.appendPlainText("plot_uncertainty")
                    #plot_MT_uncertainty_centroid()
                    isola.plot_seismo('seismo.png')
                    isola.plot_seismo('seismo_sharey.png', sharey=True)
                    self.infoTx.appendPlainText("plot_seismo")

                    if self.covarianceCB.isChecked():
                        isola.plot_seismo('plot_seismo.png', cholesky=True)
                        self.infoTx.appendPlainText("plot_seismo_cova")
                        isola.plot_noise()
                        self.infoTx.appendPlainText("plot_noise")
                        isola.plot_spectra()
                        self.infoTx.appendPlainText("plot_spectra")

                    isola.plot_stations()
                    self.infoTx.appendPlainText("plot_stations")

                except:
                    print("Couldn't Plot")

                try:
                    if self.covarianceCB.isChecked():
                        isola.plot_covariance_matrix(colorbar=True)
                    #isola.plot_3D()
                except:
                    pass

                try:
                    isola.html_log(
                        h1='ISP Moment Tensor inversion',
                        plot_MT='centroid.png',
                        plot_uncertainty='uncertainty.png',
                        plot_stations='stations.png',
                        plot_seismo_cova='seismo_cova.png',
                        plot_seismo_sharey='seismo_sharey.png',
                        plot_spectra='spectra.png',
                        plot_noise='noise.png',
                        plot_covariance_matrix='covariance_matrix.png',
                        plot_maps='map.png',
                        plot_slices='slice.png',
                        plot_maps_sum='map_sum.png')
                except:
                    self.infoTx.appendPlainText("Couldn't load url")
                try:
                    isola.html_log(h1='ISP Moment Tensor inversion',
                                   plot_MT='centroid.png',
                                   plot_uncertainty='uncertainty.png',
                                   plot_stations='stations.png',
                                   plot_seismo_sharey='seismo_sharey.png',
                                   plot_maps='map.png',
                                   plot_slices='slice.png')
                except:
                    self.infoTx.appendPlainText("Couldn't load url")

                self.infoTx.appendPlainText(
                    "Moment Tensor Inversion Successfully done !!!, please plot last solution"
                )
            else:
                pass

    def plot_solution(self):

        path = os.path.join(ROOT_DIR, 'mti/output/index.html')
        url = pyc.QUrl.fromLocalFile(path)
        self.widget.load(url)

    def get_inversion_parameters(self):
        parameters = {
            'latitude': self.latDB.value(),
            'longitude': self.lonDB.value(),
            'depth': self.depthDB.value(),
            'origin_time': convert_qdatetime_utcdatetime(self.origin_time),
            'location_unc': self.location_uncDB.value(),
            'time_unc': self.timeDB.value(),
            'magnitude': self.magnitudeDB.value(),
            'depth_unc': self.depth_uncDB.value(),
            'freq_min': self.freq_min_DB.value(),
            'freq_max': self.freq_max_DB.value(),
            'deviatoric': self.deviatoricCB.isChecked(),
            'circle_shape': self.circle_shapeCB.isChecked(),
            'GFs': self.gfCB.isChecked(),
            'covariance': self.covarianceCB.isChecked()
        }
        return parameters

    def plot_map_stations(self):
        md = MessageDialog(self)
        md.hide()
        try:
            stations = []
            obsfiles = MseedUtil.get_mseed_files(self.root_path_bind.value)
            obsfiles.sort()
            try:
                if len(self.stream) > 0:
                    stations = ObspyUtil.get_stations_from_stream(self.stream)
            except:
                pass

            map_dict = {}
            sd = []

            for file in obsfiles:
                if len(stations) == 0:
                    st = SeismogramDataAdvanced(file)

                    name = st.stats.Network + "." + st.stats.Station

                    sd.append(name)

                    st_coordinates = self.__metadata_manager.extract_coordinates(
                        self.inventory, file)

                    map_dict[name] = [
                        st_coordinates.Latitude, st_coordinates.Longitude
                    ]
                else:
                    st = SeismogramDataAdvanced(file)
                    if st.stats.Station in stations:
                        name = st.stats.Network + "." + st.stats.Station

                        sd.append(name)

                        st_coordinates = self.__metadata_manager.extract_coordinates(
                            self.inventory, file)

                        map_dict[name] = [
                            st_coordinates.Latitude, st_coordinates.Longitude
                        ]
                    else:
                        pass

            self.map_stations = StationsMap(map_dict)
            self.map_stations.plot_stations_map(latitude=self.latDB.value(),
                                                longitude=self.lonDB.value())

            md.set_info_message("Station Map OK !!! ")
        except:
            md.set_error_message(
                " Please check you have process and plot seismograms and opened stations info,"
                "Please additionally check that your metada fits with your mseed files"
            )

        md.show()

    def open_help(self):
        self.help.show()
Exemplo n.º 11
0
class Controller:
    def __init__(self):
        self.main_frame = None
        self.time_frequency_frame = None
        self.earthquake_analysis_frame = None
        self.array_analysis_frame = None
        self.moment_tensor_frame = None
        self.receiver_functions_frame = None
        self.project_frame = None
        self.synthetics_frame = None
        self.data_download_frame = None
        self.ppds_frame = None
        self.realtime_frame = None
        self.noise_frame = None
        self.help = HelpDoc()

    def open_main_window(self):
        # Start the ui designer
        self.main_frame = MainFrame()
        # bind clicks
        self.main_frame.seismogramButton.clicked.connect(
            self.open_seismogram_window)
        self.main_frame.earthquakeButton.clicked.connect(
            self.open_earthquake_window)
        self.main_frame.arrayAnalysisButton.clicked.connect(
            self.open_array_window)
        self.main_frame.momentTensorButton.clicked.connect(
            self.open_momentTensor_window)
        self.main_frame.receiverFunctionsButton.clicked.connect(
            self.open_receiverFunctions)
        self.main_frame.noiseButton.clicked.connect(self.open_noise)
        self.main_frame.actionReal_Time.triggered.connect(
            self.open_realtime_window)
        self.main_frame.actionOpen_Project.triggered.connect(self.open_project)
        self.main_frame.actionCreate_new_Project.triggered.connect(
            self.create_project)
        self.main_frame.actionRetrieve_data.triggered.connect(
            self.retrieve_data)
        self.main_frame.actionPPSDs.triggered.connect(self.ppsds)
        self.main_frame.actionOpen_Help.triggered.connect(
            lambda: self.open_help())
        # show frame
        self.main_frame.show()

    def open_seismogram_window(self):
        # Start the ui designer
        if not self.time_frequency_frame:
            self.time_frequency_frame = TimeFrequencyFrame()
        self.time_frequency_frame.show()

    def open_earthquake_window(self):
        # Start the ui designer
        if not self.earthquake_analysis_frame:
            self.earthquake_analysis_frame = EarthquakeAnalysisFrame()
        self.earthquake_analysis_frame.show()

    def open_realtime_window(self):
        # Start the ui designer
        if not self.realtime_frame:
            self.realtime_frame = RealTimeFrame()
        self.realtime_frame.show()

    def open_array_window(self):
        # Start the ui designer
        if not self.array_analysis_frame:
            self.array_analysis_frame = ArrayAnalysisFrame()
        self.array_analysis_frame.show()

    def open_momentTensor_window(self):
        # Start the ui designer
        if not self.moment_tensor_frame:
            self.moment_tensor_frame = MTIFrame()
        self.moment_tensor_frame.show()

    def open_receiverFunctions(self):
        if not self.receiver_functions_frame:
            self.receiver_functions_frame = RecfFrame()
        self.receiver_functions_frame.show()

    def open_noise(self):
        if not self.noise_frame:
            self.noise_frame = NoiseFrame()
        self.noise_frame.show()

    def open_project(self):
        if not self.project_frame:
            self.project_frame = EventLocationFrame()
        if not self.project_frame.isVisible():
            self.project_frame.refreshLimits()
        self.project_frame.show()

    def create_project(self):
        if not self.synthetics_frame:
            self.synthetics_frame = SyntheticsAnalisysFrame()
        self.synthetics_frame.show()

    def retrieve_data(self):
        if not self.data_download_frame:
            self.data_download_frame = DataDownloadFrame()
        self.data_download_frame.show()

    def ppsds(self):
        if not self.ppds_frame:
            self.ppds_frame = PPSDFrame()
        self.ppds_frame.show()

    def open_help(self):
        self.help.show()

    def exception_parse(self, error_cls, exception, exc_traceback):
        md = MessageDialog(self.main_frame)
        detail_error = "".join(
            traceback.format_exception(error_cls, exception, exc_traceback))
        md.set_error_message(message="{}:{}".format(error_cls.__name__,
                                                    exception),
                             detailed_message=detail_error)
        md.show()
Exemplo n.º 12
0
class DataDownloadFrame(BaseFrame, UiDataDownloadFrame):
    def __init__(self):
        super(BaseFrame, self).__init__()
        self.setupUi(self)
        self.inventory = {}
        self.network_list = []
        self.stations_list = []
        self.catalogBtn.clicked.connect(self.get_catalog)
        self.event_dataBtn.clicked.connect(self.download_events)
        self.plotstationsBtn.clicked.connect(self.stations)
        self.TimeBtn.clicked.connect(self.download_time_series)
        self.MetadataBtn.clicked.connect(self.download_stations_xml)
        self.LoadBtn.clicked.connect(self.load_inventory)
        # Map
        self.cartopy_canvas = CartopyCanvas(self.map)
        self.cartopy_canvas.global_map(0)
        self.cartopy_canvas.figure.subplots_adjust(left=0.00,
                                                   bottom=0.055,
                                                   right=0.97,
                                                   top=0.920,
                                                   wspace=0.0,
                                                   hspace=0.0)
        self.activated_colorbar = True
        self.cartopy_canvas.on_double_click(self.on_click_matplotlib)
        self.cartopy_canvas.mpl_connect('key_press_event', self.key_pressed)
        self.cartopy_canvas.mpl_connect('button_press_event', self.press_right)
        self.actionOpen_Help.triggered.connect(lambda: self.open_help())
        # signal doubleclick
        self.tableWidget.cellDoubleClicked.connect(self.get_coordinates)

        # help Documentation

        self.help = HelpDoc()

        #
        self.latitudes = []
        self.longitudes = []
        self.depths = []
        self.magnitudes = []

    def get_coordinates(self, row, column):
        lat = self.tableWidget.item(row, 1).data(0)
        lon = self.tableWidget.item(row, 2).data(0)
        lat30, lon30, lat90, lon90 = retrieve.get_circle(lat, lon)
        self.cartopy_canvas.global_map(0,
                                       clear_plot=False,
                                       show_distance_circles=True,
                                       lon30=lon30,
                                       lat30=lat30,
                                       lon90=lon90,
                                       lat90=lat90)

        #ax = self.cartopy_canvas.get_axe(0)
        #self.line1 = ax.scatter(lon30, lat30, s=8, c="white")
        #self.line2 = ax.scatter(lon90, lat90, s=8, c="white")

    def get_catalog(self):

        latitudes = []
        longitudes = []
        depths = []
        magnitudes = []
        starttime = convert_qdatetime_utcdatetime(self.start_dateTimeEdit)
        endtime = convert_qdatetime_utcdatetime(self.end_dateTimeEdit)
        minmagnitude = self.min_magnitudeCB.value()
        maxmagnitude = self.max_magnitudeCB.value()
        mindepth = self.depth_minCB.value()
        maxdepth = self.depth_maxCB.value()

        try:
            md = MessageDialog(self)
            md.hide()
            catalog = self.client.get_events(starttime=starttime,
                                             endtime=endtime,
                                             mindepth=mindepth,
                                             maxdepth=maxdepth,
                                             minmagnitude=minmagnitude,
                                             maxmagnitude=maxmagnitude)
            for event in catalog:
                otime = event.origins[0].time
                lat = event.origins[0].latitude
                lon = event.origins[0].longitude
                depth = event.origins[0].depth
                magnitude = event.magnitudes[0].mag
                magnitude_type = event.magnitudes[0].magnitude_type
                # append results
                latitudes.append(lat)
                longitudes.append(lon)
                depths.append(depth)
                magnitudes.append(magnitude)

                self.tableWidget.insertRow(self.tableWidget.rowCount())
                self.tableWidget.setItem(
                    self.tableWidget.rowCount() - 1, 0,
                    QtWidgets.QTableWidgetItem(str(otime)))
                self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 1,
                                         QtWidgets.QTableWidgetItem(str(lat)))
                self.tableWidget.setItem(self.tableWidget.rowCount() - 1, 2,
                                         QtWidgets.QTableWidgetItem(str(lon)))
                try:

                    self.tableWidget.setItem(
                        self.tableWidget.rowCount() - 1, 3,
                        QtWidgets.QTableWidgetItem(str(depth / 1000)))

                except TypeError:

                    self.tableWidget.setItem(self.tableWidget.rowCount() - 1,
                                             3,
                                             QtWidgets.QTableWidgetItem("N/A"))

                self.tableWidget.setItem(
                    self.tableWidget.rowCount() - 1, 4,
                    QtWidgets.QTableWidgetItem(str(magnitude)))
                self.tableWidget.setItem(
                    self.tableWidget.rowCount() - 1, 5,
                    QtWidgets.QTableWidgetItem(str(magnitude_type)))

            selection_range = QtWidgets.QTableWidgetSelectionRange(
                0, 0,
                self.tableWidget.rowCount() - 1,
                self.tableWidget.columnCount() - 1)
            #print(selection_range.bottomRow())

            self.longitudes = longitudes
            self.latitudes = latitudes
            self.depths = depths
            self.magnitudes = magnitudes
            self.tableWidget.setRangeSelected(selection_range, True)
            #print(selection_range)
            self.catalog_out = [latitudes, longitudes, depths, magnitudes]
            # plot earthquakes
            self.cartopy_canvas.global_map(
                0,
                plot_earthquakes=True,
                show_colorbar=self.activated_colorbar,
                lat=latitudes,
                lon=longitudes,
                depth=depths,
                magnitude=magnitudes,
                resolution=self.typeCB.currentText())

            self.activated_colorbar = False
            self.event_dataBtn.setEnabled(True)
            md.set_info_message("Catalog generated succesfully!!!")
            md.show()
        except:

            md.set_error_message(
                "Something wet wrong, Please check that you have: 1- Loaded Inventory, "
                "2- Search Parameters have sense")
            md.show()

        #obspy.clients.fdsn.client.Client

    def download_events(self):

        root_path = os.path.dirname(os.path.abspath(__file__))

        if "darwin" == platform:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', root_path)
        else:
            dir_path = pw.QFileDialog.getExistingDirectory(
                self, 'Select Directory', root_path,
                pw.QFileDialog.DontUseNativeDialog)
        if not dir_path:
            return

        starttime = convert_qdatetime_utcdatetime(self.start_dateTimeEdit)
        endtime = convert_qdatetime_utcdatetime(self.end_dateTimeEdit)
        selected_items = self.tableWidget.selectedItems()
        event_dict = {}
        errors = False
        row = 0
        column = 0
        for i, item in enumerate(selected_items):
            event_dict.setdefault(row, {})
            header = self.tableWidget.horizontalHeaderItem(column).text()
            event_dict[row][header] = item.text()
            column += 1
            if i % 5 == 0 and i > 0:
                row += 1
                column = 0

        # Get stations

        networks = self.networksLE.text()
        stations = self.stationsLE.text()
        channels = self.channelsLE.text()

        if self.Earthworm_CB.isChecked():
            ip_address = self.IP_LE.text()
            port = self.portLE.text()
            client_earthworm = obspy.clients.earthworm.Client(
                ip_address, int(port))
            inventory = client_earthworm.get_stations(network=networks,
                                                      station=stations,
                                                      starttime=starttime,
                                                      endtime=endtime)
        else:

            inventory = self.client.get_stations(network=networks,
                                                 station=stations,
                                                 starttime=starttime,
                                                 endtime=endtime)

        model = obspy.taup.TauPyModel(model="iasp91")

        for event in event_dict.keys():
            otime = obspy.UTCDateTime(event_dict[event]['otime'])
            evla = float(event_dict[event]['lat'])
            evlo = float(event_dict[event]['lon'])
            evdp = float(event_dict[event]['depth'])
            for ntwk in inventory:
                ntwknm = ntwk.code
                for stn in ntwk:
                    stnm = stn.code
                    stla = stn.latitude
                    stlo = stn.longitude
                    #stev = stn.elevation

                    # Distance, azimuth and back_azimuth for event:
                    m_dist, az, back_az = obspy.geodetics.base.gps2dist_azimuth(
                        evla, evlo, stla, stlo)
                    deg_dist = obspy.geodetics.base.kilometers2degrees(m_dist /
                                                                       1000)
                    atime = model.get_travel_times(source_depth_in_km=evdp,
                                                   distance_in_degree=deg_dist,
                                                   receiver_depth_in_km=0.0)

                    p_onset = otime + atime[0].time
                    start = p_onset - self.timebeforeCB.value()
                    end = p_onset + self.timeafterCB.value()

                    try:

                        st = self.client.get_waveforms(ntwknm, stnm, "*",
                                                       channels, start, end)
                        print(st)
                        self.write(st, dir_path)

                    except:
                        errors = True
                        md = MessageDialog(self)
                        md.set_error_message(ntwknm + "." + stnm + "." +
                                             channels + "   " +
                                             "Couldn't download data")
        if errors:
            md = MessageDialog(self)
            md.set_info_message("Download completed with some errors")
        else:
            md = MessageDialog(self)
            md.set_info_message("Download completed")

    def download_stations_xml(self):

        fname = QtWidgets.QFileDialog.getSaveFileName()[0]
        starttime = convert_qdatetime_utcdatetime(self.start_dateTimeEdit)
        endtime = convert_qdatetime_utcdatetime(self.end_dateTimeEdit)
        networks = self.networksLE.text()
        stations = self.stationsLE.text()
        channels = self.channelsLE.text()

        inventory = self.client.get_stations(network=networks,
                                             station=stations,
                                             starttime=starttime,
                                             endtime=endtime,
                                             level="response")
        try:
            print("Getting metadata from ", networks, stations, channels,
                  starttime, endtime)
            inventory.write(fname, format="STATIONXML")
            md = MessageDialog(self)
            md.set_info_message("Download completed")
        except:

            md = MessageDialog(self)
            md.set_error_message("Metadata coudn't be downloaded")

    def download_time_series(self):

        starttime = convert_qdatetime_utcdatetime(self.start_dateTimeEdit)
        endtime = convert_qdatetime_utcdatetime(self.end_dateTimeEdit)
        networks = self.networksLE.text()
        stations = self.stationsLE.text()
        channels = self.channelsLE.text()

        try:

            print("Getting data from ", networks, stations, channels,
                  starttime, endtime)
            st = self.client.get_waveforms(networks, stations, "*", channels,
                                           starttime, endtime)
            if len(st) > 0:

                root_path = os.path.dirname(os.path.abspath(__file__))
                if "darwin" == platform:
                    dir_path = pw.QFileDialog.getExistingDirectory(
                        self, 'Select Directory', root_path)
                else:
                    dir_path = pw.QFileDialog.getExistingDirectory(
                        self, 'Select Directory', root_path,
                        pw.QFileDialog.DontUseNativeDialog)
                self.write(st, dir_path)

        except:
            md = MessageDialog(self)
            md.set_info_message("Couldn't download time series")

    def write(self, st, dir_path):

        if dir_path:
            n = len(st)
            try:
                for j in range(n):
                    tr = st[j]
                    t1 = tr.stats.starttime
                    id = tr.id + "." + "D" + "." + str(t1.year) + "." + str(
                        t1.julday)
                    print(tr.id, "Writing data processed")
                    path_output = os.path.join(dir_path, id)
                    tr.write(path_output, format="MSEED")

            except:
                md = MessageDialog(self)
                md.set_info_message("Nothing to write")

    def load_inventory(self):
        #self.networksLE.setText("")
        self.stationsLE.setText("")
        self.channelsLE.setText("")
        starttime = convert_qdatetime_utcdatetime(self.start_dateTimeEdit)
        endtime = convert_qdatetime_utcdatetime(self.end_dateTimeEdit)
        self.retrivetool = retrieve()

        try:
            self.inventory, self.client = self.retrivetool.get_inventory(
                self.URL_CB.currentText(),
                starttime,
                endtime,
                self.networksLE.text(),
                self.stationsLE.text(),
                use_networks=self.netsCB.isChecked(),
                FDSN=self.FDSN_CB.isChecked(),
                ip_address=self.IP_LE.text(),
                port=self.portLE.text())
            if self.inventory and self.client is not None:
                md = MessageDialog(self)
                md.set_info_message("Loaded Inventory from Address")
                self.plotstationsBtn.setEnabled(True)
                self.catalogBtn.setEnabled(True)
            else:
                md = MessageDialog(self)
                md.set_info_message(
                    "The current client does not have a station service. "
                    "Please check that you do not have selected -just specific nets- and the net "
                    "field provide a net name that is not expected in this service"
                )
        except:
            md = MessageDialog(self)
            md.set_info_message(
                "The current client does not have a station service")

    def stations(self):

        coordinates = self.retrivetool.get_inventory_coordinates(
            self.inventory)
        self.cartopy_canvas.global_map(
            0,
            plot_earthquakes=False,
            show_colorbar=False,
            show_stations=True,
            show_station_names=self.namesCB.isChecked(),
            clear_plot=True,
            coordinates=coordinates,
            resolution=self.typeCB.currentText())
        if len(self.latitudes) > 0 and len(self.longitudes) and len(
                self.depths) and len(self.magnitudes) > 0:

            self.cartopy_canvas.global_map(
                0,
                plot_earthquakes=True,
                show_colorbar=self.activated_colorbar,
                clear_plot=False,
                lat=self.latitudes,
                lon=self.longitudes,
                depth=self.depths,
                magnitude=self.magnitudes,
                resolution=self.typeCB.currentText())

    def on_click_matplotlib(self, event, canvas):
        self.retrivetool = retrieve()
        if isinstance(canvas, CartopyCanvas):
            x1, y1 = event.xdata, event.ydata
            data = self.retrivetool.get_station_id(x1, y1, self.inventory)

            if len(data[0]) > 0 and len(data[1]) > 0:

                if data[0] not in self.network_list:
                    self.network_list.append(data[0])
                    self.networksLE.setText(",".join(self.network_list))
                if data[1] not in self.stations_list:
                    self.stations_list.append(data[1])
                    self.stationsLE.setText(",".join(self.stations_list))

    def key_pressed(self, event):

        self.network_list = []
        self.stations_list = []

        if event.key == 'c':

            self.networksLE.setText(",".join(self.network_list))
            self.stationsLE.setText(",".join(self.stations_list))

    def press_right(self, event):
        self.retrivetool = retrieve()
        if event.dblclick:
            if event.button == 3:
                x1, y1 = event.xdata, event.ydata
                data = self.retrivetool.get_station_id(x1, y1, self.inventory)

                if len(data[0]) > 0 and len(data[1]) > 0:

                    if data[0] in self.network_list:
                        self.network_list.remove(data[0])
                        self.networksLE.setText(",".join(self.network_list))
                    if data[1] in self.stations_list:
                        self.stations_list.remove(data[1])
                        self.stationsLE.setText(",".join(self.stations_list))

    def open_help(self):
        self.help.show()