def __init__(self, x, s): self.x = x self.s = s self.a = point.diameter / 2 self.cap = geo.Geodesic(point.diameter / 2, point.f) self.mode = "reg" """Modos:
def G_function(self, epi, depth, M0, strike, dip, rake): dict = geo.Geodesic(a=self.prior['radius'], f=self.prior['f']).ArcDirect(lat1=self.prior['la_r'], lon1=self.prior['lo_r'], azi1=self.prior['baz'], a12=epi, outmask=1929) st_syn = self.seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, strike=strike, dip=dip, rake=rake, time=self.or_time, M0=M0) self.BW_syn.Get_bw_windows(st_syn, epi, depth, self.or_time)
def start_GS(self, BW_obs, depth, epi, M0): savepath = self.prior['save_dir'] + '/%s.txt' % self.prior['save_name'] color = 'b' # self.plot_original_vs_filter(BW_obs,color,self.prior['save_dir'],"OBS") strike_len = np.linspace(0, 360, int(360 / 15) + 1, endpoint=True) dip_len = np.linspace(0, 90, int(90 / 5) + 1, endpoint=True) rake_len = np.linspace(-180, 180, int(360 / 15) + 1, endpoint=True) with open(savepath, 'w') as save_file: self.write_par(save_file) i = 0 print('Iteration: %i' % i) for i_s, strike in enumerate(strike_len): for i_d, dip in enumerate(dip_len): for i_r, rake in enumerate(rake_len): ## Get the synthetic Data: dict = geo.Geodesic(a=self.prior['radius'], f=self.prior['f']).ArcDirect( lat1=self.prior['la_r'], lon1=self.prior['lo_r'], azi1=self.prior['baz'], a12=epi, outmask=1929) st_syn = self.seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, strike=strike, dip=dip, rake=rake, time=self.or_time, M0=M0) self.BW_syn.Get_bw_windows(st_syn, epi, depth, self.or_time, self.prior['Full_P_shift'],self.prior['Full_S_shift']) # color = 'r' # self.plot_original_vs_filter(self.BW_syn,color, self.prior['save_dir'], str(i)) ## Determine the misfit: Xi_bw, Norms, amplitude, time_shift, fig = self.mis.CC_BW(BW_obs, self.BW_syn, self.prior['Full_P_shift'], self.prior['Full_S_shift'], self.prior['PLOT']) M0_New = M0 / np.mean(amplitude) # Only Based on PZ if self.prior['PLOT'] == True: # self.plot() if not os.path.exists(self.prior['save_dir'] + '/plots/'): os.makedirs(self.prior['save_dir'] + '/plots/') fig.savefig( self.prior['save_dir'] + '/plots/%.3f_%.3f_%.3f_%05i.png' % (strike, dip, rake, i)) plt.close("all") self.write_sample(save_file, epi, depth, strike, dip, rake, M0_New, Xi_bw, Norms, amplitude[0], time_shift, i, accept=1) i += 1 print('Iteration: %i' % i) save_file.close()
def PolygonArea(cords): """ cords = [[lat,lon]...] list Use geodesics on WGS84 for calculations. return nvertices, perimeter, area (hectares) """ geoobj = gd.Geodesic(gd.Constants.WGS84_a, gd.Constants.WGS84_f) poly = pa.PolygonArea(geoobj) for p in cords: poly.AddPoint(*p) n, perim, area = poly.Compute(True) area = area * 10**(-4) # to hectares return n, perim, area
def set_semiPerimeter(self, SemiPerimeter): """Definição do valor do semiperímetro e calculo do valor de f correspondente Arguments: SemiPerimeter {[float]} -- [medida do semiperímetro] Returns: f[float] -- [razão de achatamento] """ self.SemiPerimeter = SemiPerimeter def CalcSemiPerimeter(f): cap = geo.Geodesic(self.diameter / 2, f) result = cap.Inverse(lat1=0, lon1=0, lat2=90, lon2=0) CalcSP = result.get('s12') return CalcSP res = opt.minimize(lambda x: (CalcSemiPerimeter( x) - SemiPerimeter)**2, bounds=[(0, 0.999)], method='L-BFGS-B', x0=0.5) f = res.get("x")[0] self.set_f(f) self.cap = geo.Geodesic(self.diameter / 2, self.f)
def CalcSemiPerimeter(f): cap = geo.Geodesic(self.diameter / 2, f) result = cap.Inverse(lat1=0, lon1=0, lat2=90, lon2=0) CalcSP = result.get('s12') return CalcSP
def set_f(self, f): self.f = f self.cap = geo.Geodesic(self.diameter / 2, f) result = self.cap.Inverse(lat1=0, lon1=0, lat2=90, lon2=0) self.SemiPerimeter = result.get("s12") self.__regPolys()
def Normal_check(): # Initiate Parameters: get_parameters = Get_Paramters() PARAMETERS = get_parameters.get_unkown() PRIOR = get_parameters.get_prior() VALUES = get_parameters.specifications() VALUES['blind'] = False VALUES[ 'directory'] = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Final/check_waveforms' ## DISCUSS THIS!!!! PRIOR['az'] = PARAMETERS['az'] PRIOR['baz'] = PARAMETERS['baz'] # Initiate the databases from instaseis: db = instaseis.open_db(PRIOR['VELOC']) create = Create_observed(PRIOR, db) d_obs, tr_obs, source = create.get_seis_automatic( parameters=PARAMETERS, prior=PRIOR, noise_model=VALUES['noise'], sdr=VALUES['sdr']) traces_obs, p_obs, s_obs, p_time_obs, s_time_obs = create.get_window_obspy( tr_obs, PARAMETERS['epi'], PARAMETERS['depth_s'], PARAMETERS['origin_time'], VALUES['npts']) time_at_receiver = create.get_receiver_time(PARAMETERS['epi'], PARAMETERS['depth_s'], PARAMETERS['origin_time']) PRIOR['var_est'] = create.get_var_data(p_time_obs, tr_obs) sw = Surface_waves(PRIOR) R_env_obs = sw.rayleigh_pick(tr_obs.traces[0], PARAMETERS['la_s'], PARAMETERS['lo_s'], PARAMETERS['depth_s'], VALUES['directory'], PARAMETERS['origin_time'], VALUES['npts'], plot_modus=False) L_env_obs = sw.love_pick(tr_obs.traces[2], PARAMETERS['la_s'], PARAMETERS['lo_s'], PARAMETERS['depth_s'], VALUES['directory'], PARAMETERS['origin_time'], VALUES['npts'], plot_modus=False) # tr_obs.plot() # ------------------------------------------------------------------ seis = Seismogram(PRIOR, db) window_code = Source_code(PRIOR['VELOC_taup']) misfit = Misfit(VALUES['directory']) epi = PARAMETERS['epi'] depth = PARAMETERS['depth_s'] strike = PARAMETERS['strike'] dip = PARAMETERS['dip'] rake = PARAMETERS['rake'] time = PARAMETERS['origin_time'] # --------------------------------------------------------------------------------------------------------------- # dict = geo.Geodesic(a=PRIOR['radius'], f=0).ArcDirect(lat1=PRIOR['la_r'], lon1=PRIOR['lo_r'], azi1=PRIOR['baz'], a12=epi, outmask=1929) d_syn, traces_syn, sources = seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, strike=strike, dip=dip, rake=rake, time=time, M0=PRIOR['M0'], sdr=VALUES['sdr']) R_env_syn = sw.rayleigh_pick(Z_trace=traces_syn.traces[0], la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, save_directory=VALUES['directory'], time_at_rec=time, npts=VALUES['npts'], plot_modus=True) L_env_syn = sw.love_pick(T_trace=traces_syn.traces[2], la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, save_directory=VALUES['directory'], time_at_rec=time, npts=VALUES['npts'], plot_modus=False) traces_syn.plot(outfile=VALUES['directory'] + '/syntethic') total_syn, p_syn, s_syn, p_time_syn, s_time_syn = window_code.get_window_obspy( traces_syn, epi, depth, time, VALUES['npts']) ax1 = plt.subplot2grid((5, 1), (0, 0)) ax1.plot(zero_to_nan(p_syn.traces[0].data), c='r', linewidth=0.3) ax1.plot(zero_to_nan(p_obs.traces[0].data), c='k', linestyle=':', linewidth=0.3) plt.tight_layout() ax2 = plt.subplot2grid((5, 1), (1, 0)) ax2.plot(zero_to_nan(p_syn.traces[1].data), c='r', linewidth=0.3) ax2.plot(zero_to_nan(p_obs.traces[1].data), c='k', linestyle=':', linewidth=0.3) plt.tight_layout() ax3 = plt.subplot2grid((5, 1), (2, 0)) ax3.plot(zero_to_nan(s_syn.traces[0].data), c='r', linewidth=0.3) ax3.plot(zero_to_nan(s_obs.traces[0].data), c='k', linewidth=0.3) plt.tight_layout() ax4 = plt.subplot2grid((5, 1), (3, 0)) ax4.plot(zero_to_nan(s_syn.traces[1].data), c='r', linewidth=0.3) ax4.plot(zero_to_nan(s_obs.traces[1].data), c='k', linewidth=0.3) plt.tight_layout() ax5 = plt.subplot2grid((5, 1), (4, 0)) ax5.plot(zero_to_nan(s_syn.traces[2].data), c='r', linewidth=0.3) ax5.plot(zero_to_nan(s_obs.traces[2].data), c='k', linewidth=0.3) plt.tight_layout() plt.savefig(VALUES['directory'] + '/%.2f_%.2f.pdf' % (epi, depth)) plt.close() ax1 = plt.subplot2grid((3, 1), (0, 0)) ax1.plot(zero_to_nan(total_syn.traces[0].data), c='r', linewidth=0.5) ax1.plot(zero_to_nan(traces_obs.traces[0].data), c='k', linestyle=':', linewidth=0.5) ax1.set_title('SYNTHETIC: = epi: %.2f REAL: epi = %.2f (depth fixed' % (epi, epi)) plt.tight_layout() ax2 = plt.subplot2grid((3, 1), (1, 0)) ax2.plot(zero_to_nan(total_syn.traces[1].data), c='r', linewidth=0.5) ax2.plot(zero_to_nan(traces_obs.traces[1].data), c='k', linestyle=':', linewidth=0.5) plt.tight_layout() ax3 = plt.subplot2grid((3, 1), (2, 0)) ax3.plot(zero_to_nan(total_syn.traces[2].data), c='r', linewidth=0.5) ax3.plot(zero_to_nan(traces_obs.traces[2].data), c='k', linestyle=':', linewidth=0.5) plt.tight_layout() plt.savefig(VALUES['directory'] + '/PS_%.2f_%.2f.pdf' % (epi, depth)) plt.close() Xi_bw_new, time_shift_new, amplitude = misfit.CC_stream( p_obs, p_syn, s_obs, s_syn, p_time_obs, p_time_syn) s_z_new = 0.1 * Xi_bw_new[0] s_r_new = 0.1 * Xi_bw_new[1] s_t_new = 1 * Xi_bw_new[2] p_z_new = 5 * Xi_bw_new[3] p_r_new = 5 * Xi_bw_new[4] bw_new = s_z_new + s_r_new + s_t_new + p_z_new + p_r_new Xi_R_new = misfit.SW_L2(R_env_obs, R_env_syn, PRIOR['var_est'], amplitude) Xi_L_new = misfit.SW_L2(L_env_obs, L_env_syn, PRIOR['var_est'], amplitude) R_dict_new = {} rw_new = 0 for j, v in enumerate(Xi_R_new): R_dict_new.update({'R_%i_new' % j: v}) rw_new += v L_dict_new = {} lw_new = 0 for j, v in enumerate(Xi_L_new): L_dict_new.update({'L_%i_new' % j: v}) lw_new += v Xi_new = bw_new + rw_new + lw_new a = 1
def Acces_Blindtest_check(): BLINDTEST_MSEED = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Database/data_Nienke/M5.0_3914855_deg_2019-09-22.mseed' BLINDTEST_XML = BLINDTEST_MSEED.replace(".mseed", ".xml") # Initiate Parameters: get_parameters = Get_Paramters() PRIOR = get_parameters.get_prior() VALUES = get_parameters.specifications() VALUES['npts'] = 2000 VALUES[ 'directory'] = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Blindtest/check_waveforms' VALUES['blind'] = True # st = read(VALUES['directory'] + '/bw.mseed') # st_reject = read(VALUES['directory'] + '/bw_reject.mseed') # Initiate the databases from instaseis: db = instaseis.open_db(PRIOR['VELOC']) tr_obs = obspy.read(BLINDTEST_MSEED) # tr_obs.plot(outfile=VALUES['directory'] + '/Observed') tr_obs.integrate() tr_obs.plot(outfile=VALUES['directory'] + '/Observed_integrated') source = instaseis.Source.parse(BLINDTEST_XML) blindtest = Blindtest() events = blindtest.get_events(BLINDTEST_XML) # get_parameters.get_prior_blindtest(events[0]) time, depth, la_s, lo_s = blindtest.get_pref_origin(events[0]) dist, az, baz = gps2dist_azimuth(lat1=la_s, lon1=lo_s, lat2=PRIOR['la_r'], lon2=PRIOR['lo_r'], a=PRIOR['radius'], f=0) epi = kilometer2degrees(dist, radius=PRIOR['radius']) PRIOR['az'] = az PRIOR['baz'] = baz PRIOR['epi']['range_min'] = epi - 5 PRIOR['epi']['range_max'] = epi + 5 PRIOR['epi']['spread'] = 1 PRIOR['depth']['range_min'] = depth - 10000 PRIOR['depth']['range_max'] = depth + 10000 PRIOR['network'] = tr_obs.traces[0].meta.network PRIOR['location'] = tr_obs.traces[0].meta.location PRIOR['station'] = tr_obs.traces[0].meta.station est_noise = Create_observed(PRIOR, db) create = Source_code(PRIOR['VELOC_taup']) traces_obs, p_obs, s_obs, p_time_obs, s_time_obs = create.get_window_obspy( tr_obs, epi, depth, time, VALUES['npts']) PRIOR['var_est'] = est_noise.get_var_data(p_time_obs, tr_obs) obs_time = Create_observed(PRIOR, db) time_at_receiver = obs_time.get_receiver_time(epi, depth, time) plt.figure() catalog_path = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Additional_scripts/MQScatalog_withFrequencies/MQS_absolute_withFrequencyInfo.xml' events_catalog = blindtest.get_events(catalog_path) for v in events_catalog: t, d, lat_ev, lo_ev = blindtest.get_pref_origin(v) if time.date == t.date: Pick_event = v break PRIOR['M0'] = blindtest.get_pref_scalarmoment(Pick_event) picks_surface = get_phase_picks(Pick_event, pick_type='surface') R_env_obs, L_env_obs = blindtest.pick_sw(tr_obs, picks_surface, epi, PRIOR, VALUES['npts'], VALUES['directory'], plot_modus=True) start_sample = create_starting_sample() strike = 243.423396191 dip = 34.436087773 rake = 164.912874159 from Seismogram import Seismogram from Misfit import Misfit misfit = Misfit(VALUES['directory']) seis = Seismogram(PRIOR, db) epi = epi - 3 depth = depth # --------------------------------------------------------------------------------------------------------------- # dict = geo.Geodesic(a=PRIOR['radius'], f=0).ArcDirect(lat1=PRIOR['la_r'], lon1=PRIOR['lo_r'], azi1=PRIOR['baz'], a12=epi, outmask=1929) d_syn, traces_syn, sources = seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, strike=strike, dip=dip, rake=rake, time=time, M0=PRIOR['M0'], sdr=VALUES['sdr']) R_env_syn, L_env_syn = blindtest.pick_sw(traces_syn, picks_surface, epi, PRIOR, VALUES['npts'], VALUES['directory'], plot_modus=False) traces_syn.plot(outfile=VALUES['directory'] + '/syntethic') total_syn, p_syn, s_syn, p_time_syn, s_time_syn = create.get_window_obspy( traces_syn, epi, depth, time, VALUES['npts']) ax1 = plt.subplot2grid((5, 1), (0, 0)) ax1.plot(zero_to_nan(p_syn.traces[0].data), c='r', linewidth=0.3) ax1.plot(zero_to_nan(p_obs.traces[0].data), c='k', linestyle=':', linewidth=0.3) plt.tight_layout() ax2 = plt.subplot2grid((5, 1), (1, 0)) ax2.plot(zero_to_nan(p_syn.traces[1].data), c='r', linewidth=0.3) ax2.plot(zero_to_nan(p_obs.traces[1].data), c='k', linestyle=':', linewidth=0.3) plt.tight_layout() ax3 = plt.subplot2grid((5, 1), (2, 0)) ax3.plot(zero_to_nan(s_syn.traces[0].data), c='r', linewidth=0.3) ax3.plot(zero_to_nan(s_obs.traces[0].data), c='k', linewidth=0.3) plt.tight_layout() ax4 = plt.subplot2grid((5, 1), (3, 0)) ax4.plot(zero_to_nan(s_syn.traces[1].data), c='r', linewidth=0.3) ax4.plot(zero_to_nan(s_obs.traces[1].data), c='k', linewidth=0.3) plt.tight_layout() ax5 = plt.subplot2grid((5, 1), (4, 0)) ax5.plot(zero_to_nan(s_syn.traces[2].data), c='r', linewidth=0.3) ax5.plot(zero_to_nan(s_obs.traces[2].data), c='k', linewidth=0.3) plt.tight_layout() plt.savefig(VALUES['directory'] + '/%.2f_%.2f.pdf' % (epi, depth)) plt.close() # time = ax1 = plt.subplot2grid((3, 1), (0, 0)) ax1.plot(zero_to_nan(total_syn.traces[0].data), c='r', linewidth=0.5) ax1.plot(zero_to_nan(traces_obs.traces[0].data), c='k', linestyle=':', linewidth=0.5) ax1.set_title('SYNTHETIC: = epi: %.2f REAL: epi = %.2f (depth fixed' % (epi, epi + 3)) plt.tight_layout() ax2 = plt.subplot2grid((3, 1), (1, 0)) ax2.plot(zero_to_nan(total_syn.traces[1].data), c='r', linewidth=0.5) ax2.plot(zero_to_nan(traces_obs.traces[1].data), c='k', linestyle=':', linewidth=0.5) plt.tight_layout() ax3 = plt.subplot2grid((3, 1), (2, 0)) ax3.plot(zero_to_nan(total_syn.traces[2].data), c='r', linewidth=0.5) ax3.plot(zero_to_nan(traces_obs.traces[2].data), c='k', linestyle=':', linewidth=0.5) plt.tight_layout() plt.savefig(VALUES['directory'] + '/PS_%.2f_%.2f.pdf' % (epi, depth)) plt.close() Xi_bw_new, time_shift_new, amplitude = misfit.CC_stream( p_obs, p_syn, s_obs, s_syn, p_time_obs, p_time_syn) s_z_new = 0.1 * Xi_bw_new[0] s_r_new = 0.1 * Xi_bw_new[1] s_t_new = 1 * Xi_bw_new[2] p_z_new = 5 * Xi_bw_new[3] p_r_new = 5 * Xi_bw_new[4] bw_new = s_z_new + s_r_new + s_t_new + p_z_new + p_r_new Xi_R_new = misfit.SW_L2(R_env_obs, R_env_syn, PRIOR['var_est'], amplitude) Xi_L_new = misfit.SW_L2(L_env_obs, L_env_syn, PRIOR['var_est'], amplitude) R_dict_new = {} rw_new = 0 for j, v in enumerate(Xi_R_new): R_dict_new.update({'R_%i_new' % j: v}) rw_new += v L_dict_new = {} lw_new = 0 for j, v in enumerate(Xi_L_new): L_dict_new.update({'L_%i_new' % j: v}) lw_new += v Xi_new = bw_new + rw_new + lw_new a = 1
import geographiclib.geodesic as geo import matplotlib.pyplot as plt import math as m a = 1 calc = geo.Geodesic(a, 0.5) initLat = 0 initLon = 0 finalLat = 0 finalLon = 175 numDiv = 100 l = calc.InverseLine(lat1=initLat, lon1=initLon, lat2=finalLat, lon2=finalLon) increment = l.s13 / numDiv lat = initLat lon = initLon x_data = [] y_data = [] s = 0 lats = [] lons = [] for i in range(numDiv + 1): g = l.Position(s) lat = m.radians(g.get("lat2")) r = a * (1 - m.sin(lat)) # esse cálculo não está correto!!! lon = m.radians(g.get("lon2")) x = a - r * m.cos(lon) y = a - r * m.sin(lon) x_data.append(x) y_data.append(y)
def G_function(self, epi, depth, M0, moment_old=None): if moment_old is None: strike, dip, rake = self.model_samples_sdr() else: strike, dip, rake = self.model_samples_sdr(moment_old[0], moment_old[1], moment_old[2]) # epi =45.9233274286 # depth = 10000 # strike = 79 # dip = 50 # rake = 20 # strike = moment_old[0] # dip = moment_old[1] # rake = moment_old[2] # epi = 35.2068855191 # depth = 16848.1405882 dict = geo.Geodesic(a=self.prior['radius'], f=0).ArcDirect(lat1=self.prior['la_r'], lon1=self.prior['lo_r'], azi1=self.prior['baz'], a12=epi, outmask=1929) d_syn, traces_syn, sources = self.seis.get_seis_manual( la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, strike=strike, dip=dip, rake=rake, time=self.time_at_rec, M0=M0, sdr=self.sdr) # 3.16227766016798e+16 if self.blind == True: R_env_syn, L_env_syn = self.BT.pick_sw(traces_syn, self.picks, epi, self.prior, 30000, self.directory, plot_modus=False) else: R_env_syn = self.SW.rayleigh_pick(Z_trace=traces_syn.traces[0], la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, save_directory=self.directory, time_at_rec=self.time_at_rec, npts=self.npts, plot_modus=False) L_env_syn = self.SW.love_pick(T_trace=traces_syn.traces[2], la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, save_directory=self.directory, time_at_rec=self.time_at_rec, npts=self.npts, plot_modus=False) # traces_syn.plot(outfile=self.directory + '/syntethic') total_syn, p_syn, s_syn, start_time_p, start_time_s = self.window.get_window_obspy( traces_syn, epi, depth, self.time_at_rec, self.npts) # # plot_obs = self.full_obs_trace.copy() # plot_obs.trim(traces_syn.traces[0].meta.starttime, traces_syn.traces[0].meta.endtime) # if self.iter % 10 == 0: # for i in range(len(self.full_obs_trace)): # subplot_no = len(self.full_obs_trace) * 100 + 10 + i + 1 # if i < 3: # P_obs = int( # (self.P_Start.timestamp - traces_syn.traces[ # i].meta.starttime.timestamp) / traces_syn.traces[i].meta.delta) # P_syn = int( # (start_time_p.timestamp - traces_syn.traces[ # i].meta.starttime.timestamp) / traces_syn.traces[i].meta.delta) # S_obs = int( # (self.S_start.timestamp - traces_syn.traces[ # i].meta.starttime.timestamp) / traces_syn.traces[i].meta.delta) # # S_syn = int( # (start_time_s.timestamp - traces_syn.traces[ # i].meta.starttime.timestamp) / traces_syn.traces[i].meta.delta) # ax = plt.subplot(subplot_no) # plt.plot(plot_obs.traces[i].data, alpha=0.5, c='k', linewidth=0.3) # plt.plot(traces_syn.traces[i].data, alpha=0.5, c='r', linewidth=0.3) # ymin, ymax = ax.get_ylim() # if i < 3: # plt.vlines([P_obs], ymin, ymax, label="Observed", colors='k', linewidth=0.3) # plt.vlines([P_syn], ymin, ymax, label="synthetic", colors='r', linewidth=0.3) # plt.vlines([S_obs], ymin, ymax, label="Observed", colors='k', linewidth=0.3) # plt.vlines([S_syn], ymin, ymax, label="synthetic", colors='r', linewidth=0.3) # plt.xlabel(self.time_at_rec.strftime('%Y-%m-%dT%H:%M:%S + sec')) # plt.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # plt.tight_layout() # # # plt.savefig(self.directory + '/P_S_Picks_%i.pdf' %self.iter) # plt.show() # plt.close() return R_env_syn, L_env_syn, total_syn, p_syn, s_syn, np.array( [strike, dip, rake]), start_time_p
def memoPoligonPA(filestr, shpname='memopa', crs=None, geodesic=True, cfile=True, verbose=False, saveshape=True, wincpp=True, verdadeiro=True, tolerance=1e-6, snap_points=[], snap_dist=10.): """ Cria sequencia de vertices a partir de string de arquivo texto de memorial descritivo da poligonal de requerimento usando ponto de amarração. Vertices output em SIRGAS 2000. crs: crs do memorial default p/ SAD69(96) prj4 string based on https://wiki.osgeo.org/wiki/Brazilian_Coordinate_Reference_Systems#Ellipsoids_in_use .... snap_points: list [ [lat, lon] ] snap coordinate considering `snap_dist` to ONLY ONE point and recalculate walking vertices TODO: implement for 2/3 ... more points geodesic: default True - calculos geodésicos False - calculos planimetricos UTM projetado ### Calculos Geodésicos - SIGAREAS/SCM Usa pacote Geographiclib (Charles F. F. Karney) p/ calculos e distâncias, azimutes geodesicos (isso é direto no elipsoide) usa matemática esférica/elipsoidal para calculo direto ou inverso. ### Calculos Planimetricos Utiliza pacote Pyproj/PRJ4 para projeção em UTM e calculo distâncias. azimutes considerando o norte do GRID UTM. ### Transformações entre datuns Transformaçao de coordenadas entre datuns utilizando pacote Pyproj/PRJ4. Testado dando resultados identicos ao do site INPE Calculadora http://www.dpi.inpe.br/calcula/ Mais precisos que o CONVNAV. Testado contra o CONVNAV dandos resultados na ordem em média < 1 metro de diferença. Quase certeza que é diferença de abordagem provavelmente na hora de contruir a navegação. CONVNAV mantem longitude constante quando N, S rumos verdadeiros. cfile: default True Cria arquivo COORDS.txt adequado para inserir no SIGAREAS->Administrador->Inserir Poligonal wincpp : default True use geographiclib compiled on windows/pybind11 vstudio by Andre 8th order verdadeiro: default True force 'rumos verdadeiros' force decimal coordinates lat, lon to repeat last lat, lon tolerance: default 1e-6 (decimal degrees) diference to previous lat or lon to force 'verdadeiro' option WARNING: If navigation is very detailed this parameter may change it COMPLETELY Conforme Emilio todo o banco de dados do SCM foi convertido considerando que os dados já estavam no datum SAD69(96). Exemplos: 1. Com rumos verdadeiros -20 14 14 3 # latitude do Ponto de Amarração -43 52 50 2 # longitude do Ponto de Amarração 1000 SW 75 15 # distancia (metros) direção grau-minutos para o primeiro vértice 2200 E # incremento direcional a partir do primeiro vértice 1350 S 2200 W 1350 N 2. Com rumos diversos -20 16 38 4 -43 55 15 0 4836 NE 51 12 286 NW 00 00 302 SE 90 00 140 NW 00 00 Aproximadamente 0.001 (1 mm) walk changes 8 casa ou 10-8 grau decimal. """ wincpp = wincpp if crs is not None: crs = CRS(crs) else: # older sad69 #crs = CRS('+proj=longlat +ellps=aust_SA +towgs84=-66.87,4.37,-38.52,0,0,0,0 +no_defs') crs = CRS(CRS_SAD69_96) # sad69(96) lat lon print("Input CRS: ", crs) lines = filestr.split('\n') # PA information latpa = get_graus(lines[0]) lonpa = get_graus(lines[1]) print("Input lat, lon : {:.8f} {:.8f} {:}".format(latpa, lonpa, 'SAD69(96)')) print("lat {:} {:} {:} {:} | lon {:} {:} {:} {:}".format( *decdeg2dmsd(latpa), *decdeg2dmsd(lonpa))) # convert PA geografica de datum de SAD69(96) para SIRGAS 2000 # conforme Emilio todo o banco de dados do SCM foi convertido # considerando que os dados eram SAD69(96) sirgas = CRS_SIRGAS2000 tosirgas = Transformer.from_crs(crs, sirgas) lonpa, latpa = tosirgas.transform(lonpa, latpa) print("Input lat, lon: {:.8f} {:.8f} {:}".format(latpa, lonpa, 'SIRGAS2000')) print("lat {:} {:} {:} {:} | lon {:} {:} {:} {:}".format( *decdeg2dmsd(latpa), *decdeg2dmsd(lonpa))) # Projection transformation # get adequate UTM zone by using the simple equation # 1 + np.floor((-44 + 180)/6) % 60 zone = 1 + np.floor((lonpa + 180) / 6) % 60 utm_crs = CRS( "+proj=utm +zone={:} +south +units=m +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +no_defs" .format(zone)) # custom CRS LTM primeiro vertice # utm_crs = """+proj=tmerc +ellps=WGS84 +datum=WGS84 +units=m +no_defs +lon_0={:} +x_0=50000 +y_0=0 +k_0=0.9996 #+towgs84=0,0,0,0,0,0,0""".format(lonpa) # Lambert Azimuthal Equal Area # utm_crs = """+proj=laea +ellps=WGS84 +datum=WGS84 +units=m +no_defs +lon_0={:} +lat_0={:} +x_0=0 +y_0=0 +towgs84=0,0,0,0,0,0,0""".format(lonpa, latpa) if not geodesic: print("PRJ4 string UTM:", utm_crs) proj = Transformer.from_crs(sirgas, utm_crs) deproj = Transformer.from_crs(utm_crs, sirgas) # Deprojection # read all lines of segments defining the polygon # assumed clockwise directions_xy = [] directions_az = [] lines = lines[3:] idx = 0 print("First vertex at index 1, 0 is PA") for line in lines: dist, quad, angle = memoLineRead(line) azimuth = getazimuth(quad, angle) dx, dy = projectxy(dist, quad, angle) directions_xy.append([dx, dy]) directions_az.append([dist, azimuth]) print( "{:3d} : {:>+9.3f} {:>5} {:>+7.2f} {:>+7.2f} {:>+9.2f} {:>+9.2f}". format(idx, dist, quad.ljust(5), angle, azimuth, dx, dy)) idx += 1 vertices_dg = [] vertices_utm = [] if geodesic: # geodesic calculations # go to first vertex # assume clockwise, assume closed polygon otherwise BROKE first_vertex = geodesic_walk((latpa, lonpa), directions_az[:1])[1] # ignora PA not vertex, remove from directions also directions_az = directions_az[1:] vertices_dg = geodesic_poly_walk(first_vertex, directions_az, 0) rsnap_points = [] # new reference points from snapping points if snap_points: for spoint in snap_points: # list of lat, lon points for i in range(len(vertices_dg)): distance = GeoInverseWGS84(*spoint, *vertices_dg[i]) #print(distance) if (distance < snap_dist): print( "Snaping: distance from snap-vertex : Lat {:>4.8f} Lon {:>4.8f} to " "vertex : {:>3d} is {:>5.3f} m".format( *spoint, i, distance)) #print("accept?") rsnap_points.append([i, spoint]) if rsnap_points: # at least one acceptable snap_point print("Recalculating vertices") if len(rsnap_points) == 1: vertices_dg = geodesic_poly_walk(rsnap_points[0][1], directions_az, rsnap_points[0][0]) # create UTM equivalents for vertex in vertices_dg: utmx, utmy = proj.transform(vertex[1], vertex[0]) vertices_utm += [utmx, utmy] print("UTM X {:10.3f} Y {:10.3f} Lat {:4.8f} Lon {:4.8f}".format( utmx, utmy, vertex[0], vertex[1])) else: # planimetric calculations xpa, ypa = proj.transform(lonpa, latpa) cx, cy = xpa, ypa for segment in directions_xy: dx, dy = segment cx += dx cy += dy vertices_utm.append([cx, cy]) for vertex in vertices_utm: lon, lat = deproj.transform(vertex[0], vertex[1]) vertices_dg.append([lat, lon]) print("UTM X {:10.3f} Y {:10.3f} Lat {:4.8f} Lon {:4.8f}".format( vertex[0], vertex[1], lat, lon)) if verdadeiro: # force verdadeiro vertices_dg = force_verd(vertices_dg, tolerance).tolist() if cfile: fformatPoligonal(vertices_dg, verbose=verbose, endfirst=True) # Create polygon shape file if saveshape: savePolygonWGS84(vertices_dg, shpname) gdfvs = gp.GeoSeries(list(map(Point, vertices_dg)), index=np.arange(len(vertices_dg))) gdfvs.set_crs(pyproj.CRS(CRS_SIRGAS2000)) # SIRGAS 2000 gdfvs.to_file(shpname + 'points.shp') if verbose: elipsoide = gd.Geodesic(gd.Constants.WGS84_a, gd.Constants.WGS84_f) # same as SIRGAS poly = pa.PolygonArea(elipsoide) for p in vertices_dg: poly.AddPoint(*p) poly.Compute(True) py_num, py_perim, py_area = poly.Compute(True) py_area = py_area * 10**(-4) # to hectares print("nvertices {:} area {:>9.8f} perimeter {:>9.8f}".format( py_num, py_area, py_perim)) return vertices_dg, vertices_utm
from collections import namedtuple from enum import Enum from math import floor import numpy as np from geographiclib import geodesic WGS84 = geodesic.Geodesic(geodesic.Constants.WGS84_a, geodesic.Constants.WGS84_f) LongLat = namedtuple("LongLat", "long lat") """Longitude and latitude always get reversed, so use this to help.""" class Direction(Enum): North = 0 East = 90 South = 180 West = 270 def pixel_containing(point, geo_transform): """ Which pixel has this long-lat? This version won't work if there is shear. To implement it with shear, turn this into homogeneous coordinates and invert the geo_transform. Args: point: A point in longitude and latitude. geo_transform: Six points for a transformation with shear. Returns:
## Step 2 - Parameters = epi,depth # For now the epi,depth,time are using the exact same values as the prior, because I wanted to test my code epi = PARAMETERS['epi'] depth = PARAMETERS['depth_s'] ## Step 3 - Parameters = Strike,dip,rake strike = PARAMETERS['strike'] dip = PARAMETERS['dip'] rake = PARAMETERS['rake'] ## Step 4 - Calculate d_syn with the use of get_seismogram (from instaseis) seis = Seismogram(PRIOR, db) window_code = Source_code(PRIOR['VELOC_taup']) dict = geo.Geodesic(a=PRIOR['radius'], f=0).ArcDirect(lat1=PRIOR['la_r'], lon1=PRIOR['lo_r'], azi1=PRIOR['baz'], a12=epi, outmask=1929) # FULL seismogram # d_obs = stacked numpy array of the seismogram # traces = obspy stream with 3 traces [Z,R,T] # source = instaseis source d_syn, tr_syn, sources = seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth, strike=strike, dip=dip, rake=rake, time=time_at_receiver, sdr=True)