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 run_vespa(self): vespa = vespagram_util(self.st, self.freq_min_DB.value(), self.freq_max_DB.value(), self.win_len_DB.value(), self.slownessDB.value(), self.backazimuthCB.value(), self.inv, self.t1, self.t2, self.overlapSB.value(), selection=self.selectionCB.currentText(), method="FK") self.x, self.y, self.log_vespa_spectrogram = vespa.vespa_deg() md = MessageDialog(self) md.set_info_message("Vespagram Estimated !!!")
def subprocess_feedback(self, err_msg: str, set_default_complete=True): """ This method is used as a subprocess feedback. It runs when a raise expect is detected. :param err_msg: The error message from the except. :param set_default_complete: If True it will set a completed successfully message. Otherwise nothing will be displayed. :return: """ if err_msg: md = MessageDialog(self) if "Error code" in err_msg: md.set_error_message( "Click in show details detail for more info.", err_msg) else: md.set_warning_message("Click in show details for more info.", err_msg) else: if set_default_complete: md = MessageDialog(self) md.set_info_message("Loaded Metadata Successfully.")
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()
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 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" )
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 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 plot_ppsds(self, stations_per_page): starttime = obspy.UTCDateTime(self.dateTimeEdit_4.dateTime().toString( "yyyy-MM-ddThh:mm:ss.zzz000Z")) endtime = obspy.UTCDateTime(self.dateTimeEdit_5.dateTime().toString( "yyyy-MM-ddThh:mm:ss.zzz000Z")) # Check which radiobutton is checked: PDFs or Variation if self.radioButton.isChecked(): plot_mode = "pdf" elif self.radioButton_2.isChecked(): plot_mode = "variation" stations_per_page = self.spinBox.value() #mode = self.comboBox.currentText() # NOT YET IMPLEMENTED self.mplwidget.figure.clf() # Retrieve selected stations from the tableWidget selected_ppsds = self.tableWidget.selectedItems() # Loop over the items and create a dictionary # THIS WILL BREAK IF TWO STATIONS HAVE THE SAME NAME AS OF THIS VERSION item_type = 0 db_query = {} for item in selected_ppsds: if item_type == 0: ntwk = item.text() elif item_type == 1: stnm = item.text() db_query.setdefault(stnm, {}) db_query[stnm].setdefault('channels', []) db_query[stnm]['network'] = ntwk else: chnm = item.text() db_query[stnm]['channels'].append(chnm) item_type += 1 if item_type == 3: item_type = 0 selected_stations = sorted(list(db_query.keys())) # Number of stations per page can never be greater than the number of # selected stations if len(selected_stations) < stations_per_page: stations_per_page = len(selected_stations) # Initialize the plot with the necessary number of axes gs = gridspec.GridSpec(stations_per_page, 3) gs.update(left=0.10, right=0.95, top=0.95, bottom=0.075, hspace=0.35, wspace=0.35) for i in range(stations_per_page * 3): self.mplwidget.figure.add_subplot(gs[i]) # If necessary populate the page combobox try: pages = round(len(db_query.keys()) / stations_per_page) except ZeroDivisionError: # This means no stations are selected md = MessageDialog(self) md.set_warning_message("No stations selected!!!") return if self.pages != pages: self.pages = pages self.comboBox_2.clear() for i in range(pages): self.comboBox_2.addItem(str(i + 1)) # Plot the corresponding stations try: page = int(self.comboBox_2.currentText()) - 1 except ValueError: page = 0 st1 = stations_per_page * page st2 = min(st1 + stations_per_page, len(selected_stations)) j = 0 # j: axis index for first channel of a station for i in range(st1, st2): stnm = selected_stations[i] ntwk = db_query[stnm]['network'] c = 0 # c index of channel in current station for chnm in sorted(db_query[stnm]['channels']): # THIS WILL BE MOVED TO AN EXTERNAL METHOD IN A FUTURE REVISION ppsd = self.ppsd_db['nets'][ntwk][stnm][chnm][1] if starttime == endtime: ppsd.calculate_histogram() else: ppsd.calculate_histogram(starttime=starttime, endtime=endtime) if plot_mode == "pdf": try: zdata = (ppsd.current_histogram * 100 / (ppsd.current_histogram_count or 1)) except: # This means no stations are selected md = MessageDialog(self) md.set_error_message("Some data channel no valid.") return xedges = ppsd.period_xedges yedges = ppsd.db_bin_edges meshgrid = np.meshgrid(xedges, yedges) mode = ppsd.db_bin_centers[ppsd._current_hist_stack.argmax( axis=1)] self.mplwidget.figure.axes[j + c].pcolormesh( meshgrid[0], meshgrid[1], zdata.T, cmap=obspy.imaging.cm.pqlx) self.mplwidget.figure.axes[j + c].set_xscale("log") #self.mplwidget.figure.axes[j + c].plot(ppsd.period_bin_centers, mode, color='black', linewidth=2, linestyle='--', label="Mode") self.mplwidget.figure.axes[j + c].set_xscale("log") self.mplwidget.figure.axes[j + c].set_xlabel("Period (s)") self.mplwidget.figure.axes[j + c].set_ylabel("Amplitude (dB)") self.plot_statistics(self.mplwidget.figure.axes[j + c], ppsd) self.mplwidget.figure.axes[j + c].set_xlim(0.02, 120) elif plot_mode == "variation": variation = self.comboBox.currentText() # THIS WILL BE MOVED TO AN EXTERNAL METHOD IN A FUTURE REVISION if variation == "Diurnal": hist_dict = {} num_period_bins = len(ppsd.period_bin_centers) num_db_bins = len(ppsd.db_bin_centers) for i in range(24): hist_dict.setdefault( i, np.zeros((num_period_bins, num_db_bins), dtype=np.uint64)) for i, time in enumerate(ppsd.times_processed): if starttime != time: if not starttime < time < endtime: continue year = time.year jday = time.julday hour = time.hour # Check here if time is inside starttime-endtime <---- TO DO inds = ppsd._binned_psds[i] inds = ppsd.db_bin_edges.searchsorted( inds, side="left") - 1 inds[inds == -1] = 0 inds[inds == num_db_bins] -= 1 for i, inds_ in enumerate(inds): # count how often each bin has been hit for this period bin, # set the current 2D histogram column accordingly hist_dict[hour][i, inds_] += 1 # Finally compute statistical mode for each hour: modes = [] for i in sorted(list(hist_dict.keys())): current_hist = hist_dict[i] mode = ppsd.db_bin_centers[current_hist.argmax( axis=1)] modes.append(mode) x = ppsd.period_bin_centers y = np.arange(1, 25, 1) self.mplwidget.figure.axes[j + c].contourf( y, x, np.array(modes).T, cmap=obspy.imaging.cm.pqlx, levels=200) self.mplwidget.figure.axes[j + c].set_xlabel("GMT Hour") self.mplwidget.figure.axes[j + c].set_ylabel("Period (s)") self.mplwidget.figure.axes[j + c].set_ylim(0.02, 120) elif variation == "Seasonal": # Create blank 2D histogram for each hour hist_dict = {} num_period_bins = len(ppsd.period_bin_centers) num_db_bins = len(ppsd.db_bin_centers) for i in range(12): hist_dict.setdefault( i, np.zeros((num_period_bins, num_db_bins), dtype=np.uint64)) for i, time in enumerate(ppsd.times_processed): if starttime != time: if not starttime < time < endtime: continue year = time.year jday = time.julday hour = time.hour month = time.month inds = ppsd._binned_psds[i] inds = ppsd.db_bin_edges.searchsorted( inds, side="left") - 1 inds[inds == -1] = 0 inds[inds == num_db_bins] -= 1 for i, inds_ in enumerate(inds): # count how often each bin has been hit for this period bin, # set the current 2D histogram column accordingly hist_dict[month - 1][i, inds_] += 1 # Finally compute statistical mode for each month: modes = [] for i in sorted(list(hist_dict.keys())): current_hist = hist_dict[i] mode = ppsd.db_bin_centers[current_hist.argmax( axis=1)] modes.append(mode) x = ppsd.period_bin_centers y = np.arange(1, 13, 1) self.mplwidget.figure.axes[j + c].contourf( y, x, np.array(modes).T, cmap=obspy.imaging.cm.pqlx, levels=200) self.mplwidget.figure.axes[j + c].set_xlabel("Month") self.mplwidget.figure.axes[j + c].set_ylabel("Period (s)") self.mplwidget.figure.axes[j + c].set_ylim(0.02, 120) self.mplwidget.figure.axes[j + c].set_xlim(1, 12) self.mplwidget.figure.axes[j + c].set_title( chnm, fontsize=9, fontweight="medium") if c == 0: self.mplwidget.figure.axes[j].set_title(stnm, loc="left", fontsize=11, fontweight="bold") c = c + 1 if c < 3: for l in range(c, 3): self.mplwidget.figure.axes[j + l].set_axis_off() c = 3 j += c # set axis off for unused axis in the plot if j < stations_per_page * 3: for m in range(j, stations_per_page * 3): self.mplwidget.figure.axes[m].set_axis_off() self.mplwidget.figure.canvas.draw()
def filter_error_message(self, msg): md = MessageDialog(self) md.set_info_message(msg)
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 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()
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 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 plot_map(self, map_service='https://www.gebco.net/data_and_products/gebco_web_services/2020/mapserv?', layer='GEBCO_2020_Grid'): try: if self.cb: self.cb.remove() # self.map_widget.fig.delaxes(self.map_widget.fig.axes[1]) MAP_SERVICE_URL = map_service try: wms = WebMapService(MAP_SERVICE_URL) list(wms.contents) except: pass layer = layer entities = self.model.getEntities() lat = [] lon = [] depth = [] mag = [] for j in entities: lat.append(j[0].latitude) lon.append(j[0].longitude) depth.append(j[0].depth) if j[0].mw == None: j[0].mw = 3.0 mag.append(j[0].mw) # print(entities) mag = np.array(mag) mag = 0.5 * np.exp(mag) min_lon = min(lon) - 0.5 max_lon = max(lon) + 0.5 min_lat = min(lat) - 0.5 max_lat = max(lat) + 0.5 extent = [min_lon, max_lon, min_lat, max_lat] self.map_widget.ax.set_extent(extent, crs=ccrs.PlateCarree()) try: self.map_widget.ax.add_wms(wms, layer) except: os.environ["CARTOPY_USER_BACKGROUNDS"] = os.path.join(ROOT_DIR, "maps") self.map_widget.ax.background_img(name='ne_shaded', resolution="high") lon = np.array(lon) lat = np.array(lat) depth = np.array(depth) / 1000 color_map = plt.cm.get_cmap('rainbow') reversed_color_map = color_map.reversed() cs = self.map_widget.ax.scatter(lon, lat, s=mag, c=depth, edgecolors="black", cmap=reversed_color_map, transform=ccrs.PlateCarree()) self.cb = self.map_widget.fig.colorbar(cs, ax=self.map_widget.ax, orientation='horizontal', fraction=0.05, extend='both', pad=0.15, label='Depth (km)') self.map_widget.lat.scatter(depth, lat, s=mag, c=depth, edgecolors="black", cmap=reversed_color_map) self.map_widget.lat.set_ylim((min_lat, max_lat)) self.map_widget.lon.scatter(lon, depth, s=mag, c=depth, edgecolors="black", cmap=reversed_color_map) self.map_widget.lon.xaxis.tick_top() self.map_widget.lon.yaxis.tick_right() self.map_widget.lon.invert_yaxis() # self.map_widget.lon.set(xlabel='Longitude', ylabel='Depth (km)') self.map_widget.lon.set_xlim((min_lon, max_lon)) # magnitude legend kw = dict(prop="sizes", num=5, fmt="{x:.0f}", color="red", func=lambda s: np.log(s / 0.5)) self.map_widget.ax.legend(*cs.legend_elements(**kw), loc="lower right", title="Magnitudes") gl = self.map_widget.ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.2, color='gray', alpha=0.2, linestyle='-') gl.top_labels = False gl.left_labels = False gl.xlines = False gl.ylines = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER self.map_widget.fig.canvas.draw() except: md = MessageDialog(self) md.set_error_message("Couldn't extract info from the DB, please check that your database " "is loaded and is not empty")